Compare commits

..

4 Commits

Author SHA1 Message Date
voson
535683b15c feat: 添加结构化日志与审计
Some checks failed
Secrets CLI - Build & Release / 版本 & Release (push) Successful in 3s
Secrets CLI - Build & Release / 质量检查 (fmt / clippy / test) (push) Successful in 1m17s
Secrets CLI - Build & Release / 通知 (push) Successful in 6s
Secrets CLI - Build & Release / 发布草稿 Release (push) Has been cancelled
Secrets CLI - Build & Release / Build (aarch64-apple-darwin) (push) Has started running
Secrets CLI - Build & Release / Build (x86_64-pc-windows-msvc) (push) Has been cancelled
Secrets CLI - Build & Release / Build (x86_64-unknown-linux-musl) (push) Has been cancelled
- tracing + tracing-subscriber,全局 --verbose/-v 与 RUST_LOG 控制
- 新增 audit_log 表,add/update/delete 成功后自动写入审计记录
- 新增 src/audit.rs,审计失败仅 warn 不中断主流程
- 更新 README/AGENTS.md,补充 verbose、audit_log 说明
- .vscode/tasks.json 增加 verbose/update/audit 测试任务

Made-with: Cursor
2026-03-18 16:30:42 +08:00
voson
9620ff1923 feat(config): persist database URL to ~/.config/secrets/config.toml
- Add 'secrets config set-db/show/path' subcommands
- Remove dotenvy and DATABASE_URL env var support
- Config file created with 0600 permission
- Bump version to 0.3.0

Made-with: Cursor
2026-03-18 16:19:11 +08:00
voson
e6db23bd6d fix(ci): 移除 probe-runners,用变量控制 build,解耦 notify
Some checks failed
Secrets CLI - Build & Release / 版本 & Release (push) Successful in 2s
Secrets CLI - Build & Release / 质量检查 (fmt / clippy / test) (push) Successful in 21s
Secrets CLI - Build & Release / 通知 (push) Successful in 7s
Secrets CLI - Build & Release / Build (aarch64-apple-darwin) (push) Successful in 28s
Secrets CLI - Build & Release / Build (x86_64-unknown-linux-musl) (push) Successful in 35s
Secrets CLI - Build & Release / 发布草稿 Release (push) Successful in 0s
Secrets CLI - Build & Release / Build (x86_64-pc-windows-msvc) (push) Has been cancelled
- 删除探测 Runner job(API 解析不可靠,且 always() 导致 job 被错误调度)
- build-linux: 仅 needs version+check,默认执行
- build-macos: if vars.BUILD_MACOS != 'false'(默认开,runner 离线时设 false)
- build-windows: if vars.BUILD_WINDOWS == 'true'(默认关,无 runner)
- publish-release: 仅依赖 build-linux,避免被 macOS/Windows 阻塞
- notify: 仅 needs version+check + always(),失败也能发飞书;build 状态通过 API 查询

Made-with: Cursor
2026-03-18 16:04:16 +08:00
voson
c61c8292aa fix: CI 无 DB 下 clippy 通过 + 失败时也发飞书通知
Some checks failed
Secrets CLI - Build & Release / 探测 Runner (push) Successful in 1s
Secrets CLI - Build & Release / Build (aarch64-apple-darwin) (push) Has been skipped
Secrets CLI - Build & Release / Build (x86_64-unknown-linux-musl) (push) Has been skipped
Secrets CLI - Build & Release / 版本 & Release (push) Successful in 2s
Secrets CLI - Build & Release / 质量检查 (fmt / clippy / test) (push) Successful in 34s
Secrets CLI - Build & Release / 发布草稿 Release (push) Has been cancelled
Secrets CLI - Build & Release / 通知 (push) Has been cancelled
Secrets CLI - Build & Release / Build (x86_64-pc-windows-msvc) (push) Has been cancelled
- update.rs: sqlx::query! 改为 query/query_as,不依赖编译期 DB
- workflow: build job 加 always() 且 check.result==success,失败时 notify 能执行

Made-with: Cursor
2026-03-18 15:50:10 +08:00
16 changed files with 632 additions and 151 deletions

View File

