Compare commits

...

20 Commits

Author SHA1 Message Date
voson
8fdb6db87b feat: 客户端加密 encrypted 字段,数据库只存密文 (v0.5.0)
Some checks failed
Secrets CLI - Build & Release / 质量检查 (fmt / clippy / test) (push) Successful in 1m27s
Secrets CLI - Build & Release / 版本 & Release (push) Successful in 2s
Secrets CLI - Build & Release / Build (x86_64-unknown-linux-musl) (push) Successful in 1m14s
Secrets CLI - Build & Release / 发布草稿 Release (push) Successful in 2s
Secrets CLI - Build & Release / Build (aarch64-apple-darwin) (push) Failing after 11m1s
Secrets CLI - Build & Release / Build (x86_64-pc-windows-msvc) (push) Has been cancelled
- 新增 src/crypto.rs:AES-256-GCM 加解密 + Argon2id 密钥派生 + OS Keychain 读写
- 新增 `secrets init` 命令:输入 Master Password,派生 Master Key 存入 Keychain
- 新增 `secrets migrate-encrypt` 命令:将旧明文 JSONB 数据批量加密
- 修改 db.rs:encrypted 列 JSONB → BYTEA,新增 kv_config 表(存 Argon2id salt)
- 修改 models.rs:encrypted 字段类型 Value → Vec<u8>
- 修改 add/update:写入前 encrypt_json,update 读取后 decrypt → 合并 → 重新加密
- 修改 search:按需解密,未解密时显示 _encrypted:true/_key_count:N
- 通过 6 个 crypto 单元测试(加解密、JSON roundtrip、Argon2id 确定性)

Made-with: Cursor
2026-03-18 20:10:13 +08:00
voson
1f7984d798 feat: AI 优先的 search 增强与结构化输出 (v0.4.0)
Some checks failed
Secrets CLI - Build & Release / 质量检查 (fmt / clippy / test) (push) Successful in 57s
Secrets CLI - Build & Release / Build (aarch64-apple-darwin) (push) Successful in 33s
Secrets CLI - Build & Release / 版本 & Release (push) Successful in 2s
Secrets CLI - Build & Release / Build (x86_64-unknown-linux-musl) (push) Successful in 44s
Secrets CLI - Build & Release / 发布草稿 Release (push) Successful in 2s
Secrets CLI - Build & Release / Build (x86_64-pc-windows-msvc) (push) Has been cancelled
- search: 新增 --name、-f/--field、-o/--output、--summary、--limit、--offset、--sort
- search: 非 TTY 自动输出 json-compact,便于 AI 解析
- search: -f secret.* 自动解锁 secrets
- add: 支持 -o json/json-compact 输出
- add: 重构为 AddArgs 结构体
- 全局: 各子命令 after_help 补充典型值示例
- output.rs: OutputMode 枚举 + TTY 检测
- 文档: README/AGENTS 面向 AI 的用法,连接串改为 <host>:<port>

Made-with: Cursor
2026-03-18 17:17:43 +08:00
voson
140162f39a ci(secrets): 飞书通知分散到各构建 job,放宽超时与构建条件
Some checks failed
Secrets CLI - Build & Release / 版本 & Release (push) Successful in 2s
Secrets CLI - Build & Release / 质量检查 (fmt / clippy / test) (push) Successful in 29s
Secrets CLI - Build & Release / Build (aarch64-apple-darwin) (push) Successful in 45s
Secrets CLI - Build & Release / Build (x86_64-unknown-linux-musl) (push) Successful in 1m18s
Secrets CLI - Build & Release / 发布草稿 Release (push) Successful in 2s
Secrets CLI - Build & Release / Build (x86_64-pc-windows-msvc) (push) Has been cancelled
- 各 build job 超时 10→15min,publish-release 2→5min
- 移除 build-macos/build-windows 的 if 条件,默认全平台构建
- 删除独立 notify job,在各 build job 内增加飞书单 job 通知
- 汇总通知并入 publish-release,用 needs 取状态不再调 API
- publish-release 增加 if: always() 与 checkout 步骤

Made-with: Cursor
2026-03-18 16:32:45 +08:00
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
voson
c1d86bc96d feat: add update command, bump to 0.2.0, doc version check
Some checks failed
Secrets CLI - Build & Release / 探测 Runner (push) Successful in 1s
Secrets CLI - Build & Release / 版本 & Release (push) Successful in 3s
Secrets CLI - Build & Release / 质量检查 (fmt / clippy / test) (push) Failing after 21s
Secrets CLI - Build & Release / Build (x86_64-unknown-linux-musl) (push) Has been skipped
Secrets CLI - Build & Release / Build (aarch64-apple-darwin) (push) Has been skipped
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
- add secrets update: incremental merge for tags/metadata/encrypted
- AGENTS.md: 提交前检查增加版本号与 git tag 说明
- README/AGENTS: update 命令文档与示例
- Cargo.toml 0.1.0 -> 0.2.0 (secrets-0.1.0 已存在)

Made-with: Cursor
2026-03-18 15:40:44 +08:00
voson
f87cf3fd20 fix: store RELEASE_TOKEN as raw value, not base64
Some checks failed
Secrets CLI - Build & Release / 版本 & Release (push) Successful in 2s
Secrets CLI - Build & Release / 质量检查 (fmt / clippy / test) (push) Successful in 23s
Secrets CLI - Build & Release / Build (x86_64-unknown-linux-musl) (push) Has been skipped
Secrets CLI - Build & Release / Build (aarch64-apple-darwin) (push) Has been skipped
Secrets CLI - Build & Release / 探测 Runner (push) Successful in 1s
Secrets CLI - Build & Release / 通知 (push) Has been cancelled
Secrets CLI - Build & Release / Build (x86_64-pc-windows-msvc) (push) Has been cancelled
Gitea Actions secrets API stores the data field as-is, base64 encoding caused CI to use the encoded string as the token, resulting in 401.

Made-with: Cursor
2026-03-18 15:27:05 +08:00
voson
1aef267bbd ci: fix runner probe curl error and re-sync RELEASE_TOKEN
Some checks failed
Secrets CLI - Build & Release / 版本 & Release (push) Successful in 2s
Secrets CLI - Build & Release / 探测 Runner (push) Successful in 1s
Secrets CLI - Build & Release / 质量检查 (fmt / clippy / test) (push) Successful in 23s
Secrets CLI - Build & Release / Build (aarch64-apple-darwin) (push) Successful in 20s
Secrets CLI - Build & Release / Build (x86_64-unknown-linux-musl) (push) Successful in 27s
Secrets CLI - Build & Release / 通知 (push) Has been cancelled
Secrets CLI - Build & Release / Build (x86_64-pc-windows-msvc) (push) Has been cancelled
- Replace curl -fsS with HTTP status code check in probe-runners to avoid ugly 401 errors
- Graceful fallback: API failure defaults to trying all platforms
- RELEASE_TOKEN re-synced with correct PAT value

Made-with: Cursor
2026-03-18 15:18:03 +08:00
voson
2ad1abe846 ci: fix release 401 handling and notify based on actual results
Some checks failed
Secrets CLI - Build & Release / 版本 & Release (push) Successful in 2s
Secrets CLI - Build & Release / 探测 Runner (push) Successful in 1s
Secrets CLI - Build & Release / 质量检查 (fmt / clippy / test) (push) Successful in 22s
Secrets CLI - Build & Release / Build (aarch64-apple-darwin) (push) Successful in 18s
Secrets CLI - Build & Release / Build (x86_64-unknown-linux-musl) (push) Successful in 27s
Secrets CLI - Build & Release / 通知 (push) Has been cancelled
Secrets CLI - Build & Release / Build (x86_64-pc-windows-msvc) (push) Has been cancelled
- Replace curl -fsS with HTTP status code checking to avoid hard failures on 401/404
- Release creation failure no longer blocks the entire workflow, just skips asset upload
- Notification now depends on all jobs and reports actual success/failure per platform

