Compare commits
6 Commits
secrets-0.
...
secrets-0.
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1f7984d798 | ||
|
|
140162f39a | ||
|
|
535683b15c | ||
|
|
9620ff1923 | ||
|
|
e6db23bd6d | ||
|
|
c61c8292aa |
@@ -128,71 +128,6 @@ jobs:
|
||||
echo "release_id=" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
probe-runners:
|
||||
name: 探测 Runner
|
||||
runs-on: debian
|
||||
outputs:
|
||||
has_linux: ${{ steps.probe.outputs.has_linux }}
|
||||
has_macos: ${{ steps.probe.outputs.has_macos }}
|
||||
has_windows: ${{ steps.probe.outputs.has_windows }}
|
||||
steps:
|
||||
- name: 查询可用 Runner
|
||||
id: probe
|
||||
env:
|
||||
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
run: |
|
||||
fallback_all() {
|
||||
echo "has_linux=true" >> "$GITHUB_OUTPUT"
|
||||
echo "has_macos=true" >> "$GITHUB_OUTPUT"
|
||||
echo "has_windows=true" >> "$GITHUB_OUTPUT"
|
||||
}
|
||||
|
||||
if [ -z "$RELEASE_TOKEN" ]; then
|
||||
echo "未配置 RELEASE_TOKEN,默认尝试所有平台"
|
||||
fallback_all; exit 0
|
||||
fi
|
||||
|
||||
command -v jq >/dev/null 2>&1 || (sudo apt-get update -qq && sudo apt-get install -y -qq jq)
|
||||
|
||||
http_code=$(curl -sS -o /tmp/runners.json -w '%{http_code}' \
|
||||
-H "Authorization: token $RELEASE_TOKEN" \
|
||||
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/actions/runners")
|
||||
|
||||
if [ "$http_code" != "200" ]; then
|
||||
echo "Runner API 返回 HTTP ${http_code},默认尝试所有平台"
|
||||
fallback_all; exit 0
|
||||
fi
|
||||
|
||||
has_runner() {
|
||||
local label="$1"
|
||||
jq -e --arg label "$label" '
|
||||
(.runners // .data // . // [])
|
||||
| any(
|
||||
(
|
||||
(.online == true)
|
||||
or (
|
||||
((.status // "") | ascii_downcase)
|
||||
| IN("online", "idle", "busy", "active")
|
||||
)
|
||||
)
|
||||
and (
|
||||
(.labels // [])
|
||||
| map(if type == "object" then (.name // .label // "") else tostring end | ascii_downcase)
|
||||
| index($label)
|
||||
) != null
|
||||
)
|
||||
' /tmp/runners.json >/dev/null
|
||||
}
|
||||
|
||||
for pair in "debian:has_linux" "darwin-arm64:has_macos" "windows:has_windows"; do
|
||||
label="$(printf '%s' "${pair%%:*}" | tr '[:upper:]' '[:lower:]')"; key="${pair##*:}"
|
||||
if has_runner "$label"; then
|
||||
echo "${key}=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "${key}=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
done
|
||||
|
||||
check:
|
||||
name: 质量检查 (fmt / clippy / test)
|
||||
runs-on: debian
|
||||
@@ -227,10 +162,9 @@ jobs:
|
||||
|
||||
build-linux:
|
||||
name: Build (x86_64-unknown-linux-musl)
|
||||
needs: [version, probe-runners, check]
|
||||
if: needs.probe-runners.outputs.has_linux == 'true'
|
||||
needs: [version, check]
|
||||
runs-on: debian
|
||||
timeout-minutes: 1
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: 安装依赖
|
||||
run: |
|
||||
@@ -274,12 +208,31 @@ jobs:
|
||||
-F "attachment=@${archive}" \
|
||||
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${{ needs.version.outputs.release_id }}/assets"
|
||||
|
||||
- name: 飞书通知
|
||||
if: always()
|
||||
env:
|
||||
WEBHOOK_URL: ${{ vars.WEBHOOK_URL }}
|
||||
run: |
|
||||
[ -z "$WEBHOOK_URL" ] && exit 0
|
||||
command -v jq >/dev/null 2>&1 || (sudo apt-get update -qq && sudo apt-get install -y -qq jq)
|
||||
tag="${{ needs.version.outputs.tag }}"
|
||||
commit=$(git log -1 --pretty=format:"%s" 2>/dev/null || echo "N/A")
|
||||
url="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}"
|
||||
result="${{ job.status }}"
|
||||
if [ "$result" = "success" ]; then icon="✅"; else icon="❌"; fi
|
||||
msg="secrets linux 构建${icon}
|
||||
版本:${tag}
|
||||
提交:${commit}
|
||||
作者:${{ github.actor }}
|
||||
详情:${url}"
|
||||
payload=$(jq -n --arg text "$msg" '{msg_type: "text", content: {text: $text}}')
|
||||
curl -sS -H "Content-Type: application/json" -X POST -d "$payload" "$WEBHOOK_URL"
|
||||
|
||||
build-macos:
|
||||
name: Build (aarch64-apple-darwin)
|
||||
needs: [version, probe-runners, check]
|
||||
if: needs.probe-runners.outputs.has_macos == 'true'
|
||||
needs: [version, check]
|
||||
runs-on: darwin-arm64
|
||||
timeout-minutes: 1
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: 安装依赖
|
||||
run: |
|
||||
@@ -321,12 +274,30 @@ jobs:
|
||||
-F "attachment=@${archive}" \
|
||||
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${{ needs.version.outputs.release_id }}/assets"
|
||||
|
||||
- name: 飞书通知
|
||||
if: always()
|
||||
env:
|
||||
WEBHOOK_URL: ${{ vars.WEBHOOK_URL }}
|
||||
run: |
|
||||
[ -z "$WEBHOOK_URL" ] && exit 0
|
||||
tag="${{ needs.version.outputs.tag }}"
|
||||
commit=$(git log -1 --pretty=format:"%s" 2>/dev/null || echo "N/A")
|
||||
url="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}"
|
||||
result="${{ job.status }}"
|
||||
if [ "$result" = "success" ]; then icon="✅"; else icon="❌"; fi
|
||||
msg="secrets macOS 构建${icon}
|
||||
版本:${tag}
|
||||
提交:${commit}
|
||||
作者:${{ github.actor }}
|
||||
详情:${url}"
|
||||
payload=$(python3 -c "import json,sys; print(json.dumps({'msg_type':'text','content':{'text':sys.argv[1]}}))" "$msg")
|
||||
curl -sS -H "Content-Type: application/json" -X POST -d "$payload" "$WEBHOOK_URL"
|
||||
|
||||
build-windows:
|
||||
name: Build (x86_64-pc-windows-msvc)
|
||||
needs: [version, probe-runners, check]
|
||||
if: needs.probe-runners.outputs.has_windows == 'true'
|
||||
needs: [version, check]
|
||||
runs-on: windows
|
||||
timeout-minutes: 1
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: 安装依赖
|
||||
shell: pwsh
|
||||
@@ -372,34 +343,43 @@ jobs:
|
||||
-Headers @{ "Authorization" = "token $env:RELEASE_TOKEN" } `
|
||||
-Form @{ attachment = Get-Item $archive }
|
||||
|
||||
- name: 飞书通知
|
||||
if: always()
|
||||
shell: pwsh
|
||||
env:
|
||||
WEBHOOK_URL: ${{ vars.WEBHOOK_URL }}
|
||||
run: |
|
||||
if (-not $env:WEBHOOK_URL) { exit 0 }
|
||||
$tag = "${{ needs.version.outputs.tag }}"
|
||||
$commit = (git log -1 --pretty=format:"%s" 2>$null) ?? "N/A"
|
||||
$url = "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}"
|
||||
$result = "${{ job.status }}"
|
||||
$icon = if ($result -eq "success") { "✅" } else { "❌" }
|
||||
$msg = "secrets windows 构建${icon}`n版本:${tag}`n提交:${commit}`n作者:${{ github.actor }}`n详情:${url}"
|
||||
$payload = @{ msg_type = "text"; content = @{ text = $msg } } | ConvertTo-Json
|
||||
Invoke-RestMethod -Uri $env:WEBHOOK_URL -Method Post `
|
||||
-ContentType "application/json" -Body $payload
|
||||
|
||||
publish-release:
|
||||
name: 发布草稿 Release
|
||||
needs: [version, check, build-linux, build-macos, build-windows]
|
||||
needs: [version, build-linux]
|
||||
if: always() && needs.version.outputs.release_id != ''
|
||||
runs-on: debian
|
||||
timeout-minutes: 2
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: 发布草稿
|
||||
env:
|
||||
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
run: |
|
||||
[ -z "$RELEASE_TOKEN" ] && exit 0
|
||||
|
||||
version_r="${{ needs.version.result }}"
|
||||
check_r="${{ needs.check.result }}"
|
||||
linux_r="${{ needs.build-linux.result }}"
|
||||
macos_r="${{ needs.build-macos.result }}"
|
||||
windows_r="${{ needs.build-windows.result }}"
|
||||
|
||||
for result in "$version_r" "$check_r" "$linux_r" "$macos_r" "$windows_r"; do
|
||||
case "$result" in
|
||||
success|skipped) ;;
|
||||
*)
|
||||
echo "存在失败或取消的 job,保留草稿 Release"
|
||||
exit 0
|
||||
;;
|
||||
esac
|
||||
done
|
||||
if [ "$linux_r" != "success" ]; then
|
||||
echo "Linux 构建未成功 (${linux_r}),保留草稿 Release"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
release_api="${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${{ needs.version.outputs.release_id }}"
|
||||
http_code=$(curl -sS -o /tmp/publish-release.json -w '%{http_code}' \
|
||||
@@ -413,18 +393,10 @@ jobs:
|
||||
cat /tmp/publish-release.json 2>/dev/null || true
|
||||
exit 1
|
||||
fi
|
||||
echo "Release 已发布"
|
||||
|
||||
notify:
|
||||
name: 通知
|
||||
needs: [version, probe-runners, check, build-linux, build-macos, build-windows, publish-release]
|
||||
if: always() && github.event_name == 'push'
|
||||
runs-on: debian
|
||||
timeout-minutes: 1
|
||||
continue-on-error: true
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: 发送飞书通知
|
||||
- name: 飞书汇总通知
|
||||
if: always()
|
||||
env:
|
||||
WEBHOOK_URL: ${{ vars.WEBHOOK_URL }}
|
||||
run: |
|
||||
@@ -436,43 +408,29 @@ jobs:
|
||||
commit=$(git log -1 --pretty=format:"%s" 2>/dev/null || echo "N/A")
|
||||
url="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}"
|
||||
|
||||
version_r="${{ needs.version.result }}"
|
||||
check_r="${{ needs.check.result }}"
|
||||
check_r="${{ needs.version.result }}"
|
||||
linux_r="${{ needs.build-linux.result }}"
|
||||
macos_r="${{ needs.build-macos.result }}"
|
||||
windows_r="${{ needs.build-windows.result }}"
|
||||
publish_r="${{ needs.publish-release.result }}"
|
||||
publish_r="${{ job.status }}"
|
||||
|
||||
if [ "$version_r" = "success" ] && [ "$check_r" = "success" ] \
|
||||
&& [ "$linux_r" != "failure" ] && [ "$linux_r" != "cancelled" ] \
|
||||
&& [ "$macos_r" != "failure" ] && [ "$macos_r" != "cancelled" ] \
|
||||
&& [ "$windows_r" != "failure" ] && [ "$windows_r" != "cancelled" ] \
|
||||
&& [ "$publish_r" != "failure" ] && [ "$publish_r" != "cancelled" ]; then
|
||||
status="构建成功 ✅"
|
||||
else
|
||||
icon() { case "$1" in success) echo "✅";; skipped) echo "⏭";; *) echo "❌";; esac; }
|
||||
|
||||
if [ "$linux_r" = "success" ] && [ "$publish_r" = "success" ]; then
|
||||
status="发布成功 ✅"
|
||||
elif [ "$linux_r" != "success" ]; then
|
||||
status="构建失败 ❌"
|
||||
fi
|
||||
|
||||
icon() {
|
||||
case "$1" in
|
||||
success) echo "✅" ;;
|
||||
skipped) echo "⏭" ;;
|
||||
*) echo "❌" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
msg="${{ env.BINARY_NAME }} ${status}"
|
||||
if [ "$tag_exists" = "false" ]; then
|
||||
msg="${msg}
|
||||
🆕 新版本 ${tag}"
|
||||
else
|
||||
msg="${msg}
|
||||
🔄 重复构建 ${tag}"
|
||||
status="发布失败 ❌"
|
||||
fi
|
||||
|
||||
msg="${msg}
|
||||
构建结果:linux$(icon "$linux_r") macOS$(icon "$macos_r") windows$(icon "$windows_r")
|
||||
Release:$(icon "$publish_r")
|
||||
if [ "$tag_exists" = "false" ]; then
|
||||
version_line="🆕 新版本 ${tag}"
|
||||
else
|
||||
version_line="🔄 重复构建 ${tag}"
|
||||
fi
|
||||
|
||||
msg="secrets ${status}
|
||||
${version_line}
|
||||
linux $(icon "$linux_r") | Release $(icon "$publish_r")
|
||||
提交:${commit}
|
||||
作者:${{ github.actor }}
|
||||
详情:${url}"
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,3 +1,4 @@
|
||||
/target
|
||||
.env
|
||||
.DS_Store
|
||||
.DS_Store
|
||||
.cursor/
|
||||
44
.vscode/tasks.json
vendored
44
.vscode/tasks.json
vendored
@@ -25,12 +25,36 @@
|
||||
"command": "./target/debug/secrets help add",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "cli: help config",
|
||||
"type": "shell",
|
||||
"command": "./target/debug/secrets help config",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "cli: config path",
|
||||
"type": "shell",
|
||||
"command": "./target/debug/secrets config path",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "cli: config show",
|
||||
"type": "shell",
|
||||
"command": "./target/debug/secrets config show",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "test: search all",
|
||||
"type": "shell",
|
||||
"command": "./target/debug/secrets search",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "test: search all (verbose)",
|
||||
"type": "shell",
|
||||
"command": "./target/debug/secrets --verbose search",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "test: search by namespace (refining)",
|
||||
"type": "shell",
|
||||
@@ -82,7 +106,7 @@
|
||||
{
|
||||
"label": "test: search with secrets revealed",
|
||||
"type": "shell",
|
||||
"command": "./target/debug/secrets search -n refining --kind service --name gitea --show-secrets",
|
||||
"command": "./target/debug/secrets search -n refining --kind service --show-secrets",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
@@ -97,6 +121,24 @@
|
||||
"command": "echo '--- add ---' && ./target/debug/secrets add -n test --kind demo --name roundtrip-test --tag test -m foo=bar -s password=secret123 && echo '--- search ---' && ./target/debug/secrets search -n test --show-secrets && echo '--- delete ---' && ./target/debug/secrets delete -n test --kind demo --name roundtrip-test && echo '--- verify deleted ---' && ./target/debug/secrets search -n test",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "test: add + delete roundtrip (verbose)",
|
||||
"type": "shell",
|
||||
"command": "echo '--- add (verbose) ---' && ./target/debug/secrets --verbose add -n test --kind demo --name roundtrip-verbose --tag test -m foo=bar -s password=secret123 && echo '--- delete (verbose) ---' && ./target/debug/secrets --verbose delete -n test --kind demo --name roundtrip-verbose",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "test: update roundtrip",
|
||||
"type": "shell",
|
||||
"command": "echo '--- add ---' && ./target/debug/secrets add -n test --kind demo --name update-test --tag v1 -m env=staging && echo '--- update ---' && ./target/debug/secrets update -n test --kind demo --name update-test --add-tag v2 --remove-tag v1 -m env=production && echo '--- verify ---' && ./target/debug/secrets search -n test --kind demo && echo '--- cleanup ---' && ./target/debug/secrets delete -n test --kind demo --name update-test",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "test: audit log",
|
||||
"type": "shell",
|
||||
"command": "echo '--- add ---' && ./target/debug/secrets add -n test --kind demo --name audit-test -m foo=bar -s key=val && echo '--- update ---' && ./target/debug/secrets update -n test --kind demo --name audit-test -m foo=baz && echo '--- delete ---' && ./target/debug/secrets delete -n test --kind demo --name audit-test && echo '--- audit log (last 5) ---' && psql $DATABASE_URL -c \"SELECT action, namespace, kind, name, actor, detail, created_at FROM audit_log ORDER BY created_at DESC LIMIT 5;\"",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "test: add with file secret",
|
||||
"type": "shell",
|
||||
|
||||
266
AGENTS.md
266
AGENTS.md
@@ -7,27 +7,31 @@
|
||||
```
|
||||
secrets/
|
||||
src/
|
||||
main.rs # CLI 入口,clap 命令定义,auto-migrate
|
||||
db.rs # PgPool 创建 + 建表/索引(幂等)
|
||||
main.rs # CLI 入口,clap 命令定义,auto-migrate,--verbose 全局参数
|
||||
output.rs # OutputMode 枚举 + TTY 检测(TTY→text,非 TTY→json-compact)
|
||||
config.rs # 配置读写:~/.config/secrets/config.toml(database_url)
|
||||
db.rs # PgPool 创建 + 建表/索引(幂等,含 audit_log)
|
||||
models.rs # Secret 结构体(sqlx::FromRow + serde)
|
||||
audit.rs # 审计写入:向 audit_log 表记录所有写操作
|
||||
commands/
|
||||
add.rs # add 命令:upsert,支持 --meta key=value / --secret key=@file
|
||||
search.rs # search 命令:多条件动态查询
|
||||
add.rs # add 命令:upsert,支持 --meta key=value / --secret key=@file / -o json
|
||||
config.rs # config 命令:set-db / show / path(持久化 database_url)
|
||||
search.rs # search 命令:多条件查询,-f/-o/--summary/--limit/--offset/--sort
|
||||
delete.rs # delete 命令
|
||||
update.rs # update 命令:增量更新(合并 tags/metadata/encrypted)
|
||||
scripts/
|
||||
seed-data.sh # 从 refining/ricnsmart config.toml 导入全量数据
|
||||
.gitea/workflows/
|
||||
secrets.yml # CI:fmt + clippy + musl 构建 + Release 上传 + 飞书通知
|
||||
.vscode/tasks.json # 本地测试任务(build / search / add+delete roundtrip 等)
|
||||
.env # DATABASE_URL(gitignore,不提交)
|
||||
.vscode/tasks.json # 本地测试任务(build / config / search / add+delete / update / audit 等)
|
||||
```
|
||||
|
||||
## 数据库
|
||||
|
||||
- **Host**: `47.117.131.22:5432`(阿里云上海 ECS,PostgreSQL 18 with io_uring)
|
||||
- **Host**: `<host>:<port>`
|
||||
- **Database**: `secrets`
|
||||
- **连接串**: `postgres://postgres:<password>@47.117.131.22:5432/secrets`
|
||||
- **表**: 单张 `secrets` 表,首次连接自动建表(auto-migrate)
|
||||
- **连接串**: `postgres://postgres:<password>@<host>:<port>/secrets`
|
||||
- **表**: `secrets`(主表)+ `audit_log`(审计表),首次连接自动建表(auto-migrate)
|
||||
|
||||
### 表结构
|
||||
|
||||
@@ -46,6 +50,21 @@ secrets (
|
||||
)
|
||||
```
|
||||
|
||||
### audit_log 表结构
|
||||
|
||||
```sql
|
||||
audit_log (
|
||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
action VARCHAR(32) NOT NULL, -- 'add' | 'update' | 'delete'
|
||||
namespace VARCHAR(64) NOT NULL,
|
||||
kind VARCHAR(64) NOT NULL,
|
||||
name VARCHAR(256) NOT NULL,
|
||||
detail JSONB NOT NULL DEFAULT '{}', -- 变更摘要(tags/meta keys/secret keys,不含 value)
|
||||
actor VARCHAR(128) NOT NULL DEFAULT '', -- 操作者($USER 环境变量)
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
```
|
||||
|
||||
### 字段职责划分
|
||||
|
||||
| 字段 | 存什么 | 示例 |
|
||||
@@ -57,42 +76,104 @@ secrets (
|
||||
| `metadata` | 明文非敏感信息 | `{"ip":"47.243.154.187","desc":"Grafana","domains":["..."]}` |
|
||||
| `encrypted` | 敏感凭据(MVP 阶段明文存储,后续对 value 加密) | `{"ssh_key":"-----BEGIN...","password":"..."}` |
|
||||
|
||||
## CLI 命令
|
||||
## 数据库配置
|
||||
|
||||
首次使用需显式配置数据库连接,设置一次后在该设备上持久生效:
|
||||
|
||||
```bash
|
||||
# 查看版本
|
||||
secrets -V / --version
|
||||
|
||||
# 查看帮助
|
||||
secrets -h / --help
|
||||
secrets help <subcommand> # 子命令详细帮助,如 secrets help add
|
||||
|
||||
# 添加或更新记录(upsert)
|
||||
secrets add -n <namespace> --kind <kind> --name <name> \
|
||||
[--tag <tag>]... # 可重复
|
||||
[-m key=value]... # --meta 明文字段,-m 是短标志
|
||||
[-s key=value]... # --secret 敏感字段,value 以 @ 开头表示从文件读取
|
||||
|
||||
# 搜索(默认隐藏 encrypted 内容)
|
||||
secrets search [-n <namespace>] [--kind <kind>] [--tag <tag>] [-q <keyword>] [--show-secrets]
|
||||
# -q 匹配范围:name、namespace、kind、metadata 全文内容、tags
|
||||
|
||||
# 增量更新已有记录(合并语义,记录不存在则报错)
|
||||
secrets update -n <namespace> --kind <kind> --name <name> \
|
||||
[--add-tag <tag>]... # 添加标签(不影响已有标签)
|
||||
[--remove-tag <tag>]... # 移除标签
|
||||
[-m key=value]... # 新增或覆盖 metadata 字段(不影响其他字段)
|
||||
[--remove-meta <key>]... # 删除 metadata 字段
|
||||
[-s key=value]... # 新增或覆盖 encrypted 字段(不影响其他字段)
|
||||
[--remove-secret <key>]... # 删除 encrypted 字段
|
||||
|
||||
# 删除
|
||||
secrets delete -n <namespace> --kind <kind> --name <name>
|
||||
secrets config set-db "postgres://postgres:<password>@<host>:<port>/secrets"
|
||||
secrets config show # 查看当前配置(密码脱敏)
|
||||
secrets config path # 打印配置文件路径
|
||||
```
|
||||
|
||||
### 示例
|
||||
配置文件:`~/.config/secrets/config.toml`,权限 0600。`--db-url` 参数可一次性覆盖。
|
||||
|
||||
## CLI 命令
|
||||
|
||||
### AI 使用主路径
|
||||
|
||||
**读取一律用 `search`,写入用 `add` / `update`,避免反复查帮助。**
|
||||
|
||||
输出格式规则:
|
||||
- TTY(终端直接运行)→ 默认 `text`
|
||||
- 非 TTY(管道/重定向/AI 调用)→ 自动 `json-compact`
|
||||
- 显式 `-o json` → 美化 JSON
|
||||
- 显式 `-o env` → KEY=VALUE(可 source)
|
||||
|
||||
---
|
||||
|
||||
### search — 发现与读取
|
||||
|
||||
```bash
|
||||
# 参数说明(带典型值)
|
||||
# -n / --namespace refining | ricnsmart
|
||||
# --kind server | service
|
||||
# --name gitea | i-uf63f2uookgs5uxmrdyc | mqtt
|
||||
# --tag aliyun | hongkong | production
|
||||
# -q / --query mqtt | grafana | gitea (模糊匹配 name/namespace/kind/tags/metadata)
|
||||
# --show-secrets 不带值的 flag,显示 encrypted 字段内容
|
||||
# -f / --field metadata.ip | metadata.url | secret.token | secret.ssh_key
|
||||
# --summary 不带值的 flag,仅返回摘要(name/tags/desc/updated_at)
|
||||
# --limit 20 | 50(默认 50)
|
||||
# --offset 0 | 10 | 20(分页偏移)
|
||||
# --sort name(默认)| updated | created
|
||||
# -o / --output text | json | json-compact | env
|
||||
|
||||
# 发现概览(起步推荐)
|
||||
secrets search --summary --limit 20
|
||||
secrets search -n refining --summary --limit 20
|
||||
secrets search --sort updated --limit 10 --summary
|
||||
|
||||
# 精确定位单条记录
|
||||
secrets search -n refining --kind service --name gitea
|
||||
secrets search -n refining --kind server --name i-uf63f2uookgs5uxmrdyc
|
||||
|
||||
# 精确定位并获取完整内容(含 secrets)
|
||||
secrets search -n refining --kind service --name gitea -o json --show-secrets
|
||||
|
||||
# 直接提取字段值(最短路径,-f secret.* 自动解锁 secrets)
|
||||
secrets search -n refining --kind service --name gitea -f secret.token
|
||||
secrets search -n refining --kind service --name gitea -f metadata.url
|
||||
secrets search -n refining --kind service --name gitea \
|
||||
-f metadata.url -f metadata.default_org -f secret.token
|
||||
|
||||
# 模糊关键词搜索
|
||||
secrets search -q mqtt
|
||||
secrets search -q grafana
|
||||
secrets search -q 47.117
|
||||
|
||||
# 按条件过滤
|
||||
secrets search -n refining --kind service
|
||||
secrets search -n ricnsmart --kind server
|
||||
secrets search --tag hongkong
|
||||
secrets search --tag aliyun --summary
|
||||
|
||||
# 分页
|
||||
secrets search -n refining --summary --limit 10 --offset 0
|
||||
secrets search -n refining --summary --limit 10 --offset 10
|
||||
|
||||
# 管道 / AI 调用(非 TTY 自动 json-compact)
|
||||
secrets search -n refining --kind service | jq '.[].name'
|
||||
secrets search -n refining --kind service --name gitea --show-secrets | jq '.secrets.token'
|
||||
|
||||
# 导出为 env 文件(单条记录)
|
||||
secrets search -n refining --kind service --name gitea -o env --show-secrets \
|
||||
> ~/.config/gitea/config.env
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### add — 新增或全量覆盖(upsert)
|
||||
|
||||
```bash
|
||||
# 参数说明(带典型值)
|
||||
# -n / --namespace refining | ricnsmart
|
||||
# --kind server | service
|
||||
# --name gitea | i-uf63f2uookgs5uxmrdyc
|
||||
# --tag aliyun | hongkong(可重复)
|
||||
# -m / --meta ip=47.117.131.22 | desc="Aliyun ECS" | url=https://...(可重复)
|
||||
# -s / --secret token=<value> | ssh_key=@./key.pem | password=secret123(可重复)
|
||||
|
||||
# 添加服务器
|
||||
secrets add -n refining --kind server --name i-uf63f2uookgs5uxmrdyc \
|
||||
--tag aliyun --tag shanghai \
|
||||
@@ -102,30 +183,101 @@ secrets add -n refining --kind server --name i-uf63f2uookgs5uxmrdyc \
|
||||
# 添加服务凭据
|
||||
secrets add -n refining --kind service --name gitea \
|
||||
--tag gitea \
|
||||
-m url=https://gitea.refining.dev \
|
||||
-s token=<token>
|
||||
-m url=https://gitea.refining.dev -m default_org=refining -m username=voson \
|
||||
-s token=<token> -s runner_token=<runner_token>
|
||||
|
||||
# 搜索含 mqtt 的所有记录
|
||||
secrets search -q mqtt
|
||||
# 从文件读取 token
|
||||
secrets add -n ricnsmart --kind service --name mqtt \
|
||||
-m host=mqtt.ricnsmart.com -m port=1883 \
|
||||
-s password=@./mqtt_password.txt
|
||||
```
|
||||
|
||||
# 查看 refining 的全部服务配置(显示 secrets)
|
||||
secrets search -n refining --kind service --show-secrets
|
||||
---
|
||||
|
||||
# 按 tag 筛选
|
||||
secrets search --tag hongkong
|
||||
### update — 增量更新(记录必须已存在)
|
||||
|
||||
# 只更新一个 IP(不影响其他 metadata/secrets/tags)
|
||||
只有传入的字段才会变动,其余全部保留。
|
||||
|
||||
```bash
|
||||
# 参数说明(带典型值)
|
||||
# -n / --namespace refining | ricnsmart
|
||||
# --kind server | service
|
||||
# --name gitea | i-uf63f2uookgs5uxmrdyc
|
||||
# --add-tag production | backup(不影响已有 tag,可重复)
|
||||
# --remove-tag staging | deprecated(可重复)
|
||||
# -m / --meta ip=10.0.0.1 | desc="新描述"(新增或覆盖,可重复)
|
||||
# --remove-meta old_port | legacy_key(删除 metadata 字段,可重复)
|
||||
# -s / --secret token=<new> | ssh_key=@./new.pem(新增或覆盖,可重复)
|
||||
# --remove-secret old_password | deprecated_key(删除 secret 字段,可重复)
|
||||
|
||||
# 更新单个 metadata 字段
|
||||
secrets update -n refining --kind server --name i-uf63f2uookgs5uxmrdyc \
|
||||
-m ip=10.0.0.1
|
||||
|
||||
# 给一条记录新增 tag 并轮换密码
|
||||
# 轮换 token
|
||||
secrets update -n refining --kind service --name gitea \
|
||||
-s token=<new-token>
|
||||
|
||||
# 新增 tag 并轮换 token
|
||||
secrets update -n refining --kind service --name gitea \
|
||||
--add-tag production \
|
||||
-s token=<new-token>
|
||||
|
||||
# 移除一个废弃的 metadata 字段
|
||||
# 移除废弃字段
|
||||
secrets update -n refining --kind service --name mqtt \
|
||||
--remove-meta old_port
|
||||
--remove-meta old_port --remove-secret old_password
|
||||
|
||||
# 移除 tag
|
||||
secrets update -n refining --kind service --name gitea --remove-tag staging
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### delete — 删除记录
|
||||
|
||||
```bash
|
||||
# 参数说明(带典型值)
|
||||
# -n / --namespace refining | ricnsmart
|
||||
# --kind server | service
|
||||
# --name gitea | i-uf63f2uookgs5uxmrdyc(必须精确匹配)
|
||||
|
||||
# 删除服务凭据
|
||||
secrets delete -n refining --kind service --name legacy-mqtt
|
||||
|
||||
# 删除服务器记录
|
||||
secrets delete -n ricnsmart --kind server --name i-old-server-id
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### config — 配置管理
|
||||
|
||||
```bash
|
||||
# 设置数据库连接(每台设备执行一次,之后永久生效)
|
||||
secrets config set-db "postgres://postgres:<password>@<host>:<port>/secrets"
|
||||
|
||||
# 查看当前配置(密码脱敏)
|
||||
secrets config show
|
||||
|
||||
# 打印配置文件路径
|
||||
secrets config path
|
||||
# 输出: /Users/<user>/.config/secrets/config.toml
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 全局参数
|
||||
|
||||
```bash
|
||||
# debug 日志(位于子命令之前)
|
||||
secrets --verbose search -q mqtt
|
||||
secrets -v add -n refining --kind service --name gitea -m url=xxx -s token=yyy
|
||||
|
||||
# 或通过环境变量精细控制
|
||||
RUST_LOG=secrets=trace secrets search
|
||||
|
||||
# 一次性覆盖数据库连接
|
||||
secrets --db-url "postgres://..." search -n refining
|
||||
```
|
||||
|
||||
## 代码规范
|
||||
@@ -134,7 +286,10 @@ secrets update -n refining --kind service --name mqtt \
|
||||
- 异步:全程 `tokio`,数据库操作 `sqlx` async
|
||||
- SQL:使用 `sqlx::query` / `sqlx::query_as` 绑定参数,禁止字符串拼接(搜索的动态 WHERE 子句除外,需使用参数绑定 `$1/$2`)
|
||||
- 新增 `kind` 类型时:只需在 `add` 调用时传入,无需改代码
|
||||
- 字段命名:CLI 短标志 `-n`=namespace,`-m`=meta,`-s`=secret,`-q`=query
|
||||
- 字段命名:CLI 短标志 `-n`=namespace,`-m`=meta,`-s`=secret,`-q`=query,`-v`=verbose,`-f`=field,`-o`=output
|
||||
- 日志:用户可见输出用 `println!`;调试/运维信息用 `tracing::debug!`/`info!`/`warn!`/`error!`
|
||||
- 审计:`add`/`update`/`delete` 成功后调用 `audit::log()`,写入 `audit_log` 表;失败只 warn 不中断
|
||||
- 输出:读命令通过 `OutputMode` 支持 text/json/json-compact/env;写命令 `add` 同样支持 `-o json`
|
||||
|
||||
## 提交前检查(必须全部通过)
|
||||
|
||||
@@ -152,7 +307,7 @@ grep '^version' Cargo.toml
|
||||
git tag -l 'secrets-*'
|
||||
```
|
||||
|
||||
若当前版本已被 tag(例如已有 `secrets-0.1.0` 且 `Cargo.toml` 仍为 `0.1.0`),则应在 `Cargo.toml` 中 bump 版本号后再提交,以便 CI 自动打新 Tag 并发布 Release。
|
||||
若当前版本已被 tag(例如已有 `secrets-0.3.0` 且 `Cargo.toml` 仍为 `0.3.0`),则应在 `Cargo.toml` 中 bump 版本号后再提交,以便 CI 自动打新 Tag 并发布 Release。
|
||||
|
||||
### 2. 格式、Lint、测试
|
||||
|
||||
@@ -181,4 +336,7 @@ cargo fmt -- --check && cargo clippy -- -D warnings && cargo test
|
||||
|
||||
| 变量 | 说明 |
|
||||
|------|------|
|
||||
| `DATABASE_URL` | PostgreSQL 连接串,优先级高于 `--db-url` 参数 |
|
||||
| `RUST_LOG` | 日志级别,如 `secrets=debug`、`secrets=trace`(默认 warn) |
|
||||
| `USER` | 审计日志 actor 字段来源,Shell 自动设置,通常无需手动配置 |
|
||||
|
||||
数据库连接通过 `secrets config set-db` 持久化到 `~/.config/secrets/config.toml`,不支持环境变量。
|
||||
|
||||
142
Cargo.lock
generated
142
Cargo.lock
generated
@@ -2,6 +2,15 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "allocator-api2"
|
||||
version = "0.2.21"
|
||||
@@ -305,6 +314,27 @@ dependencies = [
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dirs"
|
||||
version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"
|
||||
dependencies = [
|
||||
"dirs-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dirs-sys"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"option-ext",
|
||||
"redox_users",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "displaydoc"
|
||||
version = "0.2.5"
|
||||
@@ -807,6 +837,15 @@ version = "0.4.29"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
|
||||
|
||||
[[package]]
|
||||
name = "matchers"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
|
||||
dependencies = [
|
||||
"regex-automata",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "md-5"
|
||||
version = "0.10.6"
|
||||
@@ -834,6 +873,15 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nu-ansi-term"
|
||||
version = "0.50.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-bigint-dig"
|
||||
version = "0.8.6"
|
||||
@@ -892,6 +940,12 @@ version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||
|
||||
[[package]]
|
||||
name = "option-ext"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
|
||||
|
||||
[[package]]
|
||||
name = "parking"
|
||||
version = "2.2.1"
|
||||
@@ -1075,6 +1129,34 @@ dependencies = [
|
||||
"bitflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_users"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac"
|
||||
dependencies = [
|
||||
"getrandom 0.2.17",
|
||||
"libredox",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.8.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
|
||||
|
||||
[[package]]
|
||||
name = "ring"
|
||||
version = "0.17.14"
|
||||
@@ -1163,17 +1245,19 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "secrets"
|
||||
version = "0.2.0"
|
||||
version = "0.4.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
"clap",
|
||||
"dotenvy",
|
||||
"dirs",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sqlx",
|
||||
"tokio",
|
||||
"toml",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
@@ -1269,6 +1353,15 @@ dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sharded-slab"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
|
||||
dependencies = [
|
||||
"lazy_static",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "1.3.0"
|
||||
@@ -1608,6 +1701,15 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thread_local"
|
||||
version = "1.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinystr"
|
||||
version = "0.8.2"
|
||||
@@ -1741,6 +1843,36 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"valuable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-log"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
|
||||
dependencies = [
|
||||
"log",
|
||||
"once_cell",
|
||||
"tracing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-subscriber"
|
||||
version = "0.3.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
|
||||
dependencies = [
|
||||
"matchers",
|
||||
"nu-ansi-term",
|
||||
"once_cell",
|
||||
"regex-automata",
|
||||
"sharded-slab",
|
||||
"smallvec",
|
||||
"thread_local",
|
||||
"tracing",
|
||||
"tracing-core",
|
||||
"tracing-log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1824,6 +1956,12 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "valuable"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
|
||||
|
||||
[[package]]
|
||||
name = "vcpkg"
|
||||
version = "0.2.15"
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
[package]
|
||||
name = "secrets"
|
||||
version = "0.2.0"
|
||||
version = "0.4.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.102"
|
||||
chrono = { version = "0.4.44", features = ["serde"] }
|
||||
clap = { version = "4.6.0", features = ["derive", "env"] }
|
||||
dotenvy = "0.15.7"
|
||||
dirs = "6.0.0"
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = "1.0.149"
|
||||
sqlx = { version = "0.8.6", features = ["runtime-tokio", "tls-rustls", "postgres", "uuid", "json", "chrono"] }
|
||||
tokio = { version = "1.50.0", features = ["full"] }
|
||||
toml = "1.0.7"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
uuid = { version = "1.22.0", features = ["serde", "v4"] }
|
||||
|
||||
151
README.md
151
README.md
@@ -11,61 +11,124 @@ cargo build --release
|
||||
# 或从 Release 页面下载预编译二进制
|
||||
```
|
||||
|
||||
配置数据库连接:
|
||||
配置数据库连接(首次使用需执行一次,之后在该设备上持久生效):
|
||||
|
||||
```bash
|
||||
export DATABASE_URL=postgres://postgres:<password>@<host>:5432/secrets
|
||||
# 或在项目根目录创建 .env 文件写入上述变量
|
||||
secrets config set-db "postgres://postgres:<password>@<host>:<port>/secrets"
|
||||
```
|
||||
|
||||
## 使用
|
||||
## AI Agent 快速指南
|
||||
|
||||
这个 CLI 以 AI 使用优先设计。核心路径只有一条:**读取用 `search`,写入用 `add` / `update`**。
|
||||
|
||||
### 第一步:发现有哪些数据
|
||||
|
||||
```bash
|
||||
# 查看版本
|
||||
secrets -V
|
||||
secrets --version
|
||||
# 列出所有记录摘要(默认最多 50 条,安全起步)
|
||||
secrets search --summary --limit 20
|
||||
|
||||
# 查看帮助
|
||||
# 按 namespace 过滤
|
||||
secrets search -n refining --summary --limit 20
|
||||
|
||||
# 按最近更新排序
|
||||
secrets search --sort updated --limit 10 --summary
|
||||
```
|
||||
|
||||
`--summary` 只返回轻量字段(namespace、kind、name、tags、desc、updated_at),不含完整 metadata 和 secrets。
|
||||
|
||||
### 第二步:精确读取单条记录
|
||||
|
||||
```bash
|
||||
# 精确定位(namespace + kind + name 三元组)
|
||||
secrets search -n refining --kind service --name gitea
|
||||
|
||||
# 获取完整记录含 secrets(JSON 格式,AI 最易解析)
|
||||
secrets search -n refining --kind service --name gitea -o json --show-secrets
|
||||
|
||||
# 直接提取单个字段值(最短路径)
|
||||
secrets search -n refining --kind service --name gitea -f secret.token
|
||||
secrets search -n refining --kind service --name gitea -f metadata.url
|
||||
|
||||
# 同时提取多个字段
|
||||
secrets search -n refining --kind service --name gitea \
|
||||
-f metadata.url -f metadata.default_org -f secret.token
|
||||
```
|
||||
|
||||
`-f secret.*` 会自动解锁 secrets,无需额外加 `--show-secrets`。
|
||||
|
||||
### 输出格式
|
||||
|
||||
| 场景 | 推荐命令 |
|
||||
|------|----------|
|
||||
| AI 解析 / 管道处理 | `-o json` 或 `-o json-compact` |
|
||||
| 写入 `.env` 文件 | `-o env --show-secrets` |
|
||||
| 人类查看 | 默认 `text`(TTY 下自动启用) |
|
||||
| 非 TTY(管道/重定向) | 自动 `json-compact` |
|
||||
|
||||
```bash
|
||||
# 管道直接 jq 解析(非 TTY 自动 json-compact)
|
||||
secrets search -n refining --kind service | jq '.[].name'
|
||||
secrets search -n refining --kind service --name gitea --show-secrets | jq '.secrets.token'
|
||||
|
||||
# 导出为可 source 的 env 文件(单条记录)
|
||||
secrets search -n refining --kind service --name gitea -o env --show-secrets \
|
||||
> ~/.config/gitea/config.env
|
||||
```
|
||||
|
||||
## 完整命令参考
|
||||
|
||||
```bash
|
||||
# 查看帮助(包含各子命令 EXAMPLES)
|
||||
secrets --help
|
||||
secrets -h
|
||||
secrets search --help
|
||||
secrets add --help
|
||||
secrets update --help
|
||||
secrets delete --help
|
||||
secrets config --help
|
||||
|
||||
# 查看子命令帮助
|
||||
secrets help add
|
||||
secrets help search
|
||||
secrets help delete
|
||||
secrets help update
|
||||
# ── search ──────────────────────────────────────────────────────────────────
|
||||
secrets search --summary --limit 20 # 发现概览
|
||||
secrets search -n refining --kind service # 按 namespace + kind
|
||||
secrets search -n refining --kind service --name gitea # 精确查找
|
||||
secrets search -q mqtt # 关键词模糊搜索
|
||||
secrets search --tag hongkong # 按 tag 过滤
|
||||
secrets search -n refining --kind service --name gitea -f secret.token # 提取字段
|
||||
secrets search -n refining --kind service --name gitea -o json --show-secrets # 完整 JSON
|
||||
secrets search --sort updated --limit 10 --summary # 最近改动
|
||||
secrets search -n refining --summary --limit 10 --offset 10 # 翻页
|
||||
|
||||
# 添加服务器
|
||||
# ── add ──────────────────────────────────────────────────────────────────────
|
||||
secrets add -n refining --kind server --name my-server \
|
||||
--tag aliyun --tag shanghai \
|
||||
-m ip=1.2.3.4 -m desc="My Server" \
|
||||
-s username=root \
|
||||
-s ssh_key=@./keys/my.pem
|
||||
-m ip=47.117.131.22 -m desc="Aliyun Shanghai ECS" \
|
||||
-s username=root -s ssh_key=@./keys/server.pem
|
||||
|
||||
# 添加服务凭据
|
||||
secrets add -n refining --kind service --name gitea \
|
||||
-m url=https://gitea.example.com \
|
||||
--tag gitea \
|
||||
-m url=https://gitea.refining.dev -m default_org=refining \
|
||||
-s token=<token>
|
||||
|
||||
# 搜索(默认隐藏敏感字段)
|
||||
secrets search
|
||||
secrets search -n refining --kind server
|
||||
secrets search --tag hongkong
|
||||
secrets search -q mqtt # 关键词匹配 name / metadata / tags
|
||||
secrets search -n refining --kind service --name gitea --show-secrets
|
||||
|
||||
# 增量更新已有记录(合并语义,记录不存在则报错)
|
||||
# ── update ───────────────────────────────────────────────────────────────────
|
||||
secrets update -n refining --kind server --name my-server -m ip=10.0.0.1
|
||||
secrets update -n refining --kind service --name gitea --add-tag production -s token=<new-token>
|
||||
secrets update -n refining --kind service --name gitea --add-tag production -s token=<new>
|
||||
secrets update -n refining --kind service --name mqtt --remove-meta old_port --remove-secret old_key
|
||||
|
||||
# 删除
|
||||
secrets delete -n refining --kind server --name my-server
|
||||
# ── delete ───────────────────────────────────────────────────────────────────
|
||||
secrets delete -n refining --kind service --name legacy-mqtt
|
||||
|
||||
# ── config ───────────────────────────────────────────────────────────────────
|
||||
secrets config set-db "postgres://postgres:<password>@<host>:<port>/secrets"
|
||||
secrets config show # 密码脱敏展示
|
||||
secrets config path # 打印配置文件路径
|
||||
|
||||
# ── 调试 ──────────────────────────────────────────────────────────────────────
|
||||
secrets --verbose search -q mqtt
|
||||
RUST_LOG=secrets=trace secrets search
|
||||
```
|
||||
|
||||
## 数据模型
|
||||
|
||||
单张 `secrets` 表,首次连接自动建表。
|
||||
单张 `secrets` 表,首次连接自动建表;同时自动创建 `audit_log` 表,记录所有写操作。
|
||||
|
||||
| 字段 | 说明 |
|
||||
|------|------|
|
||||
@@ -78,16 +141,32 @@ secrets delete -n refining --kind server --name my-server
|
||||
|
||||
`-m` / `--meta` 写入 `metadata`,`-s` / `--secret` 写入 `encrypted`,`value=@file` 从文件读取内容。
|
||||
|
||||
## 审计日志
|
||||
|
||||
`add`、`update`、`delete` 操作成功后自动向 `audit_log` 表写入一条记录,包含操作类型、操作对象和变更摘要(不含 secret 值)。操作者取自 `$USER` 环境变量。
|
||||
|
||||
```sql
|
||||
-- 查看最近 20 条审计记录
|
||||
SELECT action, namespace, kind, name, actor, detail, created_at
|
||||
FROM audit_log
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 20;
|
||||
```
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
src/
|
||||
main.rs # CLI 入口(clap)
|
||||
db.rs # 连接池 + auto-migrate
|
||||
main.rs # CLI 入口(clap),含各子命令 after_help 示例
|
||||
output.rs # OutputMode 枚举 + TTY 检测
|
||||
config.rs # 配置读写(~/.config/secrets/config.toml)
|
||||
db.rs # 连接池 + auto-migrate(secrets + audit_log)
|
||||
models.rs # Secret 结构体
|
||||
audit.rs # 审计日志写入(audit_log 表)
|
||||
commands/
|
||||
add.rs # upsert
|
||||
search.rs # 多条件查询
|
||||
add.rs # upsert,支持 -o json
|
||||
config.rs # config set-db/show/path
|
||||
search.rs # 多条件查询,支持 -f/-o/--summary/--limit/--offset/--sort
|
||||
delete.rs # 删除
|
||||
update.rs # 增量更新(合并 tags/metadata/encrypted)
|
||||
scripts/
|
||||
|
||||
34
src/audit.rs
Normal file
34
src/audit.rs
Normal file
@@ -0,0 +1,34 @@
|
||||
use anyhow::Result;
|
||||
use serde_json::Value;
|
||||
use sqlx::PgPool;
|
||||
|
||||
/// Write an audit entry for a write operation. Failures are logged as warnings
|
||||
/// and do not interrupt the main flow.
|
||||
pub async fn log(
|
||||
pool: &PgPool,
|
||||
action: &str,
|
||||
namespace: &str,
|
||||
kind: &str,
|
||||
name: &str,
|
||||
detail: Value,
|
||||
) {
|
||||
let actor = std::env::var("USER").unwrap_or_default();
|
||||
let result: Result<_, sqlx::Error> = sqlx::query(
|
||||
"INSERT INTO audit_log (action, namespace, kind, name, detail, actor) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
)
|
||||
.bind(action)
|
||||
.bind(namespace)
|
||||
.bind(kind)
|
||||
.bind(name)
|
||||
.bind(&detail)
|
||||
.bind(&actor)
|
||||
.execute(pool)
|
||||
.await;
|
||||
|
||||
if let Err(e) = result {
|
||||
tracing::warn!(error = %e, "failed to write audit log");
|
||||
} else {
|
||||
tracing::debug!(action, namespace, kind, name, actor, "audit logged");
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
use anyhow::Result;
|
||||
use serde_json::{Map, Value};
|
||||
use serde_json::{Map, Value, json};
|
||||
use sqlx::PgPool;
|
||||
use std::fs;
|
||||
|
||||
use crate::output::OutputMode;
|
||||
|
||||
/// Parse "key=value" entries. Value starting with '@' reads from file.
|
||||
pub(crate) fn parse_kv(entry: &str) -> Result<(String, String)> {
|
||||
let (key, raw_val) = entry.split_once('=').ok_or_else(|| {
|
||||
@@ -31,17 +33,21 @@ fn build_json(entries: &[String]) -> Result<Value> {
|
||||
Ok(Value::Object(map))
|
||||
}
|
||||
|
||||
pub async fn run(
|
||||
pool: &PgPool,
|
||||
namespace: &str,
|
||||
kind: &str,
|
||||
name: &str,
|
||||
tags: &[String],
|
||||
meta_entries: &[String],
|
||||
secret_entries: &[String],
|
||||
) -> Result<()> {
|
||||
let metadata = build_json(meta_entries)?;
|
||||
let encrypted = build_json(secret_entries)?;
|
||||
pub struct AddArgs<'a> {
|
||||
pub namespace: &'a str,
|
||||
pub kind: &'a str,
|
||||
pub name: &'a str,
|
||||
pub tags: &'a [String],
|
||||
pub meta_entries: &'a [String],
|
||||
pub secret_entries: &'a [String],
|
||||
pub output: OutputMode,
|
||||
}
|
||||
|
||||
pub async fn run(pool: &PgPool, args: AddArgs<'_>) -> Result<()> {
|
||||
let metadata = build_json(args.meta_entries)?;
|
||||
let encrypted = build_json(args.secret_entries)?;
|
||||
|
||||
tracing::debug!(args.namespace, args.kind, args.name, "upserting record");
|
||||
|
||||
sqlx::query(
|
||||
r#"
|
||||
@@ -55,32 +61,69 @@ pub async fn run(
|
||||
updated_at = NOW()
|
||||
"#,
|
||||
)
|
||||
.bind(namespace)
|
||||
.bind(kind)
|
||||
.bind(name)
|
||||
.bind(tags)
|
||||
.bind(args.namespace)
|
||||
.bind(args.kind)
|
||||
.bind(args.name)
|
||||
.bind(args.tags)
|
||||
.bind(&metadata)
|
||||
.bind(&encrypted)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
|
||||
println!("Added: [{}/{}] {}", namespace, kind, name);
|
||||
if !tags.is_empty() {
|
||||
println!(" tags: {}", tags.join(", "));
|
||||
}
|
||||
if !meta_entries.is_empty() {
|
||||
let keys: Vec<&str> = meta_entries
|
||||
.iter()
|
||||
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
|
||||
.collect();
|
||||
println!(" metadata: {}", keys.join(", "));
|
||||
}
|
||||
if !secret_entries.is_empty() {
|
||||
let keys: Vec<&str> = secret_entries
|
||||
.iter()
|
||||
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
|
||||
.collect();
|
||||
println!(" secrets: {}", keys.join(", "));
|
||||
let meta_keys: Vec<&str> = args
|
||||
.meta_entries
|
||||
.iter()
|
||||
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
|
||||
.collect();
|
||||
let secret_keys: Vec<&str> = args
|
||||
.secret_entries
|
||||
.iter()
|
||||
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
|
||||
.collect();
|
||||
|
||||
crate::audit::log(
|
||||
pool,
|
||||
"add",
|
||||
args.namespace,
|
||||
args.kind,
|
||||
args.name,
|
||||
json!({
|
||||
"tags": args.tags,
|
||||
"meta_keys": meta_keys,
|
||||
"secret_keys": secret_keys,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
let result_json = json!({
|
||||
"action": "added",
|
||||
"namespace": args.namespace,
|
||||
"kind": args.kind,
|
||||
"name": args.name,
|
||||
"tags": args.tags,
|
||||
"meta_keys": meta_keys,
|
||||
"secret_keys": secret_keys,
|
||||
});
|
||||
|
||||
match args.output {
|
||||
OutputMode::Json => {
|
||||
println!("{}", serde_json::to_string_pretty(&result_json)?);
|
||||
}
|
||||
OutputMode::JsonCompact => {
|
||||
println!("{}", serde_json::to_string(&result_json)?);
|
||||
}
|
||||
_ => {
|
||||
println!("Added: [{}/{}] {}", args.namespace, args.kind, args.name);
|
||||
if !args.tags.is_empty() {
|
||||
println!(" tags: {}", args.tags.join(", "));
|
||||
}
|
||||
if !args.meta_entries.is_empty() {
|
||||
println!(" metadata: {}", meta_keys.join(", "));
|
||||
}
|
||||
if !args.secret_entries.is_empty() {
|
||||
println!(" secrets: {}", secret_keys.join(", "));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
54
src/commands/config.rs
Normal file
54
src/commands/config.rs
Normal file
@@ -0,0 +1,54 @@
|
||||
use crate::config::{self, Config, config_path};
|
||||
use anyhow::Result;
|
||||
|
||||
pub enum ConfigAction {
|
||||
SetDb { url: String },
|
||||
Show,
|
||||
Path,
|
||||
}
|
||||
|
||||
pub async fn run(action: ConfigAction) -> Result<()> {
|
||||
match action {
|
||||
ConfigAction::SetDb { url } => {
|
||||
let cfg = Config {
|
||||
database_url: Some(url.clone()),
|
||||
};
|
||||
config::save_config(&cfg)?;
|
||||
println!("✓ 数据库连接串已保存到: {}", config_path().display());
|
||||
println!(" {}", mask_password(&url));
|
||||
}
|
||||
ConfigAction::Show => {
|
||||
let cfg = config::load_config()?;
|
||||
match cfg.database_url {
|
||||
Some(url) => {
|
||||
println!("database_url = {}", mask_password(&url));
|
||||
println!("配置文件: {}", config_path().display());
|
||||
}
|
||||
None => {
|
||||
println!("未配置数据库连接串。");
|
||||
println!("请运行:secrets config set-db <DATABASE_URL>");
|
||||
}
|
||||
}
|
||||
}
|
||||
ConfigAction::Path => {
|
||||
println!("{}", config_path().display());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 将 postgres://user:password@host/db 中的密码替换为 ***
|
||||
fn mask_password(url: &str) -> String {
|
||||
if let Some(at_pos) = url.rfind('@')
|
||||
&& let Some(scheme_end) = url.find("://")
|
||||
{
|
||||
let prefix = &url[..scheme_end + 3];
|
||||
let credentials = &url[scheme_end + 3..at_pos];
|
||||
let rest = &url[at_pos..];
|
||||
if let Some(colon_pos) = credentials.find(':') {
|
||||
let user = &credentials[..colon_pos];
|
||||
return format!("{}{}:***{}", prefix, user, rest);
|
||||
}
|
||||
}
|
||||
url.to_string()
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
use anyhow::Result;
|
||||
use serde_json::json;
|
||||
use sqlx::PgPool;
|
||||
|
||||
pub async fn run(pool: &PgPool, namespace: &str, kind: &str, name: &str) -> Result<()> {
|
||||
tracing::debug!(namespace, kind, name, "deleting record");
|
||||
|
||||
let result =
|
||||
sqlx::query("DELETE FROM secrets WHERE namespace = $1 AND kind = $2 AND name = $3")
|
||||
.bind(namespace)
|
||||
@@ -11,8 +14,10 @@ pub async fn run(pool: &PgPool, namespace: &str, kind: &str, name: &str) -> Resu
|
||||
.await?;
|
||||
|
||||
if result.rows_affected() == 0 {
|
||||
tracing::warn!(namespace, kind, name, "record not found for deletion");
|
||||
println!("Not found: [{}/{}] {}", namespace, kind, name);
|
||||
} else {
|
||||
crate::audit::log(pool, "delete", namespace, kind, name, json!({})).await;
|
||||
println!("Deleted: [{}/{}] {}", namespace, kind, name);
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod add;
|
||||
pub mod config;
|
||||
pub mod delete;
|
||||
pub mod search;
|
||||
pub mod update;
|
||||
|
||||
@@ -1,36 +1,51 @@
|
||||
use anyhow::Result;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::models::Secret;
|
||||
use crate::output::OutputMode;
|
||||
|
||||
pub async fn run(
|
||||
pool: &PgPool,
|
||||
namespace: Option<&str>,
|
||||
kind: Option<&str>,
|
||||
tag: Option<&str>,
|
||||
query: Option<&str>,
|
||||
show_secrets: bool,
|
||||
) -> Result<()> {
|
||||
pub struct SearchArgs<'a> {
|
||||
pub namespace: Option<&'a str>,
|
||||
pub kind: Option<&'a str>,
|
||||
pub name: Option<&'a str>,
|
||||
pub tag: Option<&'a str>,
|
||||
pub query: Option<&'a str>,
|
||||
pub show_secrets: bool,
|
||||
pub fields: &'a [String],
|
||||
pub summary: bool,
|
||||
pub limit: u32,
|
||||
pub offset: u32,
|
||||
pub sort: &'a str,
|
||||
pub output: OutputMode,
|
||||
}
|
||||
|
||||
pub async fn run(pool: &PgPool, args: SearchArgs<'_>) -> Result<()> {
|
||||
let mut conditions: Vec<String> = Vec::new();
|
||||
let mut idx: i32 = 1;
|
||||
|
||||
if namespace.is_some() {
|
||||
if args.namespace.is_some() {
|
||||
conditions.push(format!("namespace = ${}", idx));
|
||||
idx += 1;
|
||||
}
|
||||
if kind.is_some() {
|
||||
if args.kind.is_some() {
|
||||
conditions.push(format!("kind = ${}", idx));
|
||||
idx += 1;
|
||||
}
|
||||
if tag.is_some() {
|
||||
if args.name.is_some() {
|
||||
conditions.push(format!("name = ${}", idx));
|
||||
idx += 1;
|
||||
}
|
||||
if args.tag.is_some() {
|
||||
conditions.push(format!("tags @> ARRAY[${}]", idx));
|
||||
idx += 1;
|
||||
}
|
||||
if query.is_some() {
|
||||
if args.query.is_some() {
|
||||
conditions.push(format!(
|
||||
"(name ILIKE ${i} OR namespace ILIKE ${i} OR kind ILIKE ${i} OR metadata::text ILIKE ${i} OR EXISTS (SELECT 1 FROM unnest(tags) t WHERE t ILIKE ${i}))",
|
||||
i = idx
|
||||
));
|
||||
idx += 1;
|
||||
}
|
||||
|
||||
let where_clause = if conditions.is_empty() {
|
||||
@@ -39,47 +54,166 @@ pub async fn run(
|
||||
format!("WHERE {}", conditions.join(" AND "))
|
||||
};
|
||||
|
||||
let order = match args.sort {
|
||||
"updated" => "updated_at DESC",
|
||||
"created" => "created_at DESC",
|
||||
_ => "namespace, kind, name",
|
||||
};
|
||||
|
||||
let sql = format!(
|
||||
"SELECT * FROM secrets {} ORDER BY namespace, kind, name",
|
||||
where_clause
|
||||
"SELECT * FROM secrets {} ORDER BY {} LIMIT ${} OFFSET ${}",
|
||||
where_clause,
|
||||
order,
|
||||
idx,
|
||||
idx + 1
|
||||
);
|
||||
|
||||
tracing::debug!(sql, "executing search query");
|
||||
|
||||
let mut q = sqlx::query_as::<_, Secret>(&sql);
|
||||
if let Some(v) = namespace {
|
||||
if let Some(v) = args.namespace {
|
||||
q = q.bind(v);
|
||||
}
|
||||
if let Some(v) = kind {
|
||||
if let Some(v) = args.kind {
|
||||
q = q.bind(v);
|
||||
}
|
||||
if let Some(v) = tag {
|
||||
if let Some(v) = args.name {
|
||||
q = q.bind(v);
|
||||
}
|
||||
if let Some(v) = query {
|
||||
if let Some(v) = args.tag {
|
||||
q = q.bind(v);
|
||||
}
|
||||
if let Some(v) = args.query {
|
||||
q = q.bind(format!("%{}%", v));
|
||||
}
|
||||
q = q.bind(args.limit as i64).bind(args.offset as i64);
|
||||
|
||||
let rows = q.fetch_all(pool).await?;
|
||||
|
||||
if rows.is_empty() {
|
||||
println!("No records found.");
|
||||
return Ok(());
|
||||
// -f/--field: extract specific field values directly
|
||||
if !args.fields.is_empty() {
|
||||
return print_fields(&rows, args.fields);
|
||||
}
|
||||
|
||||
for row in &rows {
|
||||
println!("[{}/{}] {}", row.namespace, row.kind, row.name,);
|
||||
println!(" id: {}", row.id);
|
||||
match args.output {
|
||||
OutputMode::Json | OutputMode::JsonCompact => {
|
||||
let arr: Vec<Value> = rows
|
||||
.iter()
|
||||
.map(|r| to_json(r, args.show_secrets, args.summary))
|
||||
.collect();
|
||||
let out = if args.output == OutputMode::Json {
|
||||
serde_json::to_string_pretty(&arr)?
|
||||
} else {
|
||||
serde_json::to_string(&arr)?
|
||||
};
|
||||
println!("{}", out);
|
||||
}
|
||||
OutputMode::Env => {
|
||||
if rows.len() > 1 {
|
||||
anyhow::bail!(
|
||||
"env output requires exactly one record; got {}. Add more filters.",
|
||||
rows.len()
|
||||
);
|
||||
}
|
||||
if let Some(row) = rows.first() {
|
||||
print_env(row, args.show_secrets)?;
|
||||
} else {
|
||||
eprintln!("No records found.");
|
||||
}
|
||||
}
|
||||
OutputMode::Text => {
|
||||
if rows.is_empty() {
|
||||
println!("No records found.");
|
||||
return Ok(());
|
||||
}
|
||||
for row in &rows {
|
||||
print_text(row, args.show_secrets, args.summary)?;
|
||||
}
|
||||
println!("{} record(s) found.", rows.len());
|
||||
if rows.len() == args.limit as usize {
|
||||
println!(
|
||||
" (showing up to {}; use --offset {} to see more)",
|
||||
args.limit,
|
||||
args.offset + args.limit
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn to_json(row: &Secret, show_secrets: bool, summary: bool) -> Value {
|
||||
if summary {
|
||||
let desc = row
|
||||
.metadata
|
||||
.get("desc")
|
||||
.or_else(|| row.metadata.get("url"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
return json!({
|
||||
"namespace": row.namespace,
|
||||
"kind": row.kind,
|
||||
"name": row.name,
|
||||
"tags": row.tags,
|
||||
"desc": desc,
|
||||
"updated_at": row.updated_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let secrets_val = if show_secrets {
|
||||
row.encrypted.clone()
|
||||
} else {
|
||||
let keys: Vec<&str> = row
|
||||
.encrypted
|
||||
.as_object()
|
||||
.map(|m| m.keys().map(|k| k.as_str()).collect())
|
||||
.unwrap_or_default();
|
||||
json!({"_hidden_keys": keys})
|
||||
};
|
||||
|
||||
json!({
|
||||
"id": row.id,
|
||||
"namespace": row.namespace,
|
||||
"kind": row.kind,
|
||||
"name": row.name,
|
||||
"tags": row.tags,
|
||||
"metadata": row.metadata,
|
||||
"secrets": secrets_val,
|
||||
"created_at": row.created_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
|
||||
"updated_at": row.updated_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn print_text(row: &Secret, show_secrets: bool, summary: bool) -> Result<()> {
|
||||
println!("[{}/{}] {}", row.namespace, row.kind, row.name);
|
||||
if summary {
|
||||
let desc = row
|
||||
.metadata
|
||||
.get("desc")
|
||||
.or_else(|| row.metadata.get("url"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("-");
|
||||
if !row.tags.is_empty() {
|
||||
println!(" tags: [{}]", row.tags.join(", "));
|
||||
}
|
||||
println!(" desc: {}", desc);
|
||||
println!(
|
||||
" updated: {}",
|
||||
row.updated_at.format("%Y-%m-%d %H:%M:%S UTC")
|
||||
);
|
||||
} else {
|
||||
println!(" id: {}", row.id);
|
||||
if !row.tags.is_empty() {
|
||||
println!(" tags: [{}]", row.tags.join(", "));
|
||||
}
|
||||
|
||||
if row.metadata.as_object().is_some_and(|m| !m.is_empty()) {
|
||||
println!(
|
||||
" metadata: {}",
|
||||
serde_json::to_string_pretty(&row.metadata)?
|
||||
);
|
||||
}
|
||||
|
||||
if show_secrets {
|
||||
println!(
|
||||
" secrets: {}",
|
||||
@@ -98,13 +232,73 @@ pub async fn run(
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
println!(
|
||||
" created: {}",
|
||||
row.created_at.format("%Y-%m-%d %H:%M:%S UTC")
|
||||
);
|
||||
println!();
|
||||
}
|
||||
println!("{} record(s) found.", rows.len());
|
||||
println!();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_env(row: &Secret, show_secrets: bool) -> Result<()> {
|
||||
let prefix = row.name.to_uppercase().replace(['-', '.'], "_");
|
||||
if let Some(meta) = row.metadata.as_object() {
|
||||
for (k, v) in meta {
|
||||
let key = format!("{}_{}", prefix, k.to_uppercase().replace('-', "_"));
|
||||
println!("{}={}", key, v.as_str().unwrap_or(&v.to_string()));
|
||||
}
|
||||
}
|
||||
if show_secrets && let Some(enc) = row.encrypted.as_object() {
|
||||
for (k, v) in enc {
|
||||
let key = format!("{}_{}", prefix, k.to_uppercase().replace('-', "_"));
|
||||
println!("{}={}", key, v.as_str().unwrap_or(&v.to_string()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Extract one or more field paths like `metadata.url` or `secret.token`.
|
||||
fn print_fields(rows: &[Secret], fields: &[String]) -> Result<()> {
|
||||
for row in rows {
|
||||
for field in fields {
|
||||
let val = extract_field(row, field)?;
|
||||
println!("{}", val);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn extract_field(row: &Secret, field: &str) -> Result<String> {
|
||||
let (section, key) = field.split_once('.').ok_or_else(|| {
|
||||
anyhow::anyhow!(
|
||||
"Invalid field path '{}'. Use metadata.<key> or secret.<key>",
|
||||
field
|
||||
)
|
||||
})?;
|
||||
|
||||
let obj = match section {
|
||||
"metadata" | "meta" => &row.metadata,
|
||||
"secret" | "secrets" | "encrypted" => &row.encrypted,
|
||||
other => anyhow::bail!(
|
||||
"Unknown field section '{}'. Use 'metadata' or 'secret'",
|
||||
other
|
||||
),
|
||||
};
|
||||
|
||||
obj.get(key)
|
||||
.and_then(|v| {
|
||||
v.as_str()
|
||||
.map(|s| s.to_string())
|
||||
.or_else(|| Some(v.to_string()))
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
anyhow::anyhow!(
|
||||
"Field '{}' not found in record [{}/{}/{}]",
|
||||
field,
|
||||
row.namespace,
|
||||
row.kind,
|
||||
row.name
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
use anyhow::Result;
|
||||
use serde_json::{Map, Value};
|
||||
use sqlx::PgPool;
|
||||
use serde_json::{Map, Value, json};
|
||||
use sqlx::{FromRow, PgPool};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::add::parse_kv;
|
||||
|
||||
#[derive(FromRow)]
|
||||
struct UpdateRow {
|
||||
id: Uuid,
|
||||
tags: Vec<String>,
|
||||
metadata: Value,
|
||||
encrypted: Value,
|
||||
}
|
||||
|
||||
pub struct UpdateArgs<'a> {
|
||||
pub namespace: &'a str,
|
||||
pub kind: &'a str,
|
||||
@@ -17,16 +26,16 @@ pub struct UpdateArgs<'a> {
|
||||
}
|
||||
|
||||
pub async fn run(pool: &PgPool, args: UpdateArgs<'_>) -> Result<()> {
|
||||
let row = sqlx::query!(
|
||||
let row: Option<UpdateRow> = sqlx::query_as(
|
||||
r#"
|
||||
SELECT id, tags, metadata, encrypted
|
||||
FROM secrets
|
||||
WHERE namespace = $1 AND kind = $2 AND name = $3
|
||||
"#,
|
||||
args.namespace,
|
||||
args.kind,
|
||||
args.name,
|
||||
)
|
||||
.bind(args.namespace)
|
||||
.bind(args.kind)
|
||||
.bind(args.name)
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
|
||||
@@ -76,20 +85,55 @@ pub async fn run(pool: &PgPool, args: UpdateArgs<'_>) -> Result<()> {
|
||||
}
|
||||
let encrypted = Value::Object(enc_map);
|
||||
|
||||
sqlx::query!(
|
||||
tracing::debug!(
|
||||
namespace = args.namespace,
|
||||
kind = args.kind,
|
||||
name = args.name,
|
||||
"updating record"
|
||||
);
|
||||
|
||||
sqlx::query(
|
||||
r#"
|
||||
UPDATE secrets
|
||||
SET tags = $1, metadata = $2, encrypted = $3, updated_at = NOW()
|
||||
WHERE id = $4
|
||||
"#,
|
||||
&tags,
|
||||
metadata,
|
||||
encrypted,
|
||||
row.id,
|
||||
)
|
||||
.bind(&tags)
|
||||
.bind(metadata)
|
||||
.bind(encrypted)
|
||||
.bind(row.id)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
|
||||
let meta_keys: Vec<&str> = args
|
||||
.meta_entries
|
||||
.iter()
|
||||
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
|
||||
.collect();
|
||||
let secret_keys: Vec<&str> = args
|
||||
.secret_entries
|
||||
.iter()
|
||||
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
|
||||
.collect();
|
||||
|
||||
crate::audit::log(
|
||||
pool,
|
||||
"update",
|
||||
args.namespace,
|
||||
args.kind,
|
||||
args.name,
|
||||
json!({
|
||||
"add_tags": args.add_tags,
|
||||
"remove_tags": args.remove_tags,
|
||||
"meta_keys": meta_keys,
|
||||
"remove_meta": args.remove_meta,
|
||||
"secret_keys": secret_keys,
|
||||
"remove_secrets": args.remove_secrets,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
println!("Updated: [{}/{}] {}", args.namespace, args.kind, args.name);
|
||||
|
||||
if !args.add_tags.is_empty() {
|
||||
|
||||
70
src/config.rs
Normal file
70
src/config.rs
Normal file
@@ -0,0 +1,70 @@
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Default)]
|
||||
pub struct Config {
|
||||
pub database_url: Option<String>,
|
||||
}
|
||||
|
||||
pub fn config_dir() -> PathBuf {
|
||||
dirs::config_dir()
|
||||
.unwrap_or_else(|| PathBuf::from("~/.config"))
|
||||
.join("secrets")
|
||||
}
|
||||
|
||||
pub fn config_path() -> PathBuf {
|
||||
config_dir().join("config.toml")
|
||||
}
|
||||
|
||||
pub fn load_config() -> Result<Config> {
|
||||
let path = config_path();
|
||||
if !path.exists() {
|
||||
return Ok(Config::default());
|
||||
}
|
||||
let content = fs::read_to_string(&path)
|
||||
.with_context(|| format!("读取配置文件失败: {}", path.display()))?;
|
||||
let config: Config = toml::from_str(&content)
|
||||
.with_context(|| format!("解析配置文件失败: {}", path.display()))?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
pub fn save_config(config: &Config) -> Result<()> {
|
||||
let dir = config_dir();
|
||||
fs::create_dir_all(&dir).with_context(|| format!("创建配置目录失败: {}", dir.display()))?;
|
||||
|
||||
let path = config_path();
|
||||
let content = toml::to_string_pretty(config).context("序列化配置失败")?;
|
||||
fs::write(&path, &content).with_context(|| format!("写入配置文件失败: {}", path.display()))?;
|
||||
|
||||
// 设置文件权限为 0600(仅所有者读写)
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let perms = fs::Permissions::from_mode(0o600);
|
||||
fs::set_permissions(&path, perms)
|
||||
.with_context(|| format!("设置文件权限失败: {}", path.display()))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 按优先级解析数据库连接串:
|
||||
/// 1. --db-url CLI 参数(非空时使用)
|
||||
/// 2. ~/.config/secrets/config.toml 中的 database_url
|
||||
/// 3. 报错并提示用户配置
|
||||
pub fn resolve_db_url(cli_db_url: &str) -> Result<String> {
|
||||
if !cli_db_url.is_empty() {
|
||||
return Ok(cli_db_url.to_string());
|
||||
}
|
||||
|
||||
let config = load_config()?;
|
||||
if let Some(url) = config.database_url
|
||||
&& !url.is_empty()
|
||||
{
|
||||
return Ok(url);
|
||||
}
|
||||
|
||||
anyhow::bail!("数据库未配置。请先运行:\n\n secrets config set-db <DATABASE_URL>\n")
|
||||
}
|
||||
18
src/db.rs
18
src/db.rs
@@ -3,14 +3,17 @@ use sqlx::PgPool;
|
||||
use sqlx::postgres::PgPoolOptions;
|
||||
|
||||
pub async fn create_pool(database_url: &str) -> Result<PgPool> {
|
||||
tracing::debug!("connecting to database");
|
||||
let pool = PgPoolOptions::new()
|
||||
.max_connections(5)
|
||||
.connect(database_url)
|
||||
.await?;
|
||||
tracing::debug!("database connection established");
|
||||
Ok(pool)
|
||||
}
|
||||
|
||||
pub async fn migrate(pool: &PgPool) -> Result<()> {
|
||||
tracing::debug!("running migrations");
|
||||
sqlx::raw_sql(
|
||||
r#"
|
||||
CREATE TABLE IF NOT EXISTS secrets (
|
||||
@@ -36,9 +39,24 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
|
||||
CREATE INDEX IF NOT EXISTS idx_secrets_kind ON secrets(kind);
|
||||
CREATE INDEX IF NOT EXISTS idx_secrets_tags ON secrets USING GIN(tags);
|
||||
CREATE INDEX IF NOT EXISTS idx_secrets_metadata ON secrets USING GIN(metadata jsonb_path_ops);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS audit_log (
|
||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
action VARCHAR(32) NOT NULL,
|
||||
namespace VARCHAR(64) NOT NULL,
|
||||
kind VARCHAR(64) NOT NULL,
|
||||
name VARCHAR(256) NOT NULL,
|
||||
detail JSONB NOT NULL DEFAULT '{}',
|
||||
actor VARCHAR(128) NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_log_created ON audit_log(created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_log_ns_kind ON audit_log(namespace, kind);
|
||||
"#,
|
||||
)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
tracing::debug!("migrations complete");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
294
src/main.rs
294
src/main.rs
@@ -1,94 +1,224 @@
|
||||
mod audit;
|
||||
mod commands;
|
||||
mod config;
|
||||
mod db;
|
||||
mod models;
|
||||
mod output;
|
||||
|
||||
use anyhow::Result;
|
||||
use clap::{Parser, Subcommand};
|
||||
use dotenvy::dotenv;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
use output::resolve_output_mode;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
name = "secrets",
|
||||
version,
|
||||
about = "Secrets & config manager backed by PostgreSQL"
|
||||
about = "Secrets & config manager backed by PostgreSQL — optimised for AI agents",
|
||||
after_help = "QUICK START (AI agents):
|
||||
# Discover what namespaces / kinds exist
|
||||
secrets search --summary --limit 20
|
||||
|
||||
# Precise lookup (JSON output for easy parsing)
|
||||
secrets search -n refining --kind service --name gitea -o json --show-secrets
|
||||
|
||||
# Extract a single field value directly
|
||||
secrets search -n refining --kind service --name gitea -f secret.token
|
||||
|
||||
# Pipe-friendly (non-TTY defaults to json-compact automatically)
|
||||
secrets search -n refining --kind service | jq '.[].name'"
|
||||
)]
|
||||
struct Cli {
|
||||
/// Database URL (or set DATABASE_URL env var)
|
||||
#[arg(long, env = "DATABASE_URL", global = true, default_value = "")]
|
||||
/// Database URL, overrides saved config (one-time override)
|
||||
#[arg(long, global = true, default_value = "")]
|
||||
db_url: String,
|
||||
|
||||
/// Enable verbose debug output
|
||||
#[arg(long, short, global = true)]
|
||||
verbose: bool,
|
||||
|
||||
#[command(subcommand)]
|
||||
command: Commands,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Commands {
|
||||
/// Add or update a record (upsert)
|
||||
/// Add or update a record (upsert). Use -m for plaintext metadata, -s for secrets.
|
||||
#[command(after_help = "EXAMPLES:
|
||||
# Add a server
|
||||
secrets add -n refining --kind server --name my-server \\
|
||||
--tag aliyun --tag shanghai \\
|
||||
-m ip=47.117.131.22 -m desc=\"Aliyun Shanghai ECS\" \\
|
||||
-s username=root -s ssh_key=@./keys/server.pem
|
||||
|
||||
# Add a service credential
|
||||
secrets add -n refining --kind service --name gitea \\
|
||||
--tag gitea \\
|
||||
-m url=https://gitea.refining.dev -m default_org=refining \\
|
||||
-s token=<token>
|
||||
|
||||
# Add with token read from a file
|
||||
secrets add -n ricnsmart --kind service --name mqtt \\
|
||||
-m host=mqtt.ricnsmart.com -m port=1883 \\
|
||||
-s password=@./mqtt_password.txt")]
|
||||
Add {
|
||||
/// Namespace (e.g. refining, ricnsmart)
|
||||
/// Namespace, e.g. refining, ricnsmart
|
||||
#[arg(short, long)]
|
||||
namespace: String,
|
||||
/// Kind of record (server, service, key, ...)
|
||||
/// Kind of record: server, service, key, ...
|
||||
#[arg(long)]
|
||||
kind: String,
|
||||
/// Human-readable name
|
||||
/// Human-readable unique name, e.g. gitea, i-uf63f2uookgs5uxmrdyc
|
||||
#[arg(long)]
|
||||
name: String,
|
||||
/// Tags for categorization (repeatable)
|
||||
/// Tag for categorization (repeatable), e.g. --tag aliyun --tag hongkong
|
||||
#[arg(long = "tag")]
|
||||
tags: Vec<String>,
|
||||
/// Plaintext metadata entry: key=value (repeatable, key=@file reads from file)
|
||||
/// Plaintext metadata: key=value (repeatable; value=@file reads from file)
|
||||
#[arg(long = "meta", short = 'm')]
|
||||
meta: Vec<String>,
|
||||
/// Secret entry: key=value (repeatable, key=@file reads from file)
|
||||
/// Secret entry: key=value (repeatable; value=@file reads from file)
|
||||
#[arg(long = "secret", short = 's')]
|
||||
secrets: Vec<String>,
|
||||
/// Output format: text (default on TTY), json, json-compact, env
|
||||
#[arg(short, long = "output")]
|
||||
output: Option<String>,
|
||||
},
|
||||
|
||||
/// Search records
|
||||
/// Search / read records. This is the primary read command for AI agents.
|
||||
///
|
||||
/// Supports fuzzy search (-q), exact lookup (--name), field extraction (-f),
|
||||
/// summary view (--summary), pagination (--limit / --offset), and structured
|
||||
/// output (-o json / json-compact / env). When stdout is not a TTY, output
|
||||
/// defaults to json-compact automatically.
|
||||
#[command(after_help = "EXAMPLES:
|
||||
# Discover all records (summary, safe default limit)
|
||||
secrets search --summary --limit 20
|
||||
|
||||
# Filter by namespace and kind
|
||||
secrets search -n refining --kind service
|
||||
|
||||
# Exact lookup — returns 0 or 1 record
|
||||
secrets search -n refining --kind service --name gitea
|
||||
|
||||
# Fuzzy keyword search (matches name, namespace, kind, tags, metadata)
|
||||
secrets search -q mqtt
|
||||
|
||||
# Extract a single field value (implies --show-secrets for secret.*)
|
||||
secrets search -n refining --kind service --name gitea -f secret.token
|
||||
secrets search -n refining --kind service --name gitea -f metadata.url
|
||||
|
||||
# Multiple fields at once
|
||||
secrets search -n refining --kind service --name gitea \\
|
||||
-f metadata.url -f metadata.default_org -f secret.token
|
||||
|
||||
# Full JSON output with secrets revealed (ideal for AI parsing)
|
||||
secrets search -n refining --kind service --name gitea -o json --show-secrets
|
||||
|
||||
# Export as env vars (source-able; single record only)
|
||||
secrets search -n refining --kind service --name gitea -o env --show-secrets
|
||||
|
||||
# Paginate large result sets
|
||||
secrets search -n refining --summary --limit 10 --offset 0
|
||||
secrets search -n refining --summary --limit 10 --offset 10
|
||||
|
||||
# Sort by most recently updated
|
||||
secrets search --sort updated --limit 5 --summary
|
||||
|
||||
# Non-TTY / pipe: output is json-compact by default
|
||||
secrets search -n refining --kind service | jq '.[].name'
|
||||
secrets search -n refining --kind service --name gitea --show-secrets | jq '.secrets.token'")]
|
||||
Search {
|
||||
/// Filter by namespace
|
||||
/// Filter by namespace, e.g. refining, ricnsmart
|
||||
#[arg(short, long)]
|
||||
namespace: Option<String>,
|
||||
/// Filter by kind
|
||||
/// Filter by kind, e.g. server, service
|
||||
#[arg(long)]
|
||||
kind: Option<String>,
|
||||
/// Filter by tag
|
||||
/// Exact name filter, e.g. gitea, i-uf63f2uookgs5uxmrdyc
|
||||
#[arg(long)]
|
||||
name: Option<String>,
|
||||
/// Filter by tag, e.g. --tag aliyun
|
||||
#[arg(long)]
|
||||
tag: Option<String>,
|
||||
/// Search by keyword (matches name, namespace, kind)
|
||||
/// Fuzzy keyword (matches name, namespace, kind, tags, metadata text)
|
||||
#[arg(short, long)]
|
||||
query: Option<String>,
|
||||
/// Reveal encrypted secret values
|
||||
/// Reveal encrypted secret values in output
|
||||
#[arg(long)]
|
||||
show_secrets: bool,
|
||||
/// Extract field value(s) directly: metadata.<key> or secret.<key> (repeatable)
|
||||
#[arg(short = 'f', long = "field")]
|
||||
fields: Vec<String>,
|
||||
/// Return lightweight summary only (namespace, kind, name, tags, desc, updated_at)
|
||||
#[arg(long)]
|
||||
summary: bool,
|
||||
/// Maximum number of records to return [default: 50]
|
||||
#[arg(long, default_value = "50")]
|
||||
limit: u32,
|
||||
/// Skip this many records (for pagination)
|
||||
#[arg(long, default_value = "0")]
|
||||
offset: u32,
|
||||
/// Sort order: name (default), updated, created
|
||||
#[arg(long, default_value = "name")]
|
||||
sort: String,
|
||||
/// Output format: text (default on TTY), json, json-compact, env
|
||||
#[arg(short, long = "output")]
|
||||
output: Option<String>,
|
||||
},
|
||||
|
||||
/// Delete a record
|
||||
/// Delete a record permanently. Requires exact namespace + kind + name.
|
||||
#[command(after_help = "EXAMPLES:
|
||||
# Delete a service credential
|
||||
secrets delete -n refining --kind service --name legacy-mqtt
|
||||
|
||||
# Delete a server record
|
||||
secrets delete -n ricnsmart --kind server --name i-old-server-id")]
|
||||
Delete {
|
||||
/// Namespace
|
||||
/// Namespace, e.g. refining
|
||||
#[arg(short, long)]
|
||||
namespace: String,
|
||||
/// Kind
|
||||
/// Kind, e.g. server, service
|
||||
#[arg(long)]
|
||||
kind: String,
|
||||
/// Name
|
||||
/// Exact name of the record to delete
|
||||
#[arg(long)]
|
||||
name: String,
|
||||
},
|
||||
|
||||
/// Incrementally update an existing record (merge semantics)
|
||||
/// Incrementally update an existing record (merge semantics; record must exist).
|
||||
///
|
||||
/// Only the fields you pass are changed — everything else is preserved.
|
||||
/// Use --add-tag / --remove-tag to modify tags without touching other fields.
|
||||
#[command(after_help = "EXAMPLES:
|
||||
# Update a single metadata field (all other fields unchanged)
|
||||
secrets update -n refining --kind server --name my-server -m ip=10.0.0.1
|
||||
|
||||
# Rotate a secret token
|
||||
secrets update -n refining --kind service --name gitea -s token=<new-token>
|
||||
|
||||
# Add a tag and rotate password at the same time
|
||||
secrets update -n refining --kind service --name gitea \\
|
||||
--add-tag production -s token=<new-token>
|
||||
|
||||
# Remove a deprecated metadata field and a stale secret key
|
||||
secrets update -n refining --kind service --name mqtt \\
|
||||
--remove-meta old_port --remove-secret old_password
|
||||
|
||||
# Remove a tag
|
||||
secrets update -n refining --kind service --name gitea --remove-tag staging")]
|
||||
Update {
|
||||
/// Namespace (e.g. refining, ricnsmart)
|
||||
/// Namespace, e.g. refining, ricnsmart
|
||||
#[arg(short, long)]
|
||||
namespace: String,
|
||||
/// Kind of record (server, service, key, ...)
|
||||
/// Kind of record: server, service, key, ...
|
||||
#[arg(long)]
|
||||
kind: String,
|
||||
/// Human-readable name
|
||||
/// Human-readable unique name
|
||||
#[arg(long)]
|
||||
name: String,
|
||||
/// Add a tag (repeatable)
|
||||
/// Add a tag (repeatable; does not affect existing tags)
|
||||
#[arg(long = "add-tag")]
|
||||
add_tags: Vec<String>,
|
||||
/// Remove a tag (repeatable)
|
||||
@@ -97,32 +227,73 @@ enum Commands {
|
||||
/// Set or overwrite a metadata field: key=value (repeatable, @file supported)
|
||||
#[arg(long = "meta", short = 'm')]
|
||||
meta: Vec<String>,
|
||||
/// Remove a metadata field by key (repeatable)
|
||||
/// Delete a metadata field by key (repeatable)
|
||||
#[arg(long = "remove-meta")]
|
||||
remove_meta: Vec<String>,
|
||||
/// Set or overwrite a secret field: key=value (repeatable, @file supported)
|
||||
#[arg(long = "secret", short = 's')]
|
||||
secrets: Vec<String>,
|
||||
/// Remove a secret field by key (repeatable)
|
||||
/// Delete a secret field by key (repeatable)
|
||||
#[arg(long = "remove-secret")]
|
||||
remove_secrets: Vec<String>,
|
||||
},
|
||||
|
||||
/// Manage CLI configuration (database connection, etc.)
|
||||
#[command(after_help = "EXAMPLES:
|
||||
# Configure the database URL (run once per device; persisted to config file)
|
||||
secrets config set-db \"postgres://postgres:<password>@<host>:<port>/secrets\"
|
||||
|
||||
# Show current config (password is masked)
|
||||
secrets config show
|
||||
|
||||
# Print path to the config file
|
||||
secrets config path")]
|
||||
Config {
|
||||
#[command(subcommand)]
|
||||
action: ConfigAction,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum ConfigAction {
|
||||
/// Save database URL to config file (~/.config/secrets/config.toml)
|
||||
SetDb {
|
||||
/// PostgreSQL connection string, e.g. postgres://user:pass@<host>:<port>/dbname
|
||||
url: String,
|
||||
},
|
||||
/// Show current configuration (password masked)
|
||||
Show,
|
||||
/// Print path to the config file
|
||||
Path,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
dotenv().ok();
|
||||
|
||||
let cli = Cli::parse();
|
||||
|
||||
let db_url = if cli.db_url.is_empty() {
|
||||
std::env::var("DATABASE_URL").map_err(|_| {
|
||||
anyhow::anyhow!("DATABASE_URL not set. Use --db-url or set DATABASE_URL env var.")
|
||||
})?
|
||||
let filter = if cli.verbose {
|
||||
EnvFilter::new("secrets=debug")
|
||||
} else {
|
||||
cli.db_url.clone()
|
||||
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("secrets=warn"))
|
||||
};
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(filter)
|
||||
.with_target(false)
|
||||
.init();
|
||||
|
||||
// config 子命令不需要数据库连接,提前处理
|
||||
if let Commands::Config { action } = &cli.command {
|
||||
let cmd_action = match action {
|
||||
ConfigAction::SetDb { url } => {
|
||||
commands::config::ConfigAction::SetDb { url: url.clone() }
|
||||
}
|
||||
ConfigAction::Show => commands::config::ConfigAction::Show,
|
||||
ConfigAction::Path => commands::config::ConfigAction::Path,
|
||||
};
|
||||
return commands::config::run(cmd_action).await;
|
||||
}
|
||||
|
||||
let db_url = config::resolve_db_url(&cli.db_url)?;
|
||||
let pool = db::create_pool(&db_url).await?;
|
||||
db::migrate(&pool).await?;
|
||||
|
||||
@@ -134,23 +305,59 @@ async fn main() -> Result<()> {
|
||||
tags,
|
||||
meta,
|
||||
secrets,
|
||||
output,
|
||||
} => {
|
||||
commands::add::run(&pool, namespace, kind, name, tags, meta, secrets).await?;
|
||||
let _span =
|
||||
tracing::info_span!("cmd", command = "add", %namespace, %kind, %name).entered();
|
||||
let out = resolve_output_mode(output.as_deref())?;
|
||||
commands::add::run(
|
||||
&pool,
|
||||
commands::add::AddArgs {
|
||||
namespace,
|
||||
kind,
|
||||
name,
|
||||
tags,
|
||||
meta_entries: meta,
|
||||
secret_entries: secrets,
|
||||
output: out,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Commands::Search {
|
||||
namespace,
|
||||
kind,
|
||||
name,
|
||||
tag,
|
||||
query,
|
||||
show_secrets,
|
||||
fields,
|
||||
summary,
|
||||
limit,
|
||||
offset,
|
||||
sort,
|
||||
output,
|
||||
} => {
|
||||
let _span = tracing::info_span!("cmd", command = "search").entered();
|
||||
// -f implies --show-secrets when any field path starts with "secret"
|
||||
let show = *show_secrets || fields.iter().any(|f| f.starts_with("secret"));
|
||||
let out = resolve_output_mode(output.as_deref())?;
|
||||
commands::search::run(
|
||||
&pool,
|
||||
namespace.as_deref(),
|
||||
kind.as_deref(),
|
||||
tag.as_deref(),
|
||||
query.as_deref(),
|
||||
*show_secrets,
|
||||
commands::search::SearchArgs {
|
||||
namespace: namespace.as_deref(),
|
||||
kind: kind.as_deref(),
|
||||
name: name.as_deref(),
|
||||
tag: tag.as_deref(),
|
||||
query: query.as_deref(),
|
||||
show_secrets: show,
|
||||
fields,
|
||||
summary: *summary,
|
||||
limit: *limit,
|
||||
offset: *offset,
|
||||
sort,
|
||||
output: out,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
@@ -159,6 +366,8 @@ async fn main() -> Result<()> {
|
||||
kind,
|
||||
name,
|
||||
} => {
|
||||
let _span =
|
||||
tracing::info_span!("cmd", command = "delete", %namespace, %kind, %name).entered();
|
||||
commands::delete::run(&pool, namespace, kind, name).await?;
|
||||
}
|
||||
Commands::Update {
|
||||
@@ -172,6 +381,8 @@ async fn main() -> Result<()> {
|
||||
secrets,
|
||||
remove_secrets,
|
||||
} => {
|
||||
let _span =
|
||||
tracing::info_span!("cmd", command = "update", %namespace, %kind, %name).entered();
|
||||
commands::update::run(
|
||||
&pool,
|
||||
commands::update::UpdateArgs {
|
||||
@@ -188,6 +399,7 @@ async fn main() -> Result<()> {
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Commands::Config { .. } => unreachable!(),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
47
src/output.rs
Normal file
47
src/output.rs
Normal file
@@ -0,0 +1,47 @@
|
||||
use std::io::IsTerminal;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// Output format for all commands.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub enum OutputMode {
|
||||
/// Human-readable text (default when stdout is a TTY)
|
||||
#[default]
|
||||
Text,
|
||||
/// Pretty-printed JSON
|
||||
Json,
|
||||
/// Single-line JSON (default when stdout is NOT a TTY, e.g. piped to jq)
|
||||
JsonCompact,
|
||||
/// KEY=VALUE pairs suitable for `source` or `.env` files
|
||||
Env,
|
||||
}
|
||||
|
||||
impl FromStr for OutputMode {
|
||||
type Err = anyhow::Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"text" => Ok(Self::Text),
|
||||
"json" => Ok(Self::Json),
|
||||
"json-compact" => Ok(Self::JsonCompact),
|
||||
"env" => Ok(Self::Env),
|
||||
other => Err(anyhow::anyhow!(
|
||||
"Unknown output format '{}'. Valid: text, json, json-compact, env",
|
||||
other
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the effective output mode.
|
||||
/// - Explicit value from `--output` takes priority.
|
||||
/// - TTY → text; non-TTY (piped/redirected) → json-compact.
|
||||
pub fn resolve_output_mode(explicit: Option<&str>) -> anyhow::Result<OutputMode> {
|
||||
if let Some(s) = explicit {
|
||||
return s.parse();
|
||||
}
|
||||
if std::io::stdout().is_terminal() {
|
||||
Ok(OutputMode::Text)
|
||||
} else {
|
||||
Ok(OutputMode::JsonCompact)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user