@@ -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: 10
steps:
- name: 安装依赖
run: |
@@ -276,10 +210,10 @@ jobs:
build-macos:
name: Build (aarch64-apple-darwin)
needs: [version, probe-runners, check]
if: needs.probe-runners.outputs.has_macos == 'true'
needs: [version, check]
if: vars.BUILD_MACOS != 'false'
runs-on: darwin-arm64
timeout-minutes: 1
timeout-minutes: 10
steps:
- name: 安装依赖
run: |
@@ -323,10 +257,10 @@ jobs:
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]
if: vars.BUILD_WINDOWS == 'true'
runs-on: windows
timeout-minutes: 1
timeout-minutes: 10
steps:
- name: 安装依赖
shell: pwsh
@@ -374,8 +308,8 @@ jobs:
publish-release:
name: 发布草稿 Release
needs: [version, check, build-linux, build-macos, build-windows]
if: always() && needs.version.outputs.release_id != ''
needs: [version, build-linux]
if: needs.version.outputs.release_id != ''
runs-on: debian
timeout-minutes: 2
steps:
@@ -385,21 +319,11 @@ jobs:
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}' \
@@ -416,7 +340,7 @@ jobs:
notify:
name: 通知
needs: [version, probe-runners, check, build-linux, build-macos, build-windows, publish-release]
needs: [version, check]
if: always() && github.event_name == 'push'
runs-on: debian
timeout-minutes: 1
@@ -427,6 +351,7 @@ jobs:
- name: 发送飞书通知
env:
WEBHOOK_URL: ${{ vars.WEBHOOK_URL }}
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
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)
@@ -438,25 +363,40 @@ jobs:
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 }}"
publish_r="${{ needs.publish-release.result }}"
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="构建成功 ✅"
# 通过 API 查询当前 run 的构建 job 状态best-effort
linux_r="unknown"; macos_r="unknown"; windows_r="unknown"; publish_r="unknown"
if [ -n "$RELEASE_TOKEN" ]; then
sleep 3
run_api="${{ github.server_url }}/api/v1/repos/${{ github.repository }}/actions/tasks"
http_code=$(curl -sS -o /tmp/jobs.json -w '%{http_code}' \
-H "Authorization: token $RELEASE_TOKEN" "$run_api" 2>/dev/null) || true
if [ "$http_code" = "200" ] && [ -f /tmp/jobs.json ]; then
get_status() {
jq -r --arg name "$1" '
(.workflow_runs // .task_runs // . // [])[]?
| select(.name == $name)
| .status // "unknown"
' /tmp/jobs.json 2>/dev/null | head -1
}
s=$(get_status "Build (x86_64-unknown-linux-musl)"); [ -n "$s" ] && linux_r="$s"
s=$(get_status "Build (aarch64-apple-darwin)"); [ -n "$s" ] && macos_r="$s"
s=$(get_status "Build (x86_64-pc-windows-msvc)"); [ -n "$s" ] && windows_r="$s"
s=$(get_status "发布草稿 Release"); [ -n "$s" ] && publish_r="$s"
fi
fi
if [ "$version_r" = "success" ] && [ "$check_r" = "success" ]; then
status="检查通过 ✅"
else
status="构建失败 ❌"
status="检查失败 ❌"
fi
icon() {
case "$1" in
success) echo "✅" ;;
skipped) echo "⏭" ;;
unknown) echo "⏳" ;;
*) echo "❌" ;;
esac
}
@@ -471,6 +411,7 @@ jobs:
fi
msg="${msg}
质量检查:$(icon "$check_r")
构建结果linux$(icon "$linux_r") macOS$(icon "$macos_r") windows$(icon "$windows_r")
Release$(icon "$publish_r")
提交:${commit}

44
.vscode/tasks.json vendored
View File

@@ -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",

View File