Made-with: Cursor
2026-03-18 15:04:07 +08:00
voson
010001a4f4 ci: fix version parsing and release backfill
Some checks failed
Secrets CLI - Build & Release / 通知 (push) Successful in 2s
Secrets CLI - Build & Release / Build (x86_64-pc-windows-msvc) (push) Has been cancelled
Secrets CLI - Build & Release / 版本 & Release (push) Failing after 1s
Secrets CLI - Build & Release / 探测 Runner (push) Successful in 0s
Secrets CLI - Build & Release / 质量检查 (fmt / clippy / test) (push) Successful in 21s
Secrets CLI - Build & Release / Build (x86_64-unknown-linux-musl) (push) Has been skipped
Secrets CLI - Build & Release / Build (aarch64-apple-darwin) (push) Has been skipped
Avoid failing the version step when there is no previous tag, and keep creating a release when the tag already exists but the release page is missing.

Made-with: Cursor
2026-03-18 15:00:10 +08:00
voson
0f7c151c89 chore: update .gitignore to include .DS_Store
Some checks failed
Secrets CLI - Build & Release / 版本 & Release (push) Failing after 2s
Secrets CLI - Build & Release / 探测 Runner (push) Successful in 0s
Secrets CLI - Build & Release / 通知 (push) Successful in 2s
Secrets CLI - Build & Release / 质量检查 (fmt / clippy / test) (push) Successful in 24s
Secrets CLI - Build & Release / Build (x86_64-unknown-linux-musl) (push) Has been skipped
Secrets CLI - Build & Release / Build (aarch64-apple-darwin) (push) Has been skipped
Secrets CLI - Build & Release / Build (x86_64-pc-windows-msvc) (push) Has been cancelled
2026-03-18 14:56:57 +08:00
voson
a3a92e073f ci: Release 正文仅保留变更日志,使用说明见 README
Made-with: Cursor
2026-03-18 14:55:31 +08:00
voson
3d00b65f55 Revert "ci: decouple notify from build to avoid blocking release"
This reverts commit 1acc2537b3.
2026-03-18 14:43:45 +08:00
voson
1acc2537b3 ci: decouple notify from build to avoid blocking release
Some checks failed
Secrets CLI - Build & Release / 版本 & Release (push) Successful in 1s
Secrets CLI - Build & Release / 通知 (push) Successful in 2s
Secrets CLI - Build & Release / 质量检查 (fmt / clippy / test) (push) Successful in 23s
Secrets CLI - Build & Release / Build (aarch64-apple-darwin) (push) Successful in 20s
Secrets CLI - Build & Release / Build (x86_64-unknown-linux-musl) (push) Successful in 28s
Secrets CLI - Build & Release / Build (x86_64-pc-windows-msvc) (push) Has been cancelled
Make notification fire independently of matrix builds so stalled runners do not block release publishing.

Made-with: Cursor
2026-03-18 14:41:59 +08:00
voson
9a562be4e4 ci: reduce check job timeout to 1 minute for efficiency
Some checks failed
Secrets CLI - Build & Release / 版本 & Release (push) Successful in 1s
Secrets CLI - Build & Release / 质量检查 (fmt / clippy / test) (push) Successful in 24s
Secrets CLI - Build & Release / Build (aarch64-apple-darwin) (push) Successful in 15s
Secrets CLI - Build & Release / Build (x86_64-unknown-linux-musl) (push) Successful in 26s
Secrets CLI - Build & Release / 通知 (push) Has been cancelled
Secrets CLI - Build & Release / Build (x86_64-pc-windows-msvc) (push) Has been cancelled
2026-03-18 14:36:14 +08:00
voson
3203984fb4 ci: 优化 workflow,拆分 check job,预创建 Release,超时 10m
Some checks failed
Secrets CLI - Build & Release / 版本 & Release (push) Successful in 1s
Secrets CLI - Build & Release / 质量检查 (fmt / clippy / test) (push) Successful in 2m20s
Secrets CLI - Build & Release / Build (aarch64-apple-darwin) (push) Successful in 53s
Secrets CLI - Build & Release / Build (x86_64-unknown-linux-musl) (push) Successful in 2m48s
Secrets CLI - Build & Release / 通知 (push) Has been cancelled
Secrets CLI - Build & Release / Build (x86_64-pc-windows-msvc) (push) Has been cancelled
- 新增 check job:fmt/clippy/test 仅在 Linux 跑一次
- version job 预创建 Release,消除多 job 竞态
- build job 只编译+上传,加 --locked
- 超时从 30m 改为 10m
- AGENTS.md 补充提交前检查规范

Made-with: Cursor
2026-03-18 14:30:54 +08:00
voson
52ee858fd7 fix: use tls-rustls for musl builds; fix clippy collapsible-if
Some checks failed
Secrets CLI - Build & Release / 检查版本 (push) Successful in 1s
Secrets CLI - Build & Release / Build (aarch64-apple-darwin) (push) Successful in 1m2s
Secrets CLI - Build & Release / Build (x86_64-unknown-linux-musl) (push) Successful in 3m14s
Secrets CLI - Build & Release / 发送通知 (push) Has been cancelled
Secrets CLI - Build & Release / Build (x86_64-pc-windows-msvc) (push) Has been cancelled
- Switch sqlx from tls-native-tls to tls-rustls to avoid OpenSSL
  pkg-config cross-compilation issues on x86_64-unknown-linux-musl
- Collapse nested if-let in search.rs to satisfy clippy::collapsible-if

Made-with: Cursor
2026-03-18 14:18:25 +08:00
voson
3b338be2d2 style: cargo fmt — fix rustfmt formatting
Some checks failed
Secrets CLI - Build & Release / 检查版本 (push) Successful in 1s
Secrets CLI - Build & Release / Build (x86_64-unknown-linux-musl) (push) Failing after 31s
Secrets CLI - Build & Release / Build (aarch64-apple-darwin) (push) Failing after 37s
Secrets CLI - Build & Release / Build (x86_64-pc-windows-msvc) (push) Has been cancelled
Secrets CLI - Build & Release / 发送通知 (push) Has been cancelled
Made-with: Cursor
2026-03-18 14:13:37 +08:00
23 changed files with 2844 additions and 570 deletions

View File

@@ -24,120 +24,127 @@ env:
RUST_BACKTRACE: short
jobs:
# ========== 版本检查(只跑一次,供后续 job 共用)==========
version:
name: 检查版本
name: 版本 & Release
runs-on: debian
outputs:
version: ${{ steps.version.outputs.version }}
tag: ${{ steps.version.outputs.tag }}
tag_exists: ${{ steps.version.outputs.tag_exists }}
version: ${{ steps.ver.outputs.version }}
tag: ${{ steps.ver.outputs.tag }}
tag_exists: ${{ steps.ver.outputs.tag_exists }}
release_id: ${{ steps.release.outputs.release_id }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: 检查版本
id: version
- name: 解析版本
id: ver
run: |
version=$(grep -m1 '^version' Cargo.toml | sed 's/.*"\(.*\)".*/\1/')
tag="secrets-${version}"
echo "version=${version}" >> $GITHUB_OUTPUT
echo "tag=${tag}" >> $GITHUB_OUTPUT
previous_tag=$(git tag --list 'secrets-*' --sort=-v:refname | awk -v tag="$tag" '$0 != tag { print; exit }')
echo "version=${version}" >> "$GITHUB_OUTPUT"
echo "tag=${tag}" >> "$GITHUB_OUTPUT"
echo "previous_tag=${previous_tag}" >> "$GITHUB_OUTPUT"
if git rev-parse "refs/tags/${tag}" >/dev/null 2>&1; then
echo "tag_exists=true" >> $GITHUB_OUTPUT
echo "tag_exists=true" >> "$GITHUB_OUTPUT"
echo "版本 ${tag} 已存在"
else
echo "tag_exists=false" >> $GITHUB_OUTPUT
echo "tag_exists=false" >> "$GITHUB_OUTPUT"
echo "将创建新版本 ${tag}"
fi
- name: 创建 Tag
if: steps.version.outputs.tag_exists == 'false'
if: steps.ver.outputs.tag_exists == 'false'
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag -a "${{ steps.version.outputs.tag }}" -m "Release ${{ steps.version.outputs.tag }}"
git push origin "${{ steps.version.outputs.tag }}"
git tag -a "${{ steps.ver.outputs.tag }}" -m "Release ${{ steps.ver.outputs.tag }}"
git push origin "${{ steps.ver.outputs.tag }}"
# ========== 矩阵构建 ==========
build:
name: Build (${{ matrix.target }})
needs: version
continue-on-error: true # 某平台失败/超时不阻断其他平台和 notify
timeout-minutes: 30 # runner 不在线时 30 分钟后放弃
strategy:
fail-fast: false
matrix:
include:
- runner: debian
target: x86_64-unknown-linux-musl
archive_suffix: x86_64-linux-musl
os: linux
- runner: darwin-arm64
target: aarch64-apple-darwin
archive_suffix: aarch64-macos
os: macos
- runner: windows
target: x86_64-pc-windows-msvc
archive_suffix: x86_64-windows
os: windows
- name: 解析或创建 Release
id: release
env:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: |
if [ -z "$RELEASE_TOKEN" ]; then
echo "release_id=" >> "$GITHUB_OUTPUT"
exit 0
fi
runs-on: ${{ matrix.runner }}
command -v jq >/dev/null 2>&1 || (sudo apt-get update -qq && sudo apt-get install -y -qq jq)
tag="${{ steps.ver.outputs.tag }}"
version="${{ steps.ver.outputs.version }}"
release_api="${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases"
http_code=$(curl -sS -o /tmp/release.json -w '%{http_code}' \
-H "Authorization: token $RELEASE_TOKEN" \
"${release_api}/tags/${tag}")
if [ "$http_code" = "200" ]; then
release_id=$(jq -r '.id // empty' /tmp/release.json)
if [ -n "$release_id" ]; then
echo "已找到现有 Release: ${release_id}"
echo "release_id=${release_id}" >> "$GITHUB_OUTPUT"
exit 0
fi
fi
previous_tag="${{ steps.ver.outputs.previous_tag }}"
if [ -n "$previous_tag" ]; then
changes=$(git log --pretty=format:'- %s (%h)' "${previous_tag}..HEAD")
else
changes=$(git log --pretty=format:'- %s (%h)')
fi
[ -z "$changes" ] && changes="- 首次发布"
body=$(printf '## 变更日志\n\n%s' "$changes")
payload=$(jq -n \
--arg tag "$tag" \
--arg name "${{ env.BINARY_NAME }} ${version}" \
--arg body "$body" \
'{tag_name: $tag, name: $name, body: $body, draft: true}')
http_code=$(curl -sS -o /tmp/create-release.json -w '%{http_code}' \
-H "Authorization: token $RELEASE_TOKEN" \
-H "Content-Type: application/json" \
-X POST "$release_api" \
-d "$payload")
if [ "$http_code" = "201" ] || [ "$http_code" = "200" ]; then
release_id=$(jq -r '.id // empty' /tmp/create-release.json)
fi
if [ -n "$release_id" ]; then
echo "已创建草稿 Release: ${release_id}"
echo "release_id=${release_id}" >> "$GITHUB_OUTPUT"
else
echo "⚠ 创建 Release 失败 (HTTP ${http_code}),跳过产物上传"
cat /tmp/create-release.json 2>/dev/null || true
echo "release_id=" >> "$GITHUB_OUTPUT"
fi
check:
name: 质量检查 (fmt / clippy / test)
runs-on: debian
timeout-minutes: 10
steps:
# ========== 环境准备 ==========
- name: 安装依赖 (Linux)
if: matrix.os == 'linux'
- name: 安装 Rust
run: |
sudo apt-get update
sudo apt-get install -y jq curl git pkg-config musl-tools binutils
if ! command -v cargo &>/dev/null; then
echo "安装 Rust 工具链..."
if ! command -v cargo >/dev/null 2>&1; then
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
source "$HOME/.cargo/env"
rustup component add rustfmt clippy
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
fi
rustup target add ${{ matrix.target }}
echo "$HOME/.cargo/bin" >> $GITHUB_PATH
- name: 安装依赖 (macOS)
if: matrix.os == 'macos'
run: |
brew install jq
if ! command -v cargo &>/dev/null; then
echo "安装 Rust 工具链..."
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
source "$HOME/.cargo/env"
rustup component add rustfmt clippy
fi
rustup target add ${{ matrix.target }}
echo "$HOME/.cargo/bin" >> $GITHUB_PATH
- name: 安装依赖 (Windows)
if: matrix.os == 'windows'
shell: pwsh
run: |
# 检查 Rust 是否已安装
if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) {
Write-Host "安装 Rust 工具链..."
Invoke-WebRequest -Uri "https://win.rustup.rs/x86_64" -OutFile rustup-init.exe
.\rustup-init.exe -y --default-toolchain stable
Remove-Item rustup-init.exe
}
source "$HOME/.cargo/env" 2>/dev/null || true
rustup component add rustfmt clippy
rustup target add ${{ matrix.target }}
- uses: actions/checkout@v4
with:
fetch-depth: 0
# ========== Cargo 缓存 ==========
- name: 缓存 Cargo 依赖
- name: 缓存 Cargo
uses: actions/cache@v4
with:
path: |
@@ -145,169 +152,288 @@ jobs:
~/.cargo/registry/cache
~/.cargo/git/db
target
key: cargo-secrets-${{ matrix.target }}-${{ hashFiles('Cargo.lock') }}
key: cargo-check-${{ hashFiles('Cargo.lock') }}
restore-keys: |
cargo-secrets-${{ matrix.target }}-
cargo-check-
- name: 检查代码格式
if: matrix.os != 'windows'
run: cargo fmt -- --check
- run: cargo fmt -- --check
- run: cargo clippy --locked -- -D warnings
- run: cargo test --locked
- name: 检查代码格式 (Windows)
if: matrix.os == 'windows'
shell: pwsh
run: cargo fmt -- --check
- name: 运行 Clippy 检查
if: matrix.os != 'windows'
run: cargo clippy --release --target ${{ matrix.target }} -- -D warnings
- name: 运行 Clippy 检查 (Windows)
if: matrix.os == 'windows'
shell: pwsh
run: cargo clippy --release --target ${{ matrix.target }} -- -D warnings
- name: 构建
if: matrix.os != 'windows'
env:
GIT_TAG: ${{ needs.version.outputs.version }}
run: cargo build --release --target ${{ matrix.target }} --verbose
- name: 构建 (Windows)
if: matrix.os == 'windows'
shell: pwsh
env:
GIT_TAG: ${{ needs.version.outputs.version }}
run: cargo build --release --target ${{ matrix.target }} --verbose
- name: Strip 二进制 (Linux)
if: matrix.os == 'linux'
run: strip target/${{ matrix.target }}/release/${{ env.BINARY_NAME }}
- name: Strip 二进制 (macOS)
if: matrix.os == 'macos'
run: strip -x target/${{ matrix.target }}/release/${{ env.BINARY_NAME }}
# ========== 上传 Release 产物 ==========
- name: 上传 Release 产物 (Linux/macOS)
if: needs.version.outputs.tag_exists == 'false' && matrix.os != 'windows'
env:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: |
[ -z "$RELEASE_TOKEN" ] && echo "跳过:未配置 RELEASE_TOKEN" && exit 0
tag="${{ needs.version.outputs.tag }}"
binary="target/${{ matrix.target }}/release/${{ env.BINARY_NAME }}"
archive="${{ env.BINARY_NAME }}-${tag}-${{ matrix.archive_suffix }}.tar.gz"
tar -czf "$archive" -C "$(dirname $binary)" "$(basename $binary)"
# 查找已有 Release由首个完成的 job 创建,后续 job 直接上传)
release_url="${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases"
release_id=$(curl -sS -H "Authorization: token $RELEASE_TOKEN" \
"${release_url}/tags/${tag}" | jq -r '.id // empty')
if [ -z "$release_id" ]; then
release_id=$(curl -sS -H "Authorization: token $RELEASE_TOKEN" \
-H "Content-Type: application/json" \
-X POST "$release_url" \
-d "{\"tag_name\": \"${tag}\", \"name\": \"${tag}\", \"body\": \"Release ${tag}\"}" \
| jq -r '.id')
fi
upload_url="${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${release_id}/assets"
curl -sS -H "Authorization: token $RELEASE_TOKEN" \
-F "attachment=@${archive}" \
"$upload_url"
echo "已上传: ${archive} → Release ${tag}"
- name: 上传 Release 产物 (Windows)
if: needs.version.outputs.tag_exists == 'false' && matrix.os == 'windows'
shell: pwsh
env:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: |
if (-not $env:RELEASE_TOKEN) { Write-Host "跳过:未配置 RELEASE_TOKEN"; exit 0 }
$tag = "${{ needs.version.outputs.tag }}"
$binary = "target\${{ matrix.target }}\release\${{ env.BINARY_NAME }}.exe"
$archive = "${{ env.BINARY_NAME }}-${tag}-${{ matrix.archive_suffix }}.zip"
Compress-Archive -Path $binary -DestinationPath $archive
$headers = @{ "Authorization" = "token $env:RELEASE_TOKEN"; "Content-Type" = "application/json" }
$release_url = "${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases"
# 查找已有 Release
$existing = Invoke-RestMethod -Uri "${release_url}/tags/${tag}" -Headers $headers -ErrorAction SilentlyContinue
if ($existing.id) {
$release_id = $existing.id
} else {
$body = @{ tag_name = $tag; name = $tag; body = "Release ${tag}" } | ConvertTo-Json
$release_id = (Invoke-RestMethod -Uri $release_url -Method Post -Headers $headers -Body $body).id
}
$upload_url = "${release_url}/${release_id}/assets"
$upload_headers = @{ "Authorization" = "token $env:RELEASE_TOKEN" }
$form = @{ attachment = Get-Item $archive }
Invoke-RestMethod -Uri $upload_url -Method Post -Headers $upload_headers -Form $form
Write-Host "已上传: ${archive} → Release ${tag}"
# ========== 汇总通知 ==========
notify:
name: 发送通知
needs: [version, build]
if: always() && github.event_name == 'push'
build-linux:
name: Build (x86_64-unknown-linux-musl)
needs: [version, check]
runs-on: debian
timeout-minutes: 15
steps:
- name: 安装依赖
run: |
sudo apt-get update
sudo apt-get install -y pkg-config musl-tools binutils curl
if ! command -v cargo >/dev/null 2>&1; then
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
fi
source "$HOME/.cargo/env" 2>/dev/null || true
rustup target add x86_64-unknown-linux-musl
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- uses: actions/checkout@v4
- name: 发送通知
continue-on-error: true
- name: 缓存 Cargo
uses: actions/cache@v4
with:
path: |
~/.cargo/registry/index
~/.cargo/registry/cache
~/.cargo/git/db
target
key: cargo-x86_64-unknown-linux-musl-${{ hashFiles('Cargo.lock') }}
restore-keys: |
cargo-x86_64-unknown-linux-musl-
- run: cargo build --release --locked --target x86_64-unknown-linux-musl
- run: strip target/x86_64-unknown-linux-musl/release/${{ env.BINARY_NAME }}
- name: 上传 Release 产物
if: needs.version.outputs.release_id != ''
env:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: |
[ -z "$RELEASE_TOKEN" ] && exit 0
tag="${{ needs.version.outputs.tag }}"
bin="target/x86_64-unknown-linux-musl/release/${{ env.BINARY_NAME }}"
archive="${{ env.BINARY_NAME }}-${tag}-x86_64-linux-musl.tar.gz"
tar -czf "$archive" -C "$(dirname "$bin")" "$(basename "$bin")"
curl -fsS -H "Authorization: token $RELEASE_TOKEN" \
-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, check]
runs-on: darwin-arm64
timeout-minutes: 15
steps:
- name: 安装依赖
run: |
if ! command -v cargo >/dev/null 2>&1; then
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
fi
source "$HOME/.cargo/env" 2>/dev/null || true
rustup target add aarch64-apple-darwin
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- uses: actions/checkout@v4
- name: 缓存 Cargo
uses: actions/cache@v4
with:
path: |
~/.cargo/registry/index
~/.cargo/registry/cache
~/.cargo/git/db
target
key: cargo-aarch64-apple-darwin-${{ hashFiles('Cargo.lock') }}
restore-keys: |
cargo-aarch64-apple-darwin-
- run: cargo build --release --locked --target aarch64-apple-darwin
- run: strip -x target/aarch64-apple-darwin/release/${{ env.BINARY_NAME }}
- name: 上传 Release 产物
if: needs.version.outputs.release_id != ''
env:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: |
[ -z "$RELEASE_TOKEN" ] && exit 0
tag="${{ needs.version.outputs.tag }}"
bin="target/aarch64-apple-darwin/release/${{ env.BINARY_NAME }}"
archive="${{ env.BINARY_NAME }}-${tag}-aarch64-macos.tar.gz"
tar -czf "$archive" -C "$(dirname "$bin")" "$(basename "$bin")"
curl -fsS -H "Authorization: token $RELEASE_TOKEN" \
-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, check]
runs-on: windows
timeout-minutes: 15
steps:
- name: 安装依赖
shell: pwsh
run: |
if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) {
Invoke-WebRequest -Uri "https://win.rustup.rs/x86_64" -OutFile rustup-init.exe
.\rustup-init.exe -y --default-toolchain stable
Remove-Item rustup-init.exe
}
rustup target add x86_64-pc-windows-msvc
- uses: actions/checkout@v4
- name: 缓存 Cargo
uses: actions/cache@v4
with:
path: |
~/.cargo/registry/index
~/.cargo/registry/cache
~/.cargo/git/db
target
key: cargo-x86_64-pc-windows-msvc-${{ hashFiles('Cargo.lock') }}
restore-keys: |
cargo-x86_64-pc-windows-msvc-
- name: 构建
shell: pwsh
run: cargo build --release --locked --target x86_64-pc-windows-msvc
- name: 上传 Release 产物
if: needs.version.outputs.release_id != ''
shell: pwsh
env:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: |
if (-not $env:RELEASE_TOKEN) { exit 0 }
$tag = "${{ needs.version.outputs.tag }}"
$bin = "target\x86_64-pc-windows-msvc\release\${{ env.BINARY_NAME }}.exe"
$archive = "${{ env.BINARY_NAME }}-${tag}-x86_64-windows.zip"
Compress-Archive -Path $bin -DestinationPath $archive -Force
$url = "${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${{ needs.version.outputs.release_id }}/assets"
Invoke-RestMethod -Uri $url -Method Post `
-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, build-linux]
if: always() && needs.version.outputs.release_id != ''
runs-on: debian
timeout-minutes: 5
steps:
- uses: actions/checkout@v4
- name: 发布草稿
env:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: |
[ -z "$RELEASE_TOKEN" ] && exit 0
linux_r="${{ needs.build-linux.result }}"
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}' \
-H "Authorization: token $RELEASE_TOKEN" \
-H "Content-Type: application/json" \
-X PATCH "$release_api" \
-d '{"draft":false}')
if [ "$http_code" != "200" ]; then
echo "发布草稿 Release 失败 (HTTP ${http_code})"
cat /tmp/publish-release.json 2>/dev/null || true
exit 1
fi
echo "Release 已发布"
- 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 }}"
tag_exists="${{ needs.version.outputs.tag_exists }}"
build_result="${{ needs.build.result }}"
commit=$(git log -1 --pretty=format:"%s" 2>/dev/null || echo "N/A")
url="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}"
if [ "$build_result" = "success" ]; then
status_text="构建成功 ✅"
check_r="${{ needs.version.result }}"
linux_r="${{ needs.build-linux.result }}"
publish_r="${{ job.status }}"
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="构建失败 ❌"
else
status_text="构建失败 ❌"
status="发布失败 ❌"
fi
commit_title=$(git log -1 --pretty=format:"%s" 2>/dev/null || echo "N/A")
workflow_url="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}"
if [ "$build_result" != "success" ]; then
payload=$(jq -n \
--arg title "${{ env.BINARY_NAME }} ${status_text}" \
--arg commit "$commit_title" \
--arg version "$tag" \
--arg author "${{ github.actor }}" \
--arg url "$workflow_url" \
'{msg_type: "text", content: {text: "\($title)\n提交\($commit)\n版本\($version)\n作者\($author)\n详情\($url)"}}')
elif [ "$tag_exists" = "false" ]; then
payload=$(jq -n \
--arg title "${{ env.BINARY_NAME }} ${status_text}" \
--arg commit "$commit_title" \
--arg version "$tag" \
--arg author "${{ github.actor }}" \
--arg url "$workflow_url" \
'{msg_type: "text", content: {text: "\($title)\n🆕 新版本已发布 (linux / macOS / windows)\n提交\($commit)\n版本\($version)\n作者\($author)\n详情\($url)"}}')
if [ "$tag_exists" = "false" ]; then
version_line="🆕 新版本 ${tag}"
else
payload=$(jq -n \
--arg title "${{ env.BINARY_NAME }} ${status_text}" \
--arg commit "$commit_title" \
--arg version "$tag" \
--arg author "${{ github.actor }}" \
--arg url "$workflow_url" \
'{msg_type: "text", content: {text: "\($title)\n🔄 重复构建\n提交\($commit)\n版本\($version)\n作者\($author)\n详情\($url)"}}')
version_line="🔄 重复构建 ${tag}"
fi
msg="secrets ${status}
${version_line}
linux $(icon "$linux_r") | Release $(icon "$publish_r")
提交:${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"

2
.gitignore vendored
View File

@@ -1,2 +1,4 @@
/target
.env
.DS_Store
.cursor/

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

292
AGENTS.md
View File

@@ -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.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
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 # 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 等)
```
## 数据库
- **Host**: `47.117.131.22:5432`(阿里云上海 ECSPostgreSQL 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,33 +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 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 \
@@ -93,17 +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 — 增量更新(记录必须已存在)
只有传入的字段才会变动,其余全部保留。
```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
# 轮换 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>
# 移除废弃字段
secrets update -n refining --kind service --name mqtt \
--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
```
## 代码规范
@@ -112,7 +286,42 @@ secrets search --tag hongkong
- 异步:全程 `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`
## 提交前检查(必须全部通过)
每次提交代码前,请在本地依次执行以下检查,**全部通过后再 push**
### 1. 版本号(按需)
若本次改动需要发版,请先确认 `Cargo.toml` 中的 `version` 已提升,避免 CI 打出的 Tag 与已有版本重复。可通过 git tag 判断:
```bash
# 查看当前 Cargo.toml 版本
grep '^version' Cargo.toml
# 查看是否已存在该版本对应的 tagCI 使用格式 secrets-<version>
git tag -l 'secrets-*'
```
若当前版本已被 tag例如已有 `secrets-0.3.0``Cargo.toml` 仍为 `0.3.0`),则应在 `Cargo.toml` 中 bump 版本号后再提交,以便 CI 自动打新 Tag 并发布 Release。
### 2. 格式、Lint、测试
```bash
cargo fmt -- --check # 格式检查(不通过则运行 cargo fmt 修复)
cargo clippy -- -D warnings # Lint 检查(消除所有 warning
cargo test # 单元/集成测试
```
或一次性执行:
```bash
cargo fmt -- --check && cargo clippy -- -D warnings && cargo test
```
## CI/CD
@@ -127,4 +336,7 @@ secrets search --tag hongkong
| 变量 | 说明 |
|------|------|
| `DATABASE_URL` | PostgreSQL 连接串,优先级高于 `--db-url` 参数 |
| `RUST_LOG` | 日志级别,如 `secrets=debug``secrets=trace`(默认 warn |
| `USER` | 审计日志 actor 字段来源Shell 自动设置,通常无需手动配置 |
数据库连接通过 `secrets config set-db` 持久化到 `~/.config/secrets/config.toml`,不支持环境变量。

657
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,16 +1,23 @@
[package]
name = "secrets"
version = "0.1.0"
version = "0.5.0"
edition = "2024"
[dependencies]
aes-gcm = "0.10.3"
anyhow = "1.0.102"
argon2 = { version = "0.5.3", features = ["std"] }
chrono = { version = "0.4.44", features = ["serde"] }
clap = { version = "4.6.0", features = ["derive", "env"] }
dotenvy = "0.15.7"
dirs = "6.0.0"
keyring = { version = "3.6.3", features = ["apple-native"] }
rand = "0.10.0"
rpassword = "7.4.0"
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.149"
sqlx = { version = "0.8.6", features = ["runtime-tokio", "tls-native-tls", "postgres", "uuid", "json", "chrono"] }
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"] }

150
README.md
View File

@@ -11,55 +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
# 获取完整记录含 secretsJSON 格式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
# ── 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>
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` 表,记录所有写操作
| 字段 | 说明 |
|------|------|
@@ -72,17 +141,34 @@ 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-migratesecrets + 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/
seed-data.sh # 导入 refining / ricnsmart 全量数据
```

View File

@@ -109,11 +109,10 @@ echo ""
# 1. 创建 Secret: RELEASE_TOKEN
echo "1. 创建 Secret: RELEASE_TOKEN"
encoded=$(echo -n "$GITEA_TOKEN" | base64)
resp=$(curl -s -w "\n%{http_code}" -X PUT \
-H "Authorization: token $GITEA_TOKEN" \
-H "Content-Type: application/json" \
-d "{\"data\":\"${encoded}\"}" \
-d "{\"data\":\"${GITEA_TOKEN}\"}" \
"${API_BASE}/repos/${OWNER}/${REPO}/actions/secrets/RELEASE_TOKEN")
http_code=$(echo "$resp" | tail -n1)
body=$(echo "$resp" | sed '$d')

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,10 +1,13 @@
use anyhow::Result;
use serde_json::{Map, Value};
use serde_json::{Map, Value, json};
use sqlx::PgPool;
use std::fs;
use crate::crypto;
use crate::output::OutputMode;
/// Parse "key=value" entries. Value starting with '@' reads from file.
fn parse_kv(entry: &str) -> Result<(String, String)> {
pub(crate) fn parse_kv(entry: &str) -> Result<(String, String)> {
let (key, raw_val) = entry.split_once('=').ok_or_else(|| {
anyhow::anyhow!(
"Invalid format '{}'. Expected: key=value or key=@file",
@@ -22,7 +25,7 @@ fn parse_kv(entry: &str) -> Result<(String, String)> {
Ok((key.to_string(), value))
}
fn build_json(entries: &[String]) -> Result<Value> {
pub(crate) fn build_json(entries: &[String]) -> Result<Value> {
let mut map = Map::new();
for entry in entries {
let (key, value) = parse_kv(entry)?;
@@ -31,17 +34,24 @@ 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<'_>, master_key: &[u8; 32]) -> Result<()> {
let metadata = build_json(args.meta_entries)?;
let secret_json = build_json(args.secret_entries)?;
// Encrypt the secret JSON before storing
let encrypted_bytes = crypto::encrypt_json(master_key, &secret_json)?;
tracing::debug!(args.namespace, args.kind, args.name, "upserting record");
sqlx::query(
r#"
@@ -55,32 +65,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)
.bind(&encrypted_bytes)
.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
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,19 +1,23 @@
use anyhow::Result;
use serde_json::json;
use sqlx::PgPool;
pub async fn run(pool: &PgPool, namespace: &str, kind: &str, name: &str) -> Result<()> {
let result = sqlx::query(
"DELETE FROM secrets WHERE namespace = $1 AND kind = $2 AND name = $3",
)
.bind(namespace)
.bind(kind)
.bind(name)
.execute(pool)
.await?;
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)
.bind(kind)
.bind(name)
.execute(pool)
.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(())

62
src/commands/init.rs Normal file
View File

@@ -0,0 +1,62 @@
use anyhow::{Context, Result};
use rand::RngExt;
use sqlx::PgPool;
use crate::{crypto, db};
pub async fn run(pool: &PgPool) -> Result<()> {
println!("Initializing secrets master key...");
println!();
// Read password (no echo)
let password =
rpassword::prompt_password("Enter master password: ").context("failed to read password")?;
if password.is_empty() {
anyhow::bail!("Master password must not be empty.");
}
let confirm = rpassword::prompt_password("Confirm master password: ")
.context("failed to read password confirmation")?;
if password != confirm {
anyhow::bail!("Passwords do not match.");
}
// Get or create Argon2id salt
let salt = match db::load_argon2_salt(pool).await? {
Some(existing) => {
println!("Found existing salt in database (not the first device).");
existing
}
None => {
println!("Generating new Argon2id salt and storing in database...");
let mut salt = vec![0u8; 16];
rand::rng().fill(&mut salt[..]);
db::store_argon2_salt(pool, &salt).await?;
salt
}
};
// Derive master key
print!("Deriving master key (Argon2id, this takes a moment)... ");
let master_key = crypto::derive_master_key(&password, &salt)?;
println!("done.");
// Store in OS Keychain
crypto::store_master_key(&master_key)?;
// Self-test: encrypt and decrypt a canary value
let canary = b"secrets-cli-canary";
let enc = crypto::encrypt(&master_key, canary)?;
let dec = crypto::decrypt(&master_key, &enc)?;
if dec != canary {
anyhow::bail!("Self-test failed: encryption roundtrip mismatch");
}
println!();
println!("Master key stored in OS Keychain.");
println!("You can now use `secrets add` / `secrets search` commands.");
println!();
println!("IMPORTANT: Remember your master password — it is not stored anywhere.");
println!(" On a new device, run `secrets init` with the same password.");
Ok(())
}

View File

@@ -0,0 +1,85 @@
use anyhow::Result;
use sqlx::PgPool;
use uuid::Uuid;
use crate::crypto;
/// Row fetched for migration
#[derive(sqlx::FromRow)]
struct MigrateRow {
id: Uuid,
namespace: String,
kind: String,
name: String,
encrypted: Vec<u8>,
}
/// Encrypt any records whose `encrypted` column contains raw (unencrypted) bytes.
///
/// After the schema migration, old JSONB rows were stored as raw UTF-8 bytes.
/// A valid AES-256-GCM blob is always at least 28 bytes (12 nonce + 16 tag).
/// We attempt to decrypt each row; if decryption fails, we assume it's plaintext
/// JSON and re-encrypt it.
pub async fn run(pool: &PgPool, master_key: &[u8; 32]) -> Result<()> {
println!("Scanning for unencrypted secret rows...");
let rows: Vec<MigrateRow> =
sqlx::query_as("SELECT id, namespace, kind, name, encrypted FROM secrets")
.fetch_all(pool)
.await?;
let total = rows.len();
let mut migrated = 0usize;
let mut already_encrypted = 0usize;
let mut skipped_empty = 0usize;
for row in rows {
if row.encrypted.is_empty() {
skipped_empty += 1;
continue;
}
// Try to decrypt; success → already encrypted, skip
if crypto::decrypt_json(master_key, &row.encrypted).is_ok() {
already_encrypted += 1;
continue;
}
// Treat as plaintext JSON bytes (from schema migration copy)
let json_str = String::from_utf8(row.encrypted.clone()).map_err(|_| {
anyhow::anyhow!(
"Row [{}/{}/{}]: encrypted column contains non-UTF-8 bytes that are also not valid ciphertext. Manual inspection required.",
row.namespace, row.kind, row.name
)
})?;
let value: serde_json::Value = serde_json::from_str(&json_str).map_err(|e| {
anyhow::anyhow!(
"Row [{}/{}/{}]: failed to parse as JSON: {}",
row.namespace,
row.kind,
row.name,
e
)
})?;
let encrypted_bytes = crypto::encrypt_json(master_key, &value)?;
sqlx::query("UPDATE secrets SET encrypted = $1, updated_at = NOW() WHERE id = $2")
.bind(&encrypted_bytes)
.bind(row.id)
.execute(pool)
.await?;
println!(" Encrypted: [{}/{}] {}", row.namespace, row.kind, row.name);
migrated += 1;
}
println!();
println!(
"Done. Total: {total}, encrypted this run: {migrated}, \
already encrypted: {already_encrypted}, empty (skipped): {skipped_empty}"
);
Ok(())
}

View File

@@ -1,3 +1,7 @@
pub mod add;
pub mod config;
pub mod delete;
pub mod init;
pub mod migrate_encrypt;
pub mod search;
pub mod update;

View File

@@ -1,36 +1,52 @@
use anyhow::Result;
use serde_json::{Value, json};
use sqlx::PgPool;
use crate::crypto;
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<'_>, master_key: Option<&[u8; 32]>) -> 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,66 +55,290 @@ 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, master_key);
}
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, master_key))
.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, master_key)?;
} 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, master_key)?;
}
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(())
}
/// Decrypt the encrypted blob for a row. Returns an empty object on empty blobs.
/// Returns an error value on decrypt failure (so callers can decide how to handle).
fn try_decrypt(row: &Secret, master_key: Option<&[u8; 32]>) -> Result<Value> {
if row.encrypted.is_empty() {
return Ok(Value::Object(Default::default()));
}
let key = master_key.ok_or_else(|| {
anyhow::anyhow!("master key required to decrypt secrets (run `secrets init`)")
})?;
crypto::decrypt_json(key, &row.encrypted)
}
fn to_json(
row: &Secret,
show_secrets: bool,
summary: bool,
master_key: Option<&[u8; 32]>,
) -> 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 {
match try_decrypt(row, master_key) {
Ok(v) => v,
Err(e) => json!({"_error": e.to_string()}),
}
} else {
json!({"_encrypted": true, "_key_count": encrypted_key_count(row, master_key)})
};
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(),
})
}
/// Return the number of keys in the encrypted JSON (decrypts to count; 0 on failure).
fn encrypted_key_count(row: &Secret, master_key: Option<&[u8; 32]>) -> usize {
if row.encrypted.is_empty() {
return 0;
}
let Some(key) = master_key else { return 0 };
match crypto::decrypt_json(key, &row.encrypted) {
Ok(Value::Object(m)) => m.len(),
_ => 0,
}
}
fn print_text(
row: &Secret,
show_secrets: bool,
summary: bool,
master_key: Option<&[u8; 32]>,
) -> 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(", "));
}
let meta_obj = row.metadata.as_object();
if let Some(m) = meta_obj {
if !m.is_empty() {
println!(" metadata: {}", serde_json::to_string_pretty(&row.metadata)?);
if row.metadata.as_object().is_some_and(|m| !m.is_empty()) {
println!(
" metadata: {}",
serde_json::to_string_pretty(&row.metadata)?
);
}
if !row.encrypted.is_empty() {
if show_secrets {
match try_decrypt(row, master_key) {
Ok(v) => println!(" secrets: {}", serde_json::to_string_pretty(&v)?),
Err(e) => println!(" secrets: [decrypt error: {}]", e),
}
} else {
println!(" secrets: [encrypted] (--show-secrets to reveal)");
}
}
if show_secrets {
println!(" secrets: {}", serde_json::to_string_pretty(&row.encrypted)?);
} else {
let keys: Vec<String> = row
.encrypted
.as_object()
.map(|m| m.keys().cloned().collect())
.unwrap_or_default();
if !keys.is_empty() {
println!(" secrets: [{}] (--show-secrets to reveal)", keys.join(", "));
}
}
println!(" created: {}", row.created_at.format("%Y-%m-%d %H:%M:%S UTC"));
println!();
println!(
" created: {}",
row.created_at.format("%Y-%m-%d %H:%M:%S UTC")
);
}
println!("{} record(s) found.", rows.len());
println!();
Ok(())
}
fn print_env(row: &Secret, show_secrets: bool, master_key: Option<&[u8; 32]>) -> 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 decrypted = try_decrypt(row, master_key)?;
if let Some(enc) = decrypted.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], master_key: Option<&[u8; 32]>) -> Result<()> {
for row in rows {
// Decrypt once per row if any field requires it
let decrypted: Option<Value> = if fields
.iter()
.any(|f| f.starts_with("secret") || f.starts_with("encrypted"))
{
Some(try_decrypt(row, master_key)?)
} else {
None
};
for field in fields {
let val = extract_field(row, field, decrypted.as_ref())?;
println!("{}", val);
}
}
Ok(())
}
fn extract_field(row: &Secret, field: &str, decrypted: Option<&Value>) -> 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" => {
decrypted.ok_or_else(|| anyhow::anyhow!("secret field requires master key"))?
}
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
)
})
}