@@ -7,19 +7,22 @@
```
secrets/
src/
main.rs # CLI 入口clap 命令定义auto-migrate
db.rs # PgPool 创建 + 建表/索引(幂等
main.rs # CLI 入口clap 命令定义auto-migrate--verbose 全局参数
config.rs # 配置读写:~/.config/secrets/config.tomldatabase_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
config.rs # config 命令set-db / show / path持久化 database_url
search.rs # search 命令:多条件动态查询
delete.rs # delete 命令
update.rs # update 命令:增量更新(合并 tags/metadata/encrypted
scripts/
seed-data.sh # 从 refining/ricnsmart config.toml 导入全量数据
.gitea/workflows/
secrets.yml # CIfmt + clippy + musl 构建 + Release 上传 + 飞书通知
.vscode/tasks.json # 本地测试任务build / search / add+delete roundtrip 等)
.env # DATABASE_URLgitignore不提交
.vscode/tasks.json # 本地测试任务build / config / search / add+delete / update / audit 等)
```
## 数据库
@@ -27,7 +30,7 @@ secrets/
- **Host**: `47.117.131.22:5432`(阿里云上海 ECSPostgreSQL 18 with io_uring
- **Database**: `secrets`
- **连接串**: `postgres://postgres:<password>@47.117.131.22:5432/secrets`
- **表**: 单张 `secrets`首次连接自动建表auto-migrate
- **表**: `secrets`(主表)+ `audit_log`(审计表)首次连接自动建表auto-migrate
### 表结构
@@ -46,6 +49,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,6 +75,18 @@ secrets (
| `metadata` | 明文非敏感信息 | `{"ip":"47.243.154.187","desc":"Grafana","domains":["..."]}` |
| `encrypted` | 敏感凭据MVP 阶段明文存储,后续对 value 加密) | `{"ssh_key":"-----BEGIN...","password":"..."}` |
## 数据库配置
首次使用需显式配置数据库连接,设置一次后在该设备上持久生效:
```bash
secrets config set-db "postgres://postgres:<password>@47.117.131.22:5432/secrets"
secrets config show # 查看当前配置(密码脱敏)
secrets config path # 打印配置文件路径
```
配置文件:`~/.config/secrets/config.toml`,权限 0600。`--db-url` 参数可一次性覆盖。
## CLI 命令
```bash
@@ -77,6 +107,11 @@ secrets add -n <namespace> --kind <kind> --name <name> \
secrets search [-n <namespace>] [--kind <kind>] [--tag <tag>] [-q <keyword>] [--show-secrets]
# -q 匹配范围name、namespace、kind、metadata 全文内容、tags
# 开启 debug 级别日志(全局参数,位于子命令之前)
secrets --verbose <subcommand>
secrets -v <subcommand>
# 或通过环境变量控制RUST_LOG=secrets=trace secrets search
# 增量更新已有记录(合并语义,记录不存在则报错)
secrets update -n <namespace> --kind <kind> --name <name> \
[--add-tag <tag>]... # 添加标签(不影响已有标签)
@@ -88,6 +123,11 @@ secrets update -n <namespace> --kind <kind> --name <name> \
# 删除
secrets delete -n <namespace> --kind <kind> --name <name>
# 配置(持久化 database_url设置一次即可
secrets config set-db <url>
secrets config show
secrets config path
```
### 示例
@@ -134,7 +174,9 @@ 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
- 日志:用户可见输出用 `println!`;调试/运维信息用 `tracing::debug!`/`info!`/`warn!`/`error!`
- 审计:`add`/`update`/`delete` 成功后调用 `audit::log()`,写入 `audit_log` 表;失败只 warn 不中断
## 提交前检查(必须全部通过)
@@ -181,4 +223,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
View File

@@ -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.3.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"

View File

@@ -1,16 +1,18 @@
[package]
name = "secrets"
version = "0.2.0"
version = "0.3.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"] }

View File