176
src/commands/update.rs Normal file
View File

@@ -0,0 +1,176 @@
use anyhow::Result;
use serde_json::{Map, Value, json};
use sqlx::{FromRow, PgPool};
use uuid::Uuid;
use super::add::parse_kv;
use crate::crypto;
#[derive(FromRow)]
struct UpdateRow {
id: Uuid,
tags: Vec<String>,
metadata: Value,
encrypted: Vec<u8>,
}
pub struct UpdateArgs<'a> {
pub namespace: &'a str,
pub kind: &'a str,
pub name: &'a str,
pub add_tags: &'a [String],
pub remove_tags: &'a [String],
pub meta_entries: &'a [String],
pub remove_meta: &'a [String],
pub secret_entries: &'a [String],
pub remove_secrets: &'a [String],
}
pub async fn run(pool: &PgPool, args: UpdateArgs<'_>, master_key: &[u8; 32]) -> Result<()> {
let row: Option<UpdateRow> = sqlx::query_as(
r#"
SELECT id, tags, metadata, encrypted
FROM secrets
WHERE namespace = $1 AND kind = $2 AND name = $3
"#,
)
.bind(args.namespace)
.bind(args.kind)
.bind(args.name)
.fetch_optional(pool)
.await?;
let row = row.ok_or_else(|| {
anyhow::anyhow!(
"Not found: [{}/{}] {}. Use `add` to create it first.",
args.namespace,
args.kind,
args.name
)
})?;
// Merge tags
let mut tags: Vec<String> = row.tags;
for t in args.add_tags {
if !tags.contains(t) {
tags.push(t.clone());
}
}
tags.retain(|t| !args.remove_tags.contains(t));
// Merge metadata
let mut meta_map: Map<String, Value> = match row.metadata {
Value::Object(m) => m,
_ => Map::new(),
};
for entry in args.meta_entries {
let (key, value) = parse_kv(entry)?;
meta_map.insert(key, Value::String(value));
}
for key in args.remove_meta {
meta_map.remove(key);
}
let metadata = Value::Object(meta_map);
// Decrypt existing encrypted blob, merge changes, re-encrypt
let existing_json = if row.encrypted.is_empty() {
Value::Object(Map::new())
} else {
crypto::decrypt_json(master_key, &row.encrypted)?
};
let mut enc_map: Map<String, Value> = match existing_json {
Value::Object(m) => m,
_ => Map::new(),
};
for entry in args.secret_entries {
let (key, value) = parse_kv(entry)?;
enc_map.insert(key, Value::String(value));
}
for key in args.remove_secrets {
enc_map.remove(key);
}
let secret_json = Value::Object(enc_map);
let encrypted_bytes = crypto::encrypt_json(master_key, &secret_json)?;
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
"#,
)
.bind(&tags)
.bind(metadata)
.bind(encrypted_bytes)
.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() {
println!(" +tags: {}", args.add_tags.join(", "));
}
if !args.remove_tags.is_empty() {
println!(" -tags: {}", args.remove_tags.join(", "));
}
if !args.meta_entries.is_empty() {
let keys: Vec<&str> = args
.meta_entries
.iter()
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
.collect();
println!(" +metadata: {}", keys.join(", "));
}
if !args.remove_meta.is_empty() {
println!(" -metadata: {}", args.remove_meta.join(", "));
}
if !args.secret_entries.is_empty() {
let keys: Vec<&str> = args
.secret_entries
.iter()
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
.collect();
println!(" +secrets: {}", keys.join(", "));
}
if !args.remove_secrets.is_empty() {
println!(" -secrets: {}", args.remove_secrets.join(", "));
}
Ok(())
}

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