@@ -11,11 +11,10 @@ cargo build --release
# 或从 Release 页面下载预编译二进制
```
配置数据库连接:
配置数据库连接(首次使用需执行一次,之后在该设备上持久生效)
```bash
export DATABASE_URL=postgres://postgres:<password>@<host>:5432/secrets
# 或在项目根目录创建 .env 文件写入上述变量
secrets config set-db "postgres://postgres:<password>@<host>:5432/secrets"
```
## 使用
@@ -30,6 +29,7 @@ secrets --help
secrets -h
# 查看子命令帮助
secrets help config
secrets help add
secrets help search
secrets help delete
@@ -54,6 +54,13 @@ secrets search --tag hongkong
secrets search -q mqtt # 关键词匹配 name / metadata / tags
secrets search -n refining --kind service --name gitea --show-secrets
# 开启 debug 级别日志(--verbose / -v全局参数
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 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>
@@ -65,7 +72,7 @@ secrets delete -n refining --kind server --name my-server
## 数据模型
单张 `secrets` 表,首次连接自动建表。
单张 `secrets` 表,首次连接自动建表;同时自动创建 `audit_log` 表,记录所有写操作
| 字段 | 说明 |
|------|------|
@@ -78,15 +85,30 @@ 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
config.rs # 配置读写(~/.config/secrets/config.toml
db.rs # 连接池 + auto-migratesecrets + audit_log
models.rs # Secret 结构体
audit.rs # 审计日志写入audit_log 表)
commands/
add.rs # upsert
config.rs # config set-db/show/path
search.rs # 多条件查询
delete.rs # 删除
update.rs # 增量更新(合并 tags/metadata/encrypted

34
src/audit.rs Normal file
View 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");
}
}

View File

@@ -1,5 +1,5 @@
use anyhow::Result;
use serde_json::{Map, Value};
use serde_json::{Map, Value, json};
use sqlx::PgPool;
use std::fs;
@@ -43,6 +43,8 @@ pub async fn run(
let metadata = build_json(meta_entries)?;
let encrypted = build_json(secret_entries)?;
tracing::debug!(namespace, kind, name, "upserting record");
sqlx::query(
r#"
INSERT INTO secrets (namespace, kind, name, tags, metadata, encrypted, updated_at)
@@ -64,23 +66,38 @@ pub async fn run(
.execute(pool)
.await?;
let meta_keys: Vec<&str> = meta_entries
.iter()
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
.collect();
let secret_keys: Vec<&str> = secret_entries
.iter()
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
.collect();
crate::audit::log(
pool,
"add",
namespace,
kind,
name,
json!({
"tags": tags,
"meta_keys": meta_keys,
"secret_keys": secret_keys,
}),
)
.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(", "));
println!(" metadata: {}", meta_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(", "));
println!(" secrets: {}", secret_keys.join(", "));
}
Ok(())

54
src/commands/config.rs Normal file
View 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()
}

View File

@@ -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(())

View File

@@ -1,4 +1,5 @@
pub mod add;
pub mod config;
pub mod delete;
pub mod search;
pub mod update;

View File

@@ -44,6 +44,8 @@ pub async fn run(
where_clause
);
tracing::debug!(sql, "executing search query");
let mut q = sqlx::query_as::<_, Secret>(&sql);
if let Some(v) = namespace {
q = q.bind(v);

View File

@@ -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
View 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")
}

View File

@@ -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(())
}

View File

@@ -1,10 +1,12 @@
mod audit;
mod commands;
mod config;
mod db;
mod models;
use anyhow::Result;
use clap::{Parser, Subcommand};
use dotenvy::dotenv;
use tracing_subscriber::EnvFilter;
#[derive(Parser)]
#[command(
@@ -13,10 +15,14 @@ use dotenvy::dotenv;
about = "Secrets & config manager backed by PostgreSQL"
)]
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,
}
@@ -107,22 +113,54 @@ enum Commands {
#[arg(long = "remove-secret")]
remove_secrets: Vec<String>,
},
/// Manage CLI configuration (database connection, etc.)
Config {
#[command(subcommand)]
action: ConfigAction,
},
}
#[derive(Subcommand)]
enum ConfigAction {
/// Save database URL to config file (~/.config/secrets/config.toml)
SetDb {
/// PostgreSQL connection string
url: String,
},
/// Show current configuration
Show,
/// Print path to 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?;
@@ -135,6 +173,8 @@ async fn main() -> Result<()> {
meta,
secrets,
} => {
let _span =
tracing::info_span!("cmd", command = "add", %namespace, %kind, %name).entered();
commands::add::run(&pool, namespace, kind, name, tags, meta, secrets).await?;
}
Commands::Search {
@@ -144,6 +184,7 @@ async fn main() -> Result<()> {
query,
show_secrets,
} => {
let _span = tracing::info_span!("cmd", command = "search").entered();
commands::search::run(
&pool,
namespace.as_deref(),
@@ -159,6 +200,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 +215,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 +233,7 @@ async fn main() -> Result<()> {
)
.await?;
}
Commands::Config { .. } => unreachable!(),
}
Ok(())