192
src/crypto.rs Normal file
View File

@@ -0,0 +1,192 @@
use aes_gcm::{
Aes256Gcm, Key, Nonce,
aead::{Aead, AeadCore, KeyInit, OsRng},
};
use anyhow::{Context, Result, bail};
use argon2::{Argon2, Params, Version};
use serde_json::Value;
const KEYRING_SERVICE: &str = "secrets-cli";
const KEYRING_USER: &str = "master-key";
const NONCE_LEN: usize = 12;
// ─── Argon2id key derivation ─────────────────────────────────────────────────
/// Derive a 32-byte Master Key from a password and salt using Argon2id.
/// Parameters: m=65536 KiB (64 MB), t=3, p=4 — OWASP recommended.
pub fn derive_master_key(password: &str, salt: &[u8]) -> Result<[u8; 32]> {
let params = Params::new(65536, 3, 4, Some(32)).context("invalid Argon2id params")?;
let argon2 = Argon2::new(argon2::Algorithm::Argon2id, Version::V0x13, params);
let mut key = [0u8; 32];
argon2
.hash_password_into(password.as_bytes(), salt, &mut key)
.map_err(|e| anyhow::anyhow!("Argon2id derivation failed: {}", e))?;
Ok(key)
}
// ─── AES-256-GCM encrypt / decrypt ───────────────────────────────────────────
/// Encrypt plaintext bytes with AES-256-GCM.
/// Returns `nonce (12 B) || ciphertext+tag`.
pub fn encrypt(master_key: &[u8; 32], plaintext: &[u8]) -> Result<Vec<u8>> {
let key = Key::<Aes256Gcm>::from_slice(master_key);
let cipher = Aes256Gcm::new(key);
let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
let ciphertext = cipher
.encrypt(&nonce, plaintext)
.map_err(|e| anyhow::anyhow!("AES-256-GCM encryption failed: {}", e))?;
let mut out = Vec::with_capacity(NONCE_LEN + ciphertext.len());
out.extend_from_slice(&nonce);
out.extend_from_slice(&ciphertext);
Ok(out)
}
/// Decrypt `nonce (12 B) || ciphertext+tag` with AES-256-GCM.
pub fn decrypt(master_key: &[u8; 32], data: &[u8]) -> Result<Vec<u8>> {
if data.len() < NONCE_LEN {
bail!(
"encrypted data too short ({}B); possibly corrupted",
data.len()
);
}
let (nonce_bytes, ciphertext) = data.split_at(NONCE_LEN);
let key = Key::<Aes256Gcm>::from_slice(master_key);
let cipher = Aes256Gcm::new(key);
let nonce = Nonce::from_slice(nonce_bytes);
cipher
.decrypt(nonce, ciphertext)
.map_err(|_| anyhow::anyhow!("decryption failed — wrong master key or corrupted data"))
}
// ─── JSON helpers ─────────────────────────────────────────────────────────────
/// Serialize a JSON Value and encrypt it. Returns the encrypted blob.
pub fn encrypt_json(master_key: &[u8; 32], value: &Value) -> Result<Vec<u8>> {
let bytes = serde_json::to_vec(value).context("serialize JSON for encryption")?;
encrypt(master_key, &bytes)
}
/// Decrypt an encrypted blob and deserialize it as a JSON Value.
pub fn decrypt_json(master_key: &[u8; 32], data: &[u8]) -> Result<Value> {
let bytes = decrypt(master_key, data)?;
serde_json::from_slice(&bytes).context("deserialize decrypted JSON")
}
// ─── OS Keychain ──────────────────────────────────────────────────────────────
/// Load the Master Key from the OS Keychain.
/// Returns an error with a helpful message if it hasn't been initialized.
pub fn load_master_key() -> Result<[u8; 32]> {
let entry =
keyring::Entry::new(KEYRING_SERVICE, KEYRING_USER).context("create keychain entry")?;
let hex = entry.get_password().map_err(|_| {
anyhow::anyhow!("Master key not found in keychain. Run `secrets init` first.")
})?;
let bytes = hex::decode_hex(&hex)?;
if bytes.len() != 32 {
bail!(
"stored master key has unexpected length {}; re-run `secrets init`",
bytes.len()
);
}
let mut key = [0u8; 32];
key.copy_from_slice(&bytes);
Ok(key)
}
/// Store the Master Key in the OS Keychain (overwrites any existing value).
pub fn store_master_key(key: &[u8; 32]) -> Result<()> {
let entry =
keyring::Entry::new(KEYRING_SERVICE, KEYRING_USER).context("create keychain entry")?;
let hex = hex::encode_hex(key);
entry
.set_password(&hex)
.map_err(|e| anyhow::anyhow!("keychain write failed: {}", e))?;
Ok(())
}
/// Delete the Master Key from the OS Keychain (used by tests / reset).
#[cfg(test)]
pub fn delete_master_key() -> Result<()> {
let entry =
keyring::Entry::new(KEYRING_SERVICE, KEYRING_USER).context("create keychain entry")?;
let _ = entry.delete_credential();
Ok(())
}
// ─── Minimal hex helpers (avoid extra dep) ────────────────────────────────────
mod hex {
use anyhow::{Result, bail};
pub fn encode_hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{:02x}", b)).collect()
}
pub fn decode_hex(s: &str) -> Result<Vec<u8>> {
if !s.len().is_multiple_of(2) {
bail!("hex string has odd length");
}
(0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).map_err(|e| anyhow::anyhow!("{}", e)))
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn roundtrip_encrypt_decrypt() {
let key = [0x42u8; 32];
let plaintext = b"hello world";
let enc = encrypt(&key, plaintext).unwrap();
let dec = decrypt(&key, &enc).unwrap();
assert_eq!(dec, plaintext);
}
#[test]
fn encrypt_produces_different_ciphertexts() {
let key = [0x42u8; 32];
let plaintext = b"hello world";
let enc1 = encrypt(&key, plaintext).unwrap();
let enc2 = encrypt(&key, plaintext).unwrap();
// Different nonces → different ciphertexts
assert_ne!(enc1, enc2);
}
#[test]
fn wrong_key_fails_decryption() {
let key1 = [0x42u8; 32];
let key2 = [0x43u8; 32];
let enc = encrypt(&key1, b"secret").unwrap();
assert!(decrypt(&key2, &enc).is_err());
}
#[test]
fn json_roundtrip() {
let key = [0x42u8; 32];
let value = serde_json::json!({"token": "abc123", "password": "hunter2"});
let enc = encrypt_json(&key, &value).unwrap();
let dec = decrypt_json(&key, &enc).unwrap();
assert_eq!(dec, value);
}
#[test]
fn derive_master_key_deterministic() {
let salt = b"fixed_test_salt_";
let k1 = derive_master_key("password", salt).unwrap();
let k2 = derive_master_key("password", salt).unwrap();
assert_eq!(k1, k2);
}
#[test]
fn derive_master_key_different_passwords() {
let salt = b"fixed_test_salt_";
let k1 = derive_master_key("password1", salt).unwrap();
let k2 = derive_master_key("password2", salt).unwrap();
assert_ne!(k1, k2);
}
}

View File

@@ -1,16 +1,19 @@
use anyhow::Result;
use sqlx::postgres::PgPoolOptions;
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 (
@@ -20,7 +23,7 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
name VARCHAR(256) NOT NULL,
tags TEXT[] NOT NULL DEFAULT '{}',
metadata JSONB NOT NULL DEFAULT '{}',
encrypted JSONB NOT NULL DEFAULT '{}',
encrypted BYTEA NOT NULL DEFAULT '\x',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE(namespace, kind, name)
@@ -32,13 +35,76 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
EXCEPTION WHEN OTHERS THEN NULL;
END $$;
-- Migrate encrypted column from JSONB to BYTEA if still JSONB type.
-- After migration, old plaintext rows will have their JSONB data
-- stored as raw bytes (not yet re-encrypted); run `secrets migrate-encrypt`
-- to encrypt them with the master key.
DO $$ BEGIN
IF EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = 'secrets'
AND column_name = 'encrypted'
AND data_type = 'jsonb'
) THEN
ALTER TABLE secrets RENAME COLUMN encrypted TO encrypted_jsonb_old;
ALTER TABLE secrets ADD COLUMN encrypted BYTEA NOT NULL DEFAULT '\x';
-- Copy existing JSONB data as raw UTF-8 bytes so nothing is lost
UPDATE secrets SET encrypted = convert_to(encrypted_jsonb_old::text, 'UTF8');
ALTER TABLE secrets DROP COLUMN encrypted_jsonb_old;
END IF;
EXCEPTION WHEN OTHERS THEN NULL;
END $$;
CREATE INDEX IF NOT EXISTS idx_secrets_namespace ON secrets(namespace);
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);
-- Key-value config table: stores Argon2id salt (shared across devices)
CREATE TABLE IF NOT EXISTS kv_config (
key TEXT PRIMARY KEY,
value BYTEA NOT NULL
);
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(())
}
/// Load the Argon2id salt from the database.
/// Returns None if not yet initialized.
pub async fn load_argon2_salt(pool: &PgPool) -> Result<Option<Vec<u8>>> {
let row: Option<(Vec<u8>,)> =
sqlx::query_as("SELECT value FROM kv_config WHERE key = 'argon2_salt'")
.fetch_optional(pool)
.await?;
Ok(row.map(|(v,)| v))
}
/// Store the Argon2id salt in the database (only called once on first device init).
pub async fn store_argon2_salt(pool: &PgPool, salt: &[u8]) -> Result<()> {
sqlx::query(
"INSERT INTO kv_config (key, value) VALUES ('argon2_salt', $1) \
ON CONFLICT (key) DO NOTHING",
)
.bind(salt)
.execute(pool)
.await?;
Ok(())
}

View File

@@ -1,97 +1,339 @@
mod audit;
mod commands;
mod config;
mod crypto;
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")]
#[command(
name = "secrets",
version,
about = "Secrets & config manager backed by PostgreSQL — optimised for AI agents",
after_help = "QUICK START:
# First time setup (run once per device)
secrets init
# 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)
/// Initialize master key on this device (run once per device).
///
/// Prompts for a master password, derives a key with Argon2id, and stores
/// it in the OS Keychain. Use the same password on every device.
#[command(after_help = "EXAMPLES:
# First device: generates a new Argon2id salt and stores master key
secrets init
# Subsequent devices: reuses existing salt from the database
secrets init")]
Init,
/// Encrypt any pre-existing plaintext records in the database.
///
/// Run this once after upgrading from a version that stored secrets as
/// plaintext JSONB. Requires `secrets init` to have been run first.
MigrateEncrypt,
/// 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; 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
#[arg(short, long)]
namespace: String,
/// Kind of record: server, service, key, ...
#[arg(long)]
kind: String,
/// Human-readable unique name
#[arg(long)]
name: String,
/// Add a tag (repeatable; does not affect existing tags)
#[arg(long = "add-tag")]
add_tags: Vec<String>,
/// Remove a tag (repeatable)
#[arg(long = "remove-tag")]
remove_tags: Vec<String>,
/// Set or overwrite a metadata field: key=value (repeatable, @file supported)
#[arg(long = "meta", short = 'm')]
meta: Vec<String>,
/// 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>,
/// 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 subcommand needs no database or master key
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?;
// init needs a pool but sets up the master key — handle before loading it
if let Commands::Init = &cli.command {
return commands::init::run(&pool).await;
}
// All remaining commands require the master key from the OS Keychain
let master_key = crypto::load_master_key()?;
match &cli.command {
Commands::Init | Commands::Config { .. } => unreachable!(),
Commands::MigrateEncrypt => {
commands::migrate_encrypt::run(&pool, &master_key).await?;
}
Commands::Add {
namespace,
kind,
@@ -99,33 +341,105 @@ async fn main() -> Result<()> {
tags,
meta,
secrets,
output,
} => {
commands::add::run(&pool, namespace, kind, name, tags, meta, secrets).await?;
}
Commands::Search {
namespace,
kind,
tag,
query,
show_secrets,
} => {
commands::search::run(
let _span =
tracing::info_span!("cmd", command = "add", %namespace, %kind, %name).entered();
let out = resolve_output_mode(output.as_deref())?;
commands::add::run(
&pool,
namespace.as_deref(),
kind.as_deref(),
tag.as_deref(),
query.as_deref(),
*show_secrets,
commands::add::AddArgs {
namespace,
kind,
name,
tags,
meta_entries: meta,
secret_entries: secrets,
output: out,
},
&master_key,
)
.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();
let show = *show_secrets || fields.iter().any(|f| f.starts_with("secret"));
let out = resolve_output_mode(output.as_deref())?;
commands::search::run(
&pool,
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,
},
Some(&master_key),
)
.await?;
}
Commands::Delete {
namespace,
kind,
name,
} => {
let _span =
tracing::info_span!("cmd", command = "delete", %namespace, %kind, %name).entered();
commands::delete::run(&pool, namespace, kind, name).await?;
}
Commands::Update {
namespace,
kind,
name,
add_tags,
remove_tags,
meta,
remove_meta,
secrets,
remove_secrets,
} => {
let _span =
tracing::info_span!("cmd", command = "update", %namespace, %kind, %name).entered();
commands::update::run(
&pool,
commands::update::UpdateArgs {
namespace,
kind,
name,
add_tags,
remove_tags,
meta_entries: meta,
remove_meta,
secret_entries: secrets,
remove_secrets,
},
&master_key,
)
.await?;
}
}
Ok(())

View File

@@ -11,7 +11,9 @@ pub struct Secret {
pub name: String,
pub tags: Vec<String>,
pub metadata: Value,
pub encrypted: Value,
/// AES-256-GCM ciphertext: nonce(12B) || ciphertext+tag
/// Decrypt with crypto::decrypt_json() before use.
pub encrypted: Vec<u8>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}

47
src/output.rs Normal file
View 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)
}
}