Compare commits
14 Commits
secrets-0.
...
secrets-0.
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5a5867adc1 | ||
|
|
4ddafbe4b6 | ||
|
|
6ea9f0861b | ||
|
|
3973295d6a | ||
|
|
c371da95c3 | ||
|
|
baad623efe | ||
|
|
2da7aab3e5 | ||
|
|
fcac14a8c4 | ||
|
|
ff79a3a9cc | ||
|
|
3c21b3dac1 | ||
|
|
3b36d5a3dd | ||
|
|
a765dcc428 | ||
|
|
31b0ea9bf1 | ||
|
|
dc0534cbc9 |
@@ -7,7 +7,6 @@ on:
|
|||||||
- 'src/**'
|
- 'src/**'
|
||||||
- 'Cargo.toml'
|
- 'Cargo.toml'
|
||||||
- 'Cargo.lock'
|
- 'Cargo.lock'
|
||||||
- '.gitea/workflows/secrets.yml'
|
|
||||||
|
|
||||||
concurrency:
|
concurrency:
|
||||||
group: ${{ github.workflow }}-${{ github.ref }}
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
@@ -56,6 +55,13 @@ jobs:
|
|||||||
echo "将创建新版本 ${tag}"
|
echo "将创建新版本 ${tag}"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
- name: 严格拦截重复版本
|
||||||
|
if: steps.ver.outputs.tag_exists == 'true'
|
||||||
|
run: |
|
||||||
|
echo "错误: 版本 ${{ steps.ver.outputs.tag }} 已存在,禁止重复发版。"
|
||||||
|
echo "请先 bump Cargo.toml 中的 version,并执行 cargo build 同步 Cargo.lock。"
|
||||||
|
exit 1
|
||||||
|
|
||||||
- name: 创建 Tag
|
- name: 创建 Tag
|
||||||
if: steps.ver.outputs.tag_exists == 'false'
|
if: steps.ver.outputs.tag_exists == 'false'
|
||||||
run: |
|
run: |
|
||||||
@@ -204,9 +210,13 @@ jobs:
|
|||||||
bin="target/x86_64-unknown-linux-musl/release/${{ env.BINARY_NAME }}"
|
bin="target/x86_64-unknown-linux-musl/release/${{ env.BINARY_NAME }}"
|
||||||
archive="${{ env.BINARY_NAME }}-${tag}-x86_64-linux-musl.tar.gz"
|
archive="${{ env.BINARY_NAME }}-${tag}-x86_64-linux-musl.tar.gz"
|
||||||
tar -czf "$archive" -C "$(dirname "$bin")" "$(basename "$bin")"
|
tar -czf "$archive" -C "$(dirname "$bin")" "$(basename "$bin")"
|
||||||
|
sha256sum "$archive" > "${archive}.sha256"
|
||||||
curl -fsS -H "Authorization: token $RELEASE_TOKEN" \
|
curl -fsS -H "Authorization: token $RELEASE_TOKEN" \
|
||||||
-F "attachment=@${archive}" \
|
-F "attachment=@${archive}" \
|
||||||
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${{ needs.version.outputs.release_id }}/assets"
|
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${{ needs.version.outputs.release_id }}/assets"
|
||||||
|
curl -fsS -H "Authorization: token $RELEASE_TOKEN" \
|
||||||
|
-F "attachment=@${archive}.sha256" \
|
||||||
|
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${{ needs.version.outputs.release_id }}/assets"
|
||||||
|
|
||||||
- name: 飞书通知
|
- name: 飞书通知
|
||||||
if: always()
|
if: always()
|
||||||
@@ -229,7 +239,7 @@ jobs:
|
|||||||
curl -sS -H "Content-Type: application/json" -X POST -d "$payload" "$WEBHOOK_URL"
|
curl -sS -H "Content-Type: application/json" -X POST -d "$payload" "$WEBHOOK_URL"
|
||||||
|
|
||||||
build-macos:
|
build-macos:
|
||||||
name: Build (aarch64-apple-darwin)
|
name: Build (macOS aarch64 + x86_64)
|
||||||
needs: [version, check]
|
needs: [version, check]
|
||||||
runs-on: darwin-arm64
|
runs-on: darwin-arm64
|
||||||
timeout-minutes: 15
|
timeout-minutes: 15
|
||||||
@@ -241,6 +251,7 @@ jobs:
|
|||||||
fi
|
fi
|
||||||
source "$HOME/.cargo/env" 2>/dev/null || true
|
source "$HOME/.cargo/env" 2>/dev/null || true
|
||||||
rustup target add aarch64-apple-darwin
|
rustup target add aarch64-apple-darwin
|
||||||
|
rustup target add x86_64-apple-darwin
|
||||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||||
|
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
@@ -253,12 +264,14 @@ jobs:
|
|||||||
~/.cargo/registry/cache
|
~/.cargo/registry/cache
|
||||||
~/.cargo/git/db
|
~/.cargo/git/db
|
||||||
target
|
target
|
||||||
key: cargo-aarch64-apple-darwin-${{ hashFiles('Cargo.lock') }}
|
key: cargo-macos-${{ hashFiles('Cargo.lock') }}
|
||||||
restore-keys: |
|
restore-keys: |
|
||||||
cargo-aarch64-apple-darwin-
|
cargo-macos-
|
||||||
|
|
||||||
- run: cargo build --release --locked --target aarch64-apple-darwin
|
- run: cargo build --release --locked --target aarch64-apple-darwin
|
||||||
|
- run: cargo build --release --locked --target x86_64-apple-darwin
|
||||||
- run: strip -x target/aarch64-apple-darwin/release/${{ env.BINARY_NAME }}
|
- run: strip -x target/aarch64-apple-darwin/release/${{ env.BINARY_NAME }}
|
||||||
|
- run: strip -x target/x86_64-apple-darwin/release/${{ env.BINARY_NAME }}
|
||||||
|
|
||||||
- name: 上传 Release 产物
|
- name: 上传 Release 产物
|
||||||
if: needs.version.outputs.release_id != ''
|
if: needs.version.outputs.release_id != ''
|
||||||
@@ -267,12 +280,29 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
[ -z "$RELEASE_TOKEN" ] && exit 0
|
[ -z "$RELEASE_TOKEN" ] && exit 0
|
||||||
tag="${{ needs.version.outputs.tag }}"
|
tag="${{ needs.version.outputs.tag }}"
|
||||||
bin="target/aarch64-apple-darwin/release/${{ env.BINARY_NAME }}"
|
release_id="${{ needs.version.outputs.release_id }}"
|
||||||
archive="${{ env.BINARY_NAME }}-${tag}-aarch64-macos.tar.gz"
|
|
||||||
tar -czf "$archive" -C "$(dirname "$bin")" "$(basename "$bin")"
|
arm_bin="target/aarch64-apple-darwin/release/${{ env.BINARY_NAME }}"
|
||||||
|
arm_archive="${{ env.BINARY_NAME }}-${tag}-aarch64-macos.tar.gz"
|
||||||
|
tar -czf "$arm_archive" -C "$(dirname "$arm_bin")" "$(basename "$arm_bin")"
|
||||||
|
shasum -a 256 "$arm_archive" > "${arm_archive}.sha256"
|
||||||
curl -fsS -H "Authorization: token $RELEASE_TOKEN" \
|
curl -fsS -H "Authorization: token $RELEASE_TOKEN" \
|
||||||
-F "attachment=@${archive}" \
|
-F "attachment=@${arm_archive}" \
|
||||||
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${{ needs.version.outputs.release_id }}/assets"
|
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${release_id}/assets"
|
||||||
|
curl -fsS -H "Authorization: token $RELEASE_TOKEN" \
|
||||||
|
-F "attachment=@${arm_archive}.sha256" \
|
||||||
|
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${release_id}/assets"
|
||||||
|
|
||||||
|
intel_bin="target/x86_64-apple-darwin/release/${{ env.BINARY_NAME }}"
|
||||||
|
intel_archive="${{ env.BINARY_NAME }}-${tag}-x86_64-macos.tar.gz"
|
||||||
|
tar -czf "$intel_archive" -C "$(dirname "$intel_bin")" "$(basename "$intel_bin")"
|
||||||
|
shasum -a 256 "$intel_archive" > "${intel_archive}.sha256"
|
||||||
|
curl -fsS -H "Authorization: token $RELEASE_TOKEN" \
|
||||||
|
-F "attachment=@${intel_archive}" \
|
||||||
|
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${release_id}/assets"
|
||||||
|
curl -fsS -H "Authorization: token $RELEASE_TOKEN" \
|
||||||
|
-F "attachment=@${intel_archive}.sha256" \
|
||||||
|
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${release_id}/assets"
|
||||||
|
|
||||||
- name: 飞书通知
|
- name: 飞书通知
|
||||||
if: always()
|
if: always()
|
||||||
@@ -285,8 +315,9 @@ jobs:
|
|||||||
url="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}"
|
url="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}"
|
||||||
result="${{ job.status }}"
|
result="${{ job.status }}"
|
||||||
if [ "$result" = "success" ]; then icon="✅"; else icon="❌"; fi
|
if [ "$result" = "success" ]; then icon="✅"; else icon="❌"; fi
|
||||||
msg="secrets macOS 构建${icon}
|
msg="secrets macOS 双架构构建${icon}
|
||||||
版本:${tag}
|
版本:${tag}
|
||||||
|
目标:aarch64-apple-darwin, x86_64-apple-darwin
|
||||||
提交:${commit}
|
提交:${commit}
|
||||||
作者:${{ github.actor }}
|
作者:${{ github.actor }}
|
||||||
详情:${url}"
|
详情:${url}"
|
||||||
@@ -302,11 +333,14 @@ jobs:
|
|||||||
- name: 安装依赖
|
- name: 安装依赖
|
||||||
shell: pwsh
|
shell: pwsh
|
||||||
run: |
|
run: |
|
||||||
|
$cargoBin = Join-Path $env:USERPROFILE ".cargo\bin"
|
||||||
if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) {
|
if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) {
|
||||||
Invoke-WebRequest -Uri "https://win.rustup.rs/x86_64" -OutFile rustup-init.exe
|
Invoke-WebRequest -Uri "https://win.rustup.rs/x86_64" -OutFile rustup-init.exe
|
||||||
.\rustup-init.exe -y --default-toolchain stable
|
.\rustup-init.exe -y --default-toolchain stable
|
||||||
Remove-Item rustup-init.exe
|
Remove-Item rustup-init.exe
|
||||||
}
|
}
|
||||||
|
$env:Path = "$cargoBin;$env:Path"
|
||||||
|
Add-Content -Path $env:GITHUB_PATH -Value $cargoBin
|
||||||
rustup target add x86_64-pc-windows-msvc
|
rustup target add x86_64-pc-windows-msvc
|
||||||
|
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
@@ -338,10 +372,15 @@ jobs:
|
|||||||
$bin = "target\x86_64-pc-windows-msvc\release\${{ env.BINARY_NAME }}.exe"
|
$bin = "target\x86_64-pc-windows-msvc\release\${{ env.BINARY_NAME }}.exe"
|
||||||
$archive = "${{ env.BINARY_NAME }}-${tag}-x86_64-windows.zip"
|
$archive = "${{ env.BINARY_NAME }}-${tag}-x86_64-windows.zip"
|
||||||
Compress-Archive -Path $bin -DestinationPath $archive -Force
|
Compress-Archive -Path $bin -DestinationPath $archive -Force
|
||||||
|
$hash = (Get-FileHash -Algorithm SHA256 $archive).Hash.ToLower()
|
||||||
|
Set-Content -Path "${archive}.sha256" -Value "$hash $archive" -NoNewline
|
||||||
$url = "${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${{ needs.version.outputs.release_id }}/assets"
|
$url = "${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${{ needs.version.outputs.release_id }}/assets"
|
||||||
Invoke-RestMethod -Uri $url -Method Post `
|
Invoke-RestMethod -Uri $url -Method Post `
|
||||||
-Headers @{ "Authorization" = "token $env:RELEASE_TOKEN" } `
|
-Headers @{ "Authorization" = "token $env:RELEASE_TOKEN" } `
|
||||||
-Form @{ attachment = Get-Item $archive }
|
-Form @{ attachment = Get-Item $archive }
|
||||||
|
Invoke-RestMethod -Uri $url -Method Post `
|
||||||
|
-Headers @{ "Authorization" = "token $env:RELEASE_TOKEN" } `
|
||||||
|
-Form @{ attachment = Get-Item "${archive}.sha256" }
|
||||||
|
|
||||||
- name: 飞书通知
|
- name: 飞书通知
|
||||||
if: always()
|
if: always()
|
||||||
@@ -362,7 +401,7 @@ jobs:
|
|||||||
|
|
||||||
publish-release:
|
publish-release:
|
||||||
name: 发布草稿 Release
|
name: 发布草稿 Release
|
||||||
needs: [version, build-linux]
|
needs: [version, build-linux, build-macos, build-windows]
|
||||||
if: always() && needs.version.outputs.release_id != ''
|
if: always() && needs.version.outputs.release_id != ''
|
||||||
runs-on: debian
|
runs-on: debian
|
||||||
timeout-minutes: 5
|
timeout-minutes: 5
|
||||||
@@ -376,8 +415,11 @@ jobs:
|
|||||||
[ -z "$RELEASE_TOKEN" ] && exit 0
|
[ -z "$RELEASE_TOKEN" ] && exit 0
|
||||||
|
|
||||||
linux_r="${{ needs.build-linux.result }}"
|
linux_r="${{ needs.build-linux.result }}"
|
||||||
if [ "$linux_r" != "success" ]; then
|
macos_r="${{ needs.build-macos.result }}"
|
||||||
echo "Linux 构建未成功 (${linux_r}),保留草稿 Release"
|
windows_r="${{ needs.build-windows.result }}"
|
||||||
|
if [ "$linux_r" != "success" ] || [ "$macos_r" != "success" ] || [ "$windows_r" != "success" ]; then
|
||||||
|
echo "存在未成功的构建任务,保留草稿 Release"
|
||||||
|
echo "linux=${linux_r} macos=${macos_r} windows=${windows_r}"
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -408,15 +450,16 @@ jobs:
|
|||||||
commit=$(git log -1 --pretty=format:"%s" 2>/dev/null || echo "N/A")
|
commit=$(git log -1 --pretty=format:"%s" 2>/dev/null || echo "N/A")
|
||||||
url="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}"
|
url="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}"
|
||||||
|
|
||||||
check_r="${{ needs.version.result }}"
|
|
||||||
linux_r="${{ needs.build-linux.result }}"
|
linux_r="${{ needs.build-linux.result }}"
|
||||||
|
macos_r="${{ needs.build-macos.result }}"
|
||||||
|
windows_r="${{ needs.build-windows.result }}"
|
||||||
publish_r="${{ job.status }}"
|
publish_r="${{ job.status }}"
|
||||||
|
|
||||||
icon() { case "$1" in success) echo "✅";; skipped) echo "⏭";; *) echo "❌";; esac; }
|
icon() { case "$1" in success) echo "✅";; skipped) echo "⏭";; *) echo "❌";; esac; }
|
||||||
|
|
||||||
if [ "$linux_r" = "success" ] && [ "$publish_r" = "success" ]; then
|
if [ "$linux_r" = "success" ] && [ "$macos_r" = "success" ] && [ "$windows_r" = "success" ] && [ "$publish_r" = "success" ]; then
|
||||||
status="发布成功 ✅"
|
status="发布成功 ✅"
|
||||||
elif [ "$linux_r" != "success" ]; then
|
elif [ "$linux_r" != "success" ] || [ "$macos_r" != "success" ] || [ "$windows_r" != "success" ]; then
|
||||||
status="构建失败 ❌"
|
status="构建失败 ❌"
|
||||||
else
|
else
|
||||||
status="发布失败 ❌"
|
status="发布失败 ❌"
|
||||||
@@ -430,7 +473,7 @@ jobs:
|
|||||||
|
|
||||||
msg="secrets ${status}
|
msg="secrets ${status}
|
||||||
${version_line}
|
${version_line}
|
||||||
linux $(icon "$linux_r") | Release $(icon "$publish_r")
|
linux $(icon "$linux_r") | macOS $(icon "$macos_r") | windows $(icon "$windows_r") | Release $(icon "$publish_r")
|
||||||
提交:${commit}
|
提交:${commit}
|
||||||
作者:${{ github.actor }}
|
作者:${{ github.actor }}
|
||||||
详情:${url}"
|
详情:${url}"
|
||||||
|
|||||||
8
.vscode/tasks.json
vendored
8
.vscode/tasks.json
vendored
@@ -104,9 +104,9 @@
|
|||||||
"dependsOn": "build"
|
"dependsOn": "build"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"label": "test: search with secrets revealed",
|
"label": "test: inject service secrets",
|
||||||
"type": "shell",
|
"type": "shell",
|
||||||
"command": "./target/debug/secrets search -n refining --kind service --show-secrets",
|
"command": "./target/debug/secrets inject -n refining --kind service --name gitea",
|
||||||
"dependsOn": "build"
|
"dependsOn": "build"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -118,7 +118,7 @@
|
|||||||
{
|
{
|
||||||
"label": "test: add + delete roundtrip",
|
"label": "test: add + delete roundtrip",
|
||||||
"type": "shell",
|
"type": "shell",
|
||||||
"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",
|
"command": "echo '--- add ---' && ./target/debug/secrets add -n test --kind demo --name roundtrip-test --tag test -m foo=bar -s password=secret123 && echo '--- search metadata ---' && ./target/debug/secrets search -n test && echo '--- inject secrets ---' && ./target/debug/secrets inject -n test --kind demo --name roundtrip-test && echo '--- delete ---' && ./target/debug/secrets delete -n test --kind demo --name roundtrip-test && echo '--- verify deleted ---' && ./target/debug/secrets search -n test",
|
||||||
"dependsOn": "build"
|
"dependsOn": "build"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -142,7 +142,7 @@
|
|||||||
{
|
{
|
||||||
"label": "test: add with file secret",
|
"label": "test: add with file secret",
|
||||||
"type": "shell",
|
"type": "shell",
|
||||||
"command": "echo '--- add key from file ---' && ./target/debug/secrets add -n test --kind key --name test-key --tag test -s content=@./refining/keys/Vultr && echo '--- verify ---' && ./target/debug/secrets search -n test --kind key --show-secrets && echo '--- cleanup ---' && ./target/debug/secrets delete -n test --kind key --name test-key",
|
"command": "echo '--- add key from file ---' && ./target/debug/secrets add -n test --kind key --name test-key --tag test -s content=@./refining/keys/Vultr && echo '--- verify metadata ---' && ./target/debug/secrets search -n test --kind key && echo '--- verify inject ---' && ./target/debug/secrets inject -n test --kind key --name test-key && echo '--- cleanup ---' && ./target/debug/secrets delete -n test --kind key --name test-key",
|
||||||
"dependsOn": "build"
|
"dependsOn": "build"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
251
AGENTS.md
251
AGENTS.md
@@ -1,6 +1,13 @@
|
|||||||
# Secrets CLI — AGENTS.md
|
# Secrets CLI — AGENTS.md
|
||||||
|
|
||||||
跨设备密钥与配置管理 CLI 工具,将 refining / ricnsmart 两个项目的服务器信息、服务凭据存储到 PostgreSQL 18,供 AI 工具读取上下文。
|
## 提交 / 发版硬规则(优先于下文其他说明)
|
||||||
|
|
||||||
|
1. 涉及 `src/**`、`Cargo.toml`、`Cargo.lock`、CLI 行为变更的提交,默认视为**需要发版**,除非用户明确说明“本次不发版”。
|
||||||
|
2. 发版前必须先检查 `Cargo.toml` 中的 `version`,再检查是否已存在对应 tag:`git tag -l 'secrets-*'`。
|
||||||
|
3. 若当前版本对应 tag 已存在,必须先 bump `Cargo.toml` 的 `version`,再执行 `cargo build` 同步 `Cargo.lock`,然后才能提交。
|
||||||
|
4. 提交前优先运行 `./scripts/release-check.sh`;该脚本会检查重复版本并执行 `cargo fmt -- --check && cargo clippy --locked -- -D warnings && cargo test --locked`。
|
||||||
|
|
||||||
|
跨设备密钥与配置管理 CLI 工具,将 refining / ricnsmart 两个项目的服务器信息、服务凭据存储到 PostgreSQL 18,供 AI 工具读取上下文。敏感数据(encrypted 字段)使用 AES-256-GCM 加密,主密钥由 Argon2id 从主密码派生并存入平台安全存储(macOS Keychain / Windows Credential Manager / Linux keyutils)。
|
||||||
|
|
||||||
## 项目结构
|
## 项目结构
|
||||||
|
|
||||||
@@ -10,17 +17,23 @@ secrets/
|
|||||||
main.rs # CLI 入口,clap 命令定义,auto-migrate,--verbose 全局参数
|
main.rs # CLI 入口,clap 命令定义,auto-migrate,--verbose 全局参数
|
||||||
output.rs # OutputMode 枚举 + TTY 检测(TTY→text,非 TTY→json-compact)
|
output.rs # OutputMode 枚举 + TTY 检测(TTY→text,非 TTY→json-compact)
|
||||||
config.rs # 配置读写:~/.config/secrets/config.toml(database_url)
|
config.rs # 配置读写:~/.config/secrets/config.toml(database_url)
|
||||||
db.rs # PgPool 创建 + 建表/索引(幂等,含 audit_log)
|
db.rs # PgPool 创建 + 建表/索引(幂等,含 audit_log + kv_config + secrets_history)
|
||||||
models.rs # Secret 结构体(sqlx::FromRow + serde)
|
crypto.rs # AES-256-GCM 加解密、Argon2id 派生、OS 钥匙串
|
||||||
audit.rs # 审计写入:向 audit_log 表记录所有写操作
|
models.rs # Secret 结构体(sqlx::FromRow + serde,含 version 字段)
|
||||||
|
audit.rs # 审计写入:log_tx(事务内)/ log(池,保留备用)
|
||||||
commands/
|
commands/
|
||||||
add.rs # add 命令:upsert,支持 --meta key=value / --secret key=@file / -o json
|
init.rs # init 命令:主密钥初始化(每台设备一次)
|
||||||
|
add.rs # add 命令:upsert,事务化,含历史快照,支持 key:=json 类型化值
|
||||||
config.rs # config 命令:set-db / show / path(持久化 database_url)
|
config.rs # config 命令:set-db / show / path(持久化 database_url)
|
||||||
search.rs # search 命令:多条件查询,-f/-o/--summary/--limit/--offset/--sort
|
search.rs # search 命令:多条件查询,公开 fetch_rows / build_env_map
|
||||||
delete.rs # delete 命令
|
delete.rs # delete 命令:事务化,含历史快照
|
||||||
update.rs # update 命令:增量更新(合并 tags/metadata/encrypted)
|
update.rs # update 命令:增量更新,CAS 并发保护,含历史快照
|
||||||
|
rollback.rs # rollback / history 命令:版本回滚与历史查看
|
||||||
|
run.rs # inject / run 命令:临时环境变量注入
|
||||||
|
upgrade.rs # upgrade 命令:检查、校验摘要并下载最新版本,自动替换二进制
|
||||||
scripts/
|
scripts/
|
||||||
seed-data.sh # 从 refining/ricnsmart config.toml 导入全量数据
|
release-check.sh # 发版前检查版本号/tag 是否重复,并执行 fmt/clippy/test
|
||||||
|
setup-gitea-actions.sh # 配置 Gitea Actions 变量与 Secrets
|
||||||
.gitea/workflows/
|
.gitea/workflows/
|
||||||
secrets.yml # CI:fmt + clippy + musl 构建 + Release 上传 + 飞书通知
|
secrets.yml # CI:fmt + clippy + musl 构建 + Release 上传 + 飞书通知
|
||||||
.vscode/tasks.json # 本地测试任务(build / config / search / add+delete / update / audit 等)
|
.vscode/tasks.json # 本地测试任务(build / config / search / add+delete / update / audit 等)
|
||||||
@@ -31,7 +44,7 @@ secrets/
|
|||||||
- **Host**: `<host>:<port>`
|
- **Host**: `<host>:<port>`
|
||||||
- **Database**: `secrets`
|
- **Database**: `secrets`
|
||||||
- **连接串**: `postgres://postgres:<password>@<host>:<port>/secrets`
|
- **连接串**: `postgres://postgres:<password>@<host>:<port>/secrets`
|
||||||
- **表**: `secrets`(主表)+ `audit_log`(审计表),首次连接自动建表(auto-migrate)
|
- **表**: `secrets`(主表)+ `audit_log`(审计表)+ `kv_config`(Argon2 salt 等),首次连接自动建表(auto-migrate)
|
||||||
|
|
||||||
### 表结构
|
### 表结构
|
||||||
|
|
||||||
@@ -43,13 +56,38 @@ secrets (
|
|||||||
name VARCHAR(256) NOT NULL, -- 人类可读标识
|
name VARCHAR(256) NOT NULL, -- 人类可读标识
|
||||||
tags TEXT[] NOT NULL DEFAULT '{}', -- 灵活标签: ["aliyun","hongkong"]
|
tags TEXT[] NOT NULL DEFAULT '{}', -- 灵活标签: ["aliyun","hongkong"]
|
||||||
metadata JSONB NOT NULL DEFAULT '{}', -- 明文描述: ip, desc, domains, location...
|
metadata JSONB NOT NULL DEFAULT '{}', -- 明文描述: ip, desc, domains, location...
|
||||||
encrypted JSONB NOT NULL DEFAULT '{}', -- 敏感数据: ssh_key, password, token...
|
encrypted BYTEA NOT NULL DEFAULT '\x', -- AES-256-GCM 密文: nonce(12B)||ciphertext+tag
|
||||||
|
version BIGINT NOT NULL DEFAULT 1, -- 乐观锁版本号,每次写操作自增
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
UNIQUE(namespace, kind, name)
|
UNIQUE(namespace, kind, name)
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
```sql
|
||||||
|
secrets_history (
|
||||||
|
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
|
secret_id UUID NOT NULL, -- 对应 secrets.id
|
||||||
|
namespace VARCHAR(64) NOT NULL,
|
||||||
|
kind VARCHAR(64) NOT NULL,
|
||||||
|
name VARCHAR(256) NOT NULL,
|
||||||
|
version BIGINT NOT NULL, -- 被快照时的版本号
|
||||||
|
action VARCHAR(16) NOT NULL, -- 'add' | 'update' | 'delete' | 'rollback'
|
||||||
|
tags TEXT[] NOT NULL DEFAULT '{}',
|
||||||
|
metadata JSONB NOT NULL DEFAULT '{}',
|
||||||
|
encrypted BYTEA NOT NULL DEFAULT '\x', -- 快照时的加密密文
|
||||||
|
actor VARCHAR(128) NOT NULL DEFAULT '',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
```sql
|
||||||
|
kv_config (
|
||||||
|
key TEXT PRIMARY KEY, -- 如 'argon2_salt'
|
||||||
|
value BYTEA NOT NULL -- Argon2id salt,首台设备 init 时生成
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
### audit_log 表结构
|
### audit_log 表结构
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
@@ -74,7 +112,7 @@ audit_log (
|
|||||||
| `name` | 唯一标识名 | `i-uf63f2uookgs5uxmrdyc`, `gitea` |
|
| `name` | 唯一标识名 | `i-uf63f2uookgs5uxmrdyc`, `gitea` |
|
||||||
| `tags` | 多维分类标签 | `["aliyun","hongkong","ricn"]` |
|
| `tags` | 多维分类标签 | `["aliyun","hongkong","ricn"]` |
|
||||||
| `metadata` | 明文非敏感信息 | `{"ip":"47.243.154.187","desc":"Grafana","domains":["..."]}` |
|
| `metadata` | 明文非敏感信息 | `{"ip":"47.243.154.187","desc":"Grafana","domains":["..."]}` |
|
||||||
| `encrypted` | 敏感凭据(MVP 阶段明文存储,后续对 value 加密) | `{"ssh_key":"-----BEGIN...","password":"..."}` |
|
| `encrypted` | 敏感凭据,AES-256-GCM 加密存储 | 二进制密文,解密后为 `{"ssh_key":"...","password":"..."}` |
|
||||||
|
|
||||||
## 数据库配置
|
## 数据库配置
|
||||||
|
|
||||||
@@ -86,8 +124,25 @@ secrets config show # 查看当前配置(密码脱敏)
|
|||||||
secrets config path # 打印配置文件路径
|
secrets config path # 打印配置文件路径
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`set-db` 会先验证连接可用,成功后才写入配置文件;连接失败时提示 "Database connection failed" 且不修改配置。
|
||||||
|
|
||||||
配置文件:`~/.config/secrets/config.toml`,权限 0600。`--db-url` 参数可一次性覆盖。
|
配置文件:`~/.config/secrets/config.toml`,权限 0600。`--db-url` 参数可一次性覆盖。
|
||||||
|
|
||||||
|
## 主密钥与加密
|
||||||
|
|
||||||
|
首次使用(每台设备各执行一次):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
secrets config set-db "postgres://postgres:<password>@<host>:<port>/secrets"
|
||||||
|
secrets init # 提示输入主密码,Argon2id 派生主密钥后存入 OS 钥匙串
|
||||||
|
```
|
||||||
|
|
||||||
|
主密码不存储;salt 存于 `kv_config`,首台设备生成后共享,确保同一主密码在所有设备派生出相同主密钥。
|
||||||
|
|
||||||
|
主密钥存储后端:macOS Keychain、Windows Credential Manager、Linux keyutils(会话级,重启后需再次 `secrets init`)。
|
||||||
|
|
||||||
|
**从旧版(明文 JSONB)升级**:升级后执行 `secrets init` 即可(明文记录需手动重新 add 或通过 update 更新)。
|
||||||
|
|
||||||
## CLI 命令
|
## CLI 命令
|
||||||
|
|
||||||
### AI 使用主路径
|
### AI 使用主路径
|
||||||
@@ -102,6 +157,16 @@ secrets config path # 打印配置文件路径
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
### init — 主密钥初始化(每台设备一次)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 首次设备:生成 Argon2id salt 并存库,派生主密钥后存 OS 钥匙串
|
||||||
|
secrets init
|
||||||
|
|
||||||
|
# 后续设备:复用已有 salt,派生主密钥后存钥匙串(主密码需与首台相同)
|
||||||
|
secrets init
|
||||||
|
```
|
||||||
|
|
||||||
### search — 发现与读取
|
### search — 发现与读取
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -111,8 +176,8 @@ secrets config path # 打印配置文件路径
|
|||||||
# --name gitea | i-uf63f2uookgs5uxmrdyc | mqtt
|
# --name gitea | i-uf63f2uookgs5uxmrdyc | mqtt
|
||||||
# --tag aliyun | hongkong | production
|
# --tag aliyun | hongkong | production
|
||||||
# -q / --query mqtt | grafana | gitea (模糊匹配 name/namespace/kind/tags/metadata)
|
# -q / --query mqtt | grafana | gitea (模糊匹配 name/namespace/kind/tags/metadata)
|
||||||
# --show-secrets 不带值的 flag,显示 encrypted 字段内容
|
# --show-secrets 已弃用;search 不再直接展示 secrets
|
||||||
# -f / --field metadata.ip | metadata.url | secret.token | secret.ssh_key
|
# -f / --field metadata.ip | metadata.url | metadata.default_org
|
||||||
# --summary 不带值的 flag,仅返回摘要(name/tags/desc/updated_at)
|
# --summary 不带值的 flag,仅返回摘要(name/tags/desc/updated_at)
|
||||||
# --limit 20 | 50(默认 50)
|
# --limit 20 | 50(默认 50)
|
||||||
# --offset 0 | 10 | 20(分页偏移)
|
# --offset 0 | 10 | 20(分页偏移)
|
||||||
@@ -128,14 +193,17 @@ secrets search --sort updated --limit 10 --summary
|
|||||||
secrets search -n refining --kind service --name gitea
|
secrets search -n refining --kind service --name gitea
|
||||||
secrets search -n refining --kind server --name i-uf63f2uookgs5uxmrdyc
|
secrets search -n refining --kind server --name i-uf63f2uookgs5uxmrdyc
|
||||||
|
|
||||||
# 精确定位并获取完整内容(含 secrets)
|
# 精确定位并获取完整内容(secrets 保持加密占位)
|
||||||
secrets search -n refining --kind service --name gitea -o json --show-secrets
|
secrets search -n refining --kind service --name gitea -o json
|
||||||
|
|
||||||
# 直接提取字段值(最短路径,-f secret.* 自动解锁 secrets)
|
# 直接提取 metadata 字段值(最短路径)
|
||||||
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
|
||||||
secrets search -n refining --kind service --name gitea \
|
secrets search -n refining --kind service --name gitea \
|
||||||
-f metadata.url -f metadata.default_org -f secret.token
|
-f metadata.url -f metadata.default_org
|
||||||
|
|
||||||
|
# 需要 secrets 时,改用 inject / run
|
||||||
|
secrets inject -n refining --kind service --name gitea
|
||||||
|
secrets run -n refining --kind service --name gitea -- printenv
|
||||||
|
|
||||||
# 模糊关键词搜索
|
# 模糊关键词搜索
|
||||||
secrets search -q mqtt
|
secrets search -q mqtt
|
||||||
@@ -154,10 +222,9 @@ secrets search -n refining --summary --limit 10 --offset 10
|
|||||||
|
|
||||||
# 管道 / AI 调用(非 TTY 自动 json-compact)
|
# 管道 / AI 调用(非 TTY 自动 json-compact)
|
||||||
secrets search -n refining --kind service | jq '.[].name'
|
secrets search -n refining --kind service | jq '.[].name'
|
||||||
secrets search -n refining --kind service --name gitea --show-secrets | jq '.secrets.token'
|
|
||||||
|
|
||||||
# 导出为 env 文件(单条记录)
|
# 导出 metadata 为 env 文件(单条记录)
|
||||||
secrets search -n refining --kind service --name gitea -o env --show-secrets \
|
secrets search -n refining --kind service --name gitea -o env \
|
||||||
> ~/.config/gitea/config.env
|
> ~/.config/gitea/config.env
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -190,6 +257,13 @@ secrets add -n refining --kind service --name gitea \
|
|||||||
secrets add -n ricnsmart --kind service --name mqtt \
|
secrets add -n ricnsmart --kind service --name mqtt \
|
||||||
-m host=mqtt.ricnsmart.com -m port=1883 \
|
-m host=mqtt.ricnsmart.com -m port=1883 \
|
||||||
-s password=@./mqtt_password.txt
|
-s password=@./mqtt_password.txt
|
||||||
|
|
||||||
|
# 使用类型化值(key:=<json>)存储非字符串类型
|
||||||
|
secrets add -n refining --kind service --name prometheus \
|
||||||
|
-m scrape_interval:=15 \
|
||||||
|
-m enabled:=true \
|
||||||
|
-m labels:='["prod","metrics"]' \
|
||||||
|
-s api_key=abc123
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -250,10 +324,116 @@ secrets delete -n ricnsmart --kind server --name i-old-server-id
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### config — 配置管理
|
### history — 查看变更历史
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 设置数据库连接(每台设备执行一次,之后永久生效)
|
# 参数说明
|
||||||
|
# -n / --namespace refining | ricnsmart
|
||||||
|
# --kind server | service
|
||||||
|
# --name 记录名
|
||||||
|
# --limit 返回条数(默认 20)
|
||||||
|
|
||||||
|
# 查看某条记录的历史版本列表
|
||||||
|
secrets history -n refining --kind service --name gitea
|
||||||
|
|
||||||
|
# 查最近 5 条
|
||||||
|
secrets history -n refining --kind service --name gitea --limit 5
|
||||||
|
|
||||||
|
# JSON 输出
|
||||||
|
secrets history -n refining --kind service --name gitea -o json
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### rollback — 回滚到指定版本
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 参数说明
|
||||||
|
# -n / --namespace refining | ricnsmart
|
||||||
|
# --kind server | service
|
||||||
|
# --name 记录名
|
||||||
|
# --to-version <N> 目标版本号(省略则恢复最近一次快照)
|
||||||
|
|
||||||
|
# 撤销上次修改(回滚到最近一次快照)
|
||||||
|
secrets rollback -n refining --kind service --name gitea
|
||||||
|
|
||||||
|
# 回滚到版本 3
|
||||||
|
secrets rollback -n refining --kind service --name gitea --to-version 3
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### inject — 输出临时环境变量
|
||||||
|
|
||||||
|
敏感值仅打印到 stdout,不持久化、不写入当前 shell。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 参数说明
|
||||||
|
# -n / --namespace refining | ricnsmart
|
||||||
|
# --kind server | service
|
||||||
|
# --name 记录名
|
||||||
|
# --tag 按 tag 过滤(可重复)
|
||||||
|
# --prefix 变量名前缀(留空则以记录 name 作前缀)
|
||||||
|
# -o / --output text(默认 KEY=VALUE)| json | json-compact
|
||||||
|
|
||||||
|
# 打印单条记录的所有变量(KEY=VALUE 格式)
|
||||||
|
secrets inject -n refining --kind service --name gitea
|
||||||
|
|
||||||
|
# 自定义前缀
|
||||||
|
secrets inject -n refining --kind service --name gitea --prefix GITEA
|
||||||
|
|
||||||
|
# JSON 格式(适合管道或脚本解析)
|
||||||
|
secrets inject -n refining --kind service --name gitea -o json
|
||||||
|
|
||||||
|
# eval 注入当前 shell(谨慎使用)
|
||||||
|
eval $(secrets inject -n refining --kind service --name gitea)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### run — 向子进程注入 secrets 并执行命令
|
||||||
|
|
||||||
|
secrets 仅作用于子进程环境,不修改当前 shell,进程退出码透传。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 参数说明
|
||||||
|
# -n / --namespace refining | ricnsmart
|
||||||
|
# --kind server | service
|
||||||
|
# --name 记录名
|
||||||
|
# --tag 按 tag 过滤(可重复)
|
||||||
|
# --prefix 变量名前缀
|
||||||
|
# -- <command> 执行的命令及参数
|
||||||
|
|
||||||
|
# 向脚本注入单条记录的 secrets
|
||||||
|
secrets run -n refining --kind service --name gitea -- ./deploy.sh
|
||||||
|
|
||||||
|
# 按 tag 批量注入(多条记录合并)
|
||||||
|
secrets run --tag production -- env | grep -i token
|
||||||
|
|
||||||
|
# 验证注入了哪些变量
|
||||||
|
secrets run -n refining --kind service --name gitea -- printenv
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### upgrade — 自动更新 CLI 二进制
|
||||||
|
|
||||||
|
从 Gitea Release 下载最新版本,校验对应 `.sha256` 摘要后替换当前二进制,无需数据库连接或主密钥。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 检查是否有新版本(不下载)
|
||||||
|
secrets upgrade --check
|
||||||
|
|
||||||
|
# 下载、校验 SHA-256 并安装最新版本
|
||||||
|
secrets upgrade
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### config — 配置管理(无需主密钥)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 设置数据库连接(每台设备执行一次,之后永久生效;先验证连接可用再写入)
|
||||||
secrets config set-db "postgres://postgres:<password>@<host>:<port>/secrets"
|
secrets config set-db "postgres://postgres:<password>@<host>:<port>/secrets"
|
||||||
|
|
||||||
# 查看当前配置(密码脱敏)
|
# 查看当前配置(密码脱敏)
|
||||||
@@ -288,16 +468,25 @@ secrets --db-url "postgres://..." search -n refining
|
|||||||
- 新增 `kind` 类型时:只需在 `add` 调用时传入,无需改代码
|
- 新增 `kind` 类型时:只需在 `add` 调用时传入,无需改代码
|
||||||
- 字段命名:CLI 短标志 `-n`=namespace,`-m`=meta,`-s`=secret,`-q`=query,`-v`=verbose,`-f`=field,`-o`=output
|
- 字段命名:CLI 短标志 `-n`=namespace,`-m`=meta,`-s`=secret,`-q`=query,`-v`=verbose,`-f`=field,`-o`=output
|
||||||
- 日志:用户可见输出用 `println!`;调试/运维信息用 `tracing::debug!`/`info!`/`warn!`/`error!`
|
- 日志:用户可见输出用 `println!`;调试/运维信息用 `tracing::debug!`/`info!`/`warn!`/`error!`
|
||||||
- 审计:`add`/`update`/`delete` 成功后调用 `audit::log()`,写入 `audit_log` 表;失败只 warn 不中断
|
- 审计:`add`/`update`/`delete` 成功后调用 `audit::log_tx`,写入 `audit_log` 表;失败只 warn 不中断
|
||||||
|
- 加密:`encrypted` 列存储 AES-256-GCM 密文;`add`/`update`/`search`/`delete` 需主密钥(`secrets init` 后从 OS 钥匙串加载)
|
||||||
- 输出:读命令通过 `OutputMode` 支持 text/json/json-compact/env;写命令 `add` 同样支持 `-o json`
|
- 输出:读命令通过 `OutputMode` 支持 text/json/json-compact/env;写命令 `add` 同样支持 `-o json`
|
||||||
|
|
||||||
## 提交前检查(必须全部通过)
|
## 提交前检查(必须全部通过)
|
||||||
|
|
||||||
每次提交代码前,请在本地依次执行以下检查,**全部通过后再 push**:
|
每次提交代码前,请在本地依次执行以下检查,**全部通过后再 push**:
|
||||||
|
|
||||||
|
优先使用:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./scripts/release-check.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
它等价于先检查版本号 / tag,再执行下面的格式、Lint、测试。
|
||||||
|
|
||||||
### 1. 版本号(按需)
|
### 1. 版本号(按需)
|
||||||
|
|
||||||
若本次改动需要发版,请先确认 `Cargo.toml` 中的 `version` 已提升,避免 CI 打出的 Tag 与已有版本重复。可通过 git tag 判断:
|
若本次改动需要发版,请先确认 `Cargo.toml` 中的 `version` 已提升,避免 CI 打出的 Tag 与已有版本重复。**升级版本后需同时更新 `Cargo.lock`**(运行 `cargo build` 即可自动同步),否则 CI 中 `cargo clippy --locked` 会因 lock 与 manifest 不一致而失败。可通过 git tag 判断:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 查看当前 Cargo.toml 版本
|
# 查看当前 Cargo.toml 版本
|
||||||
@@ -307,7 +496,7 @@ grep '^version' Cargo.toml
|
|||||||
git tag -l 'secrets-*'
|
git tag -l 'secrets-*'
|
||||||
```
|
```
|
||||||
|
|
||||||
若当前版本已被 tag(例如已有 `secrets-0.3.0` 且 `Cargo.toml` 仍为 `0.3.0`),则应在 `Cargo.toml` 中 bump 版本号后再提交,以便 CI 自动打新 Tag 并发布 Release。
|
若当前版本已被 tag(例如已有 `secrets-0.3.0` 且 `Cargo.toml` 仍为 `0.3.0`),则应在 `Cargo.toml` 中 bump 版本号,再执行 `cargo build` 同步 `Cargo.lock`,最后一并提交,以便 CI 自动打新 Tag 并发布 Release。
|
||||||
|
|
||||||
### 2. 格式、Lint、测试
|
### 2. 格式、Lint、测试
|
||||||
|
|
||||||
@@ -325,12 +514,14 @@ cargo fmt -- --check && cargo clippy -- -D warnings && cargo test
|
|||||||
|
|
||||||
## CI/CD
|
## CI/CD
|
||||||
|
|
||||||
- Gitea Actions(runner: debian)
|
- Gitea Actions(runners: debian / darwin-arm64 / windows)
|
||||||
- 触发:`src/**`、`Cargo.toml`、`Cargo.lock` 变更推送到 main
|
- 触发:`src/**`、`Cargo.toml`、`Cargo.lock` 变更推送到 main
|
||||||
- 构建目标:`x86_64-unknown-linux-musl`(静态链接,无 glibc 依赖)
|
- 构建目标:`x86_64-unknown-linux-musl`、`aarch64-apple-darwin`、`x86_64-apple-darwin`(由 ARM mac runner 交叉编译)、`x86_64-pc-windows-msvc`
|
||||||
- 新版本自动打 Tag(格式 `secrets-<version>`)并上传二进制到 Gitea Release
|
- 新版本自动打 Tag(格式 `secrets-<version>`)并上传二进制与对应 `.sha256` 摘要到 Gitea Release
|
||||||
|
- Release 仅在 Linux/macOS/Windows 构建全部成功后才会从 draft 发布
|
||||||
- 通知:飞书 Webhook(`vars.WEBHOOK_URL`)
|
- 通知:飞书 Webhook(`vars.WEBHOOK_URL`)
|
||||||
- 所需 secrets/vars:`RELEASE_TOKEN`(Release 上传,Gitea PAT)、`vars.WEBHOOK_URL`(通知,可选)
|
- 所需 secrets/vars:`RELEASE_TOKEN`(Release 上传,Gitea PAT)、`vars.WEBHOOK_URL`(通知,可选)
|
||||||
|
- **注意**:Gitea Actions 的 Secret/Variable 创建时,`data`/`value` 字段需传入**原始值**,不要使用 base64 编码
|
||||||
|
|
||||||
## 环境变量
|
## 环境变量
|
||||||
|
|
||||||
|
|||||||
669
Cargo.lock
generated
669
Cargo.lock
generated
@@ -2,6 +2,12 @@
|
|||||||
# It is not intended for manual editing.
|
# It is not intended for manual editing.
|
||||||
version = 4
|
version = 4
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "adler2"
|
||||||
|
version = "2.0.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "aead"
|
name = "aead"
|
||||||
version = "0.5.2"
|
version = "0.5.2"
|
||||||
@@ -138,6 +144,12 @@ dependencies = [
|
|||||||
"num-traits",
|
"num-traits",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "atomic-waker"
|
||||||
|
version = "1.1.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "autocfg"
|
name = "autocfg"
|
||||||
version = "1.5.0"
|
version = "1.5.0"
|
||||||
@@ -217,6 +229,12 @@ version = "1.0.4"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cfg_aliases"
|
||||||
|
version = "0.2.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "chacha20"
|
name = "chacha20"
|
||||||
version = "0.10.0"
|
version = "0.10.0"
|
||||||
@@ -372,6 +390,15 @@ version = "2.4.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5"
|
checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "crc32fast"
|
||||||
|
version = "1.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "crossbeam-queue"
|
name = "crossbeam-queue"
|
||||||
version = "0.3.12"
|
version = "0.3.12"
|
||||||
@@ -515,12 +542,40 @@ dependencies = [
|
|||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "fastrand"
|
||||||
|
version = "2.3.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "filetime"
|
||||||
|
version = "0.2.27"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f98844151eee8917efc50bd9e8318cb963ae8b297431495d3f758616ea5c57db"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"libc",
|
||||||
|
"libredox",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "find-msvc-tools"
|
name = "find-msvc-tools"
|
||||||
version = "0.1.9"
|
version = "0.1.9"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
|
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "flate2"
|
||||||
|
version = "1.1.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
|
||||||
|
dependencies = [
|
||||||
|
"crc32fast",
|
||||||
|
"miniz_oxide",
|
||||||
|
"zlib-rs",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "flume"
|
name = "flume"
|
||||||
version = "0.11.1"
|
version = "0.11.1"
|
||||||
@@ -635,8 +690,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
|
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
|
"js-sys",
|
||||||
"libc",
|
"libc",
|
||||||
"wasi",
|
"wasi",
|
||||||
|
"wasm-bindgen",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "getrandom"
|
||||||
|
version = "0.3.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"js-sys",
|
||||||
|
"libc",
|
||||||
|
"r-efi 5.3.0",
|
||||||
|
"wasip2",
|
||||||
|
"wasm-bindgen",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -647,7 +718,7 @@ checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
"libc",
|
"libc",
|
||||||
"r-efi",
|
"r-efi 6.0.0",
|
||||||
"rand_core 0.10.0",
|
"rand_core 0.10.0",
|
||||||
"wasip2",
|
"wasip2",
|
||||||
"wasip3",
|
"wasip3",
|
||||||
@@ -728,6 +799,106 @@ dependencies = [
|
|||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "http"
|
||||||
|
version = "1.4.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a"
|
||||||
|
dependencies = [
|
||||||
|
"bytes",
|
||||||
|
"itoa",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "http-body"
|
||||||
|
version = "1.0.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"
|
||||||
|
dependencies = [
|
||||||
|
"bytes",
|
||||||
|
"http",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "http-body-util"
|
||||||
|
version = "0.1.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a"
|
||||||
|
dependencies = [
|
||||||
|
"bytes",
|
||||||
|
"futures-core",
|
||||||
|
"http",
|
||||||
|
"http-body",
|
||||||
|
"pin-project-lite",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "httparse"
|
||||||
|
version = "1.10.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "hyper"
|
||||||
|
version = "1.8.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11"
|
||||||
|
dependencies = [
|
||||||
|
"atomic-waker",
|
||||||
|
"bytes",
|
||||||
|
"futures-channel",
|
||||||
|
"futures-core",
|
||||||
|
"http",
|
||||||
|
"http-body",
|
||||||
|
"httparse",
|
||||||
|
"itoa",
|
||||||
|
"pin-project-lite",
|
||||||
|
"pin-utils",
|
||||||
|
"smallvec",
|
||||||
|
"tokio",
|
||||||
|
"want",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "hyper-rustls"
|
||||||
|
version = "0.27.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58"
|
||||||
|
dependencies = [
|
||||||
|
"http",
|
||||||
|
"hyper",
|
||||||
|
"hyper-util",
|
||||||
|
"rustls",
|
||||||
|
"rustls-pki-types",
|
||||||
|
"tokio",
|
||||||
|
"tokio-rustls",
|
||||||
|
"tower-service",
|
||||||
|
"webpki-roots 1.0.6",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "hyper-util"
|
||||||
|
version = "0.1.20"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
|
||||||
|
dependencies = [
|
||||||
|
"base64",
|
||||||
|
"bytes",
|
||||||
|
"futures-channel",
|
||||||
|
"futures-util",
|
||||||
|
"http",
|
||||||
|
"http-body",
|
||||||
|
"hyper",
|
||||||
|
"ipnet",
|
||||||
|
"libc",
|
||||||
|
"percent-encoding",
|
||||||
|
"pin-project-lite",
|
||||||
|
"socket2",
|
||||||
|
"tokio",
|
||||||
|
"tower-service",
|
||||||
|
"tracing",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "iana-time-zone"
|
name = "iana-time-zone"
|
||||||
version = "0.1.65"
|
version = "0.1.65"
|
||||||
@@ -881,6 +1052,22 @@ dependencies = [
|
|||||||
"generic-array",
|
"generic-array",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ipnet"
|
||||||
|
version = "2.12.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "iri-string"
|
||||||
|
version = "0.7.10"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c91338f0783edbd6195decb37bae672fd3b165faffb89bf7b9e6942f8b1a731a"
|
||||||
|
dependencies = [
|
||||||
|
"memchr",
|
||||||
|
"serde",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "is_terminal_polyfill"
|
name = "is_terminal_polyfill"
|
||||||
version = "1.70.2"
|
version = "1.70.2"
|
||||||
@@ -909,9 +1096,12 @@ version = "3.6.3"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c"
|
checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"byteorder",
|
||||||
|
"linux-keyutils",
|
||||||
"log",
|
"log",
|
||||||
"security-framework 2.11.1",
|
"security-framework 2.11.1",
|
||||||
"security-framework 3.7.0",
|
"security-framework 3.7.0",
|
||||||
|
"windows-sys 0.60.2",
|
||||||
"zeroize",
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -964,6 +1154,22 @@ dependencies = [
|
|||||||
"vcpkg",
|
"vcpkg",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "linux-keyutils"
|
||||||
|
version = "0.2.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "761e49ec5fd8a5a463f9b84e877c373d888935b71c6be78f3767fe2ae6bed18e"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags",
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "linux-raw-sys"
|
||||||
|
version = "0.12.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "litemap"
|
name = "litemap"
|
||||||
version = "0.8.1"
|
version = "0.8.1"
|
||||||
@@ -985,6 +1191,12 @@ version = "0.4.29"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
|
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "lru-slab"
|
||||||
|
version = "0.1.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "matchers"
|
name = "matchers"
|
||||||
version = "0.2.0"
|
version = "0.2.0"
|
||||||
@@ -1010,6 +1222,16 @@ version = "2.8.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
|
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "miniz_oxide"
|
||||||
|
version = "0.8.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
|
||||||
|
dependencies = [
|
||||||
|
"adler2",
|
||||||
|
"simd-adler32",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mio"
|
name = "mio"
|
||||||
version = "1.1.1"
|
version = "1.1.1"
|
||||||
@@ -1161,6 +1383,12 @@ version = "0.2.17"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pin-utils"
|
||||||
|
version = "0.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pkcs1"
|
name = "pkcs1"
|
||||||
version = "0.7.5"
|
version = "0.7.5"
|
||||||
@@ -1243,6 +1471,61 @@ dependencies = [
|
|||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "quinn"
|
||||||
|
version = "0.11.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20"
|
||||||
|
dependencies = [
|
||||||
|
"bytes",
|
||||||
|
"cfg_aliases",
|
||||||
|
"pin-project-lite",
|
||||||
|
"quinn-proto",
|
||||||
|
"quinn-udp",
|
||||||
|
"rustc-hash",
|
||||||
|
"rustls",
|
||||||
|
"socket2",
|
||||||
|
"thiserror",
|
||||||
|
"tokio",
|
||||||
|
"tracing",
|
||||||
|
"web-time",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "quinn-proto"
|
||||||
|
version = "0.11.14"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098"
|
||||||
|
dependencies = [
|
||||||
|
"bytes",
|
||||||
|
"getrandom 0.3.4",
|
||||||
|
"lru-slab",
|
||||||
|
"rand 0.9.2",
|
||||||
|
"ring",
|
||||||
|
"rustc-hash",
|
||||||
|
"rustls",
|
||||||
|
"rustls-pki-types",
|
||||||
|
"slab",
|
||||||
|
"thiserror",
|
||||||
|
"tinyvec",
|
||||||
|
"tracing",
|
||||||
|
"web-time",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "quinn-udp"
|
||||||
|
version = "0.5.14"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"
|
||||||
|
dependencies = [
|
||||||
|
"cfg_aliases",
|
||||||
|
"libc",
|
||||||
|
"once_cell",
|
||||||
|
"socket2",
|
||||||
|
"tracing",
|
||||||
|
"windows-sys 0.60.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "quote"
|
name = "quote"
|
||||||
version = "1.0.45"
|
version = "1.0.45"
|
||||||
@@ -1252,6 +1535,12 @@ dependencies = [
|
|||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "r-efi"
|
||||||
|
version = "5.3.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "r-efi"
|
name = "r-efi"
|
||||||
version = "6.0.0"
|
version = "6.0.0"
|
||||||
@@ -1265,10 +1554,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
|
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"libc",
|
"libc",
|
||||||
"rand_chacha",
|
"rand_chacha 0.3.1",
|
||||||
"rand_core 0.6.4",
|
"rand_core 0.6.4",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rand"
|
||||||
|
version = "0.9.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"
|
||||||
|
dependencies = [
|
||||||
|
"rand_chacha 0.9.0",
|
||||||
|
"rand_core 0.9.5",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rand"
|
name = "rand"
|
||||||
version = "0.10.0"
|
version = "0.10.0"
|
||||||
@@ -1290,6 +1589,16 @@ dependencies = [
|
|||||||
"rand_core 0.6.4",
|
"rand_core 0.6.4",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rand_chacha"
|
||||||
|
version = "0.9.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||||
|
dependencies = [
|
||||||
|
"ppv-lite86",
|
||||||
|
"rand_core 0.9.5",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rand_core"
|
name = "rand_core"
|
||||||
version = "0.6.4"
|
version = "0.6.4"
|
||||||
@@ -1299,6 +1608,15 @@ dependencies = [
|
|||||||
"getrandom 0.2.17",
|
"getrandom 0.2.17",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rand_core"
|
||||||
|
version = "0.9.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
|
||||||
|
dependencies = [
|
||||||
|
"getrandom 0.3.4",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rand_core"
|
name = "rand_core"
|
||||||
version = "0.10.0"
|
version = "0.10.0"
|
||||||
@@ -1351,6 +1669,44 @@ version = "0.8.10"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
|
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "reqwest"
|
||||||
|
version = "0.12.28"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
|
||||||
|
dependencies = [
|
||||||
|
"base64",
|
||||||
|
"bytes",
|
||||||
|
"futures-core",
|
||||||
|
"http",
|
||||||
|
"http-body",
|
||||||
|
"http-body-util",
|
||||||
|
"hyper",
|
||||||
|
"hyper-rustls",
|
||||||
|
"hyper-util",
|
||||||
|
"js-sys",
|
||||||
|
"log",
|
||||||
|
"percent-encoding",
|
||||||
|
"pin-project-lite",
|
||||||
|
"quinn",
|
||||||
|
"rustls",
|
||||||
|
"rustls-pki-types",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"serde_urlencoded",
|
||||||
|
"sync_wrapper",
|
||||||
|
"tokio",
|
||||||
|
"tokio-rustls",
|
||||||
|
"tower",
|
||||||
|
"tower-http",
|
||||||
|
"tower-service",
|
||||||
|
"url",
|
||||||
|
"wasm-bindgen",
|
||||||
|
"wasm-bindgen-futures",
|
||||||
|
"web-sys",
|
||||||
|
"webpki-roots 1.0.6",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ring"
|
name = "ring"
|
||||||
version = "0.17.14"
|
version = "0.17.14"
|
||||||
@@ -1406,6 +1762,25 @@ dependencies = [
|
|||||||
"windows-sys 0.52.0",
|
"windows-sys 0.52.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustc-hash"
|
||||||
|
version = "2.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustix"
|
||||||
|
version = "1.1.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags",
|
||||||
|
"errno",
|
||||||
|
"libc",
|
||||||
|
"linux-raw-sys",
|
||||||
|
"windows-sys 0.61.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustls"
|
name = "rustls"
|
||||||
version = "0.23.36"
|
version = "0.23.36"
|
||||||
@@ -1426,6 +1801,7 @@ version = "1.14.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"
|
checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"web-time",
|
||||||
"zeroize",
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -1460,7 +1836,7 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "secrets"
|
name = "secrets"
|
||||||
version = "0.5.0"
|
version = "0.7.3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aes-gcm",
|
"aes-gcm",
|
||||||
"anyhow",
|
"anyhow",
|
||||||
@@ -1468,17 +1844,25 @@ dependencies = [
|
|||||||
"chrono",
|
"chrono",
|
||||||
"clap",
|
"clap",
|
||||||
"dirs",
|
"dirs",
|
||||||
|
"flate2",
|
||||||
"keyring",
|
"keyring",
|
||||||
"rand 0.10.0",
|
"rand 0.10.0",
|
||||||
|
"reqwest",
|
||||||
"rpassword",
|
"rpassword",
|
||||||
|
"self-replace",
|
||||||
|
"semver",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
"sha2",
|
||||||
"sqlx",
|
"sqlx",
|
||||||
|
"tar",
|
||||||
|
"tempfile",
|
||||||
"tokio",
|
"tokio",
|
||||||
"toml",
|
"toml",
|
||||||
"tracing",
|
"tracing",
|
||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
"uuid",
|
"uuid",
|
||||||
|
"zip",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1517,6 +1901,17 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "self-replace"
|
||||||
|
version = "1.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "03ec815b5eab420ab893f63393878d89c90fdd94c0bcc44c07abb8ad95552fb7"
|
||||||
|
dependencies = [
|
||||||
|
"fastrand",
|
||||||
|
"tempfile",
|
||||||
|
"windows-sys 0.52.0",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "semver"
|
name = "semver"
|
||||||
version = "1.0.27"
|
version = "1.0.27"
|
||||||
@@ -1644,6 +2039,12 @@ dependencies = [
|
|||||||
"rand_core 0.6.4",
|
"rand_core 0.6.4",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "simd-adler32"
|
||||||
|
version = "0.3.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "slab"
|
name = "slab"
|
||||||
version = "0.4.12"
|
version = "0.4.12"
|
||||||
@@ -1926,6 +2327,15 @@ dependencies = [
|
|||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "sync_wrapper"
|
||||||
|
version = "1.0.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
|
||||||
|
dependencies = [
|
||||||
|
"futures-core",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "synstructure"
|
name = "synstructure"
|
||||||
version = "0.13.2"
|
version = "0.13.2"
|
||||||
@@ -1937,6 +2347,30 @@ dependencies = [
|
|||||||
"syn",
|
"syn",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tar"
|
||||||
|
version = "0.4.44"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1d863878d212c87a19c1a610eb53bb01fe12951c0501cf5a0d65f724914a667a"
|
||||||
|
dependencies = [
|
||||||
|
"filetime",
|
||||||
|
"libc",
|
||||||
|
"xattr",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tempfile"
|
||||||
|
version = "3.27.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||||
|
dependencies = [
|
||||||
|
"fastrand",
|
||||||
|
"getrandom 0.4.2",
|
||||||
|
"once_cell",
|
||||||
|
"rustix",
|
||||||
|
"windows-sys 0.61.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "thiserror"
|
name = "thiserror"
|
||||||
version = "2.0.18"
|
version = "2.0.18"
|
||||||
@@ -2019,6 +2453,16 @@ dependencies = [
|
|||||||
"syn",
|
"syn",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tokio-rustls"
|
||||||
|
version = "0.26.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"
|
||||||
|
dependencies = [
|
||||||
|
"rustls",
|
||||||
|
"tokio",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tokio-stream"
|
name = "tokio-stream"
|
||||||
version = "0.1.18"
|
version = "0.1.18"
|
||||||
@@ -2069,6 +2513,51 @@ version = "1.0.7+spec-1.1.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f17aaa1c6e3dc22b1da4b6bba97d066e354c7945cac2f7852d4e4e7ca7a6b56d"
|
checksum = "f17aaa1c6e3dc22b1da4b6bba97d066e354c7945cac2f7852d4e4e7ca7a6b56d"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tower"
|
||||||
|
version = "0.5.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
|
||||||
|
dependencies = [
|
||||||
|
"futures-core",
|
||||||
|
"futures-util",
|
||||||
|
"pin-project-lite",
|
||||||
|
"sync_wrapper",
|
||||||
|
"tokio",
|
||||||
|
"tower-layer",
|
||||||
|
"tower-service",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tower-http"
|
||||||
|
version = "0.6.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags",
|
||||||
|
"bytes",
|
||||||
|
"futures-util",
|
||||||
|
"http",
|
||||||
|
"http-body",
|
||||||
|
"iri-string",
|
||||||
|
"pin-project-lite",
|
||||||
|
"tower",
|
||||||
|
"tower-layer",
|
||||||
|
"tower-service",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tower-layer"
|
||||||
|
version = "0.3.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tower-service"
|
||||||
|
version = "0.3.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tracing"
|
name = "tracing"
|
||||||
version = "0.1.44"
|
version = "0.1.44"
|
||||||
@@ -2131,6 +2620,18 @@ dependencies = [
|
|||||||
"tracing-log",
|
"tracing-log",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "try-lock"
|
||||||
|
version = "0.2.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "typed-path"
|
||||||
|
version = "0.12.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "typenum"
|
name = "typenum"
|
||||||
version = "1.19.0"
|
version = "1.19.0"
|
||||||
@@ -2216,7 +2717,6 @@ version = "1.22.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a68d3c8f01c0cfa54a75291d83601161799e4a89a39e0929f4b0354d88757a37"
|
checksum = "a68d3c8f01c0cfa54a75291d83601161799e4a89a39e0929f4b0354d88757a37"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"getrandom 0.4.2",
|
|
||||||
"js-sys",
|
"js-sys",
|
||||||
"serde_core",
|
"serde_core",
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
@@ -2240,6 +2740,15 @@ version = "0.9.5"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "want"
|
||||||
|
version = "0.3.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
|
||||||
|
dependencies = [
|
||||||
|
"try-lock",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wasi"
|
name = "wasi"
|
||||||
version = "0.11.1+wasi-snapshot-preview1"
|
version = "0.11.1+wasi-snapshot-preview1"
|
||||||
@@ -2283,6 +2792,20 @@ dependencies = [
|
|||||||
"wasm-bindgen-shared",
|
"wasm-bindgen-shared",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wasm-bindgen-futures"
|
||||||
|
version = "0.4.64"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e9c5522b3a28661442748e09d40924dfb9ca614b21c00d3fd135720e48b67db8"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"futures-util",
|
||||||
|
"js-sys",
|
||||||
|
"once_cell",
|
||||||
|
"wasm-bindgen",
|
||||||
|
"web-sys",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wasm-bindgen-macro"
|
name = "wasm-bindgen-macro"
|
||||||
version = "0.2.114"
|
version = "0.2.114"
|
||||||
@@ -2349,6 +2872,26 @@ dependencies = [
|
|||||||
"semver",
|
"semver",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "web-sys"
|
||||||
|
version = "0.3.91"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "854ba17bb104abfb26ba36da9729addc7ce7f06f5c0f90f3c391f8461cca21f9"
|
||||||
|
dependencies = [
|
||||||
|
"js-sys",
|
||||||
|
"wasm-bindgen",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "web-time"
|
||||||
|
version = "1.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
|
||||||
|
dependencies = [
|
||||||
|
"js-sys",
|
||||||
|
"wasm-bindgen",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "webpki-roots"
|
name = "webpki-roots"
|
||||||
version = "0.26.11"
|
version = "0.26.11"
|
||||||
@@ -2463,6 +3006,15 @@ dependencies = [
|
|||||||
"windows-targets 0.52.6",
|
"windows-targets 0.52.6",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-sys"
|
||||||
|
version = "0.60.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
|
||||||
|
dependencies = [
|
||||||
|
"windows-targets 0.53.5",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows-sys"
|
name = "windows-sys"
|
||||||
version = "0.61.2"
|
version = "0.61.2"
|
||||||
@@ -2496,13 +3048,30 @@ dependencies = [
|
|||||||
"windows_aarch64_gnullvm 0.52.6",
|
"windows_aarch64_gnullvm 0.52.6",
|
||||||
"windows_aarch64_msvc 0.52.6",
|
"windows_aarch64_msvc 0.52.6",
|
||||||
"windows_i686_gnu 0.52.6",
|
"windows_i686_gnu 0.52.6",
|
||||||
"windows_i686_gnullvm",
|
"windows_i686_gnullvm 0.52.6",
|
||||||
"windows_i686_msvc 0.52.6",
|
"windows_i686_msvc 0.52.6",
|
||||||
"windows_x86_64_gnu 0.52.6",
|
"windows_x86_64_gnu 0.52.6",
|
||||||
"windows_x86_64_gnullvm 0.52.6",
|
"windows_x86_64_gnullvm 0.52.6",
|
||||||
"windows_x86_64_msvc 0.52.6",
|
"windows_x86_64_msvc 0.52.6",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-targets"
|
||||||
|
version = "0.53.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
|
||||||
|
dependencies = [
|
||||||
|
"windows-link",
|
||||||
|
"windows_aarch64_gnullvm 0.53.1",
|
||||||
|
"windows_aarch64_msvc 0.53.1",
|
||||||
|
"windows_i686_gnu 0.53.1",
|
||||||
|
"windows_i686_gnullvm 0.53.1",
|
||||||
|
"windows_i686_msvc 0.53.1",
|
||||||
|
"windows_x86_64_gnu 0.53.1",
|
||||||
|
"windows_x86_64_gnullvm 0.53.1",
|
||||||
|
"windows_x86_64_msvc 0.53.1",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_aarch64_gnullvm"
|
name = "windows_aarch64_gnullvm"
|
||||||
version = "0.48.5"
|
version = "0.48.5"
|
||||||
@@ -2515,6 +3084,12 @@ version = "0.52.6"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
|
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_aarch64_gnullvm"
|
||||||
|
version = "0.53.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_aarch64_msvc"
|
name = "windows_aarch64_msvc"
|
||||||
version = "0.48.5"
|
version = "0.48.5"
|
||||||
@@ -2527,6 +3102,12 @@ version = "0.52.6"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
|
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_aarch64_msvc"
|
||||||
|
version = "0.53.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_i686_gnu"
|
name = "windows_i686_gnu"
|
||||||
version = "0.48.5"
|
version = "0.48.5"
|
||||||
@@ -2539,12 +3120,24 @@ version = "0.52.6"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
|
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_i686_gnu"
|
||||||
|
version = "0.53.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_i686_gnullvm"
|
name = "windows_i686_gnullvm"
|
||||||
version = "0.52.6"
|
version = "0.52.6"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
|
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_i686_gnullvm"
|
||||||
|
version = "0.53.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_i686_msvc"
|
name = "windows_i686_msvc"
|
||||||
version = "0.48.5"
|
version = "0.48.5"
|
||||||
@@ -2557,6 +3150,12 @@ version = "0.52.6"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
|
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_i686_msvc"
|
||||||
|
version = "0.53.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_x86_64_gnu"
|
name = "windows_x86_64_gnu"
|
||||||
version = "0.48.5"
|
version = "0.48.5"
|
||||||
@@ -2569,6 +3168,12 @@ version = "0.52.6"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
|
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_x86_64_gnu"
|
||||||
|
version = "0.53.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_x86_64_gnullvm"
|
name = "windows_x86_64_gnullvm"
|
||||||
version = "0.48.5"
|
version = "0.48.5"
|
||||||
@@ -2581,6 +3186,12 @@ version = "0.52.6"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
|
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_x86_64_gnullvm"
|
||||||
|
version = "0.53.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_x86_64_msvc"
|
name = "windows_x86_64_msvc"
|
||||||
version = "0.48.5"
|
version = "0.48.5"
|
||||||
@@ -2593,6 +3204,12 @@ version = "0.52.6"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_x86_64_msvc"
|
||||||
|
version = "0.53.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "winnow"
|
name = "winnow"
|
||||||
version = "1.0.0"
|
version = "1.0.0"
|
||||||
@@ -2693,6 +3310,16 @@ version = "0.6.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9"
|
checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "xattr"
|
||||||
|
version = "1.6.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"rustix",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "yoke"
|
name = "yoke"
|
||||||
version = "0.8.1"
|
version = "0.8.1"
|
||||||
@@ -2796,8 +3423,40 @@ dependencies = [
|
|||||||
"syn",
|
"syn",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zip"
|
||||||
|
version = "8.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b680f2a0cd479b4cff6e1233c483fdead418106eae419dc60200ae9850f6d004"
|
||||||
|
dependencies = [
|
||||||
|
"crc32fast",
|
||||||
|
"flate2",
|
||||||
|
"indexmap",
|
||||||
|
"memchr",
|
||||||
|
"typed-path",
|
||||||
|
"zopfli",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zlib-rs"
|
||||||
|
version = "0.6.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3be3d40e40a133f9c916ee3f9f4fa2d9d63435b5fbe1bfc6d9dae0aa0ada1513"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zmij"
|
name = "zmij"
|
||||||
version = "1.0.21"
|
version = "1.0.21"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
|
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zopfli"
|
||||||
|
version = "0.8.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"
|
||||||
|
dependencies = [
|
||||||
|
"bumpalo",
|
||||||
|
"crc32fast",
|
||||||
|
"log",
|
||||||
|
"simd-adler32",
|
||||||
|
]
|
||||||
|
|||||||
16
Cargo.toml
16
Cargo.toml
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "secrets"
|
name = "secrets"
|
||||||
version = "0.5.0"
|
version = "0.7.3"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
@@ -8,16 +8,24 @@ aes-gcm = "0.10.3"
|
|||||||
anyhow = "1.0.102"
|
anyhow = "1.0.102"
|
||||||
argon2 = { version = "0.5.3", features = ["std"] }
|
argon2 = { version = "0.5.3", features = ["std"] }
|
||||||
chrono = { version = "0.4.44", features = ["serde"] }
|
chrono = { version = "0.4.44", features = ["serde"] }
|
||||||
clap = { version = "4.6.0", features = ["derive", "env"] }
|
clap = { version = "4.6.0", features = ["derive"] }
|
||||||
dirs = "6.0.0"
|
dirs = "6.0.0"
|
||||||
keyring = { version = "3.6.3", features = ["apple-native"] }
|
flate2 = "1.1.9"
|
||||||
|
keyring = { version = "3.6.3", features = ["apple-native", "windows-native", "linux-native"] }
|
||||||
rand = "0.10.0"
|
rand = "0.10.0"
|
||||||
|
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json"] }
|
||||||
rpassword = "7.4.0"
|
rpassword = "7.4.0"
|
||||||
|
self-replace = "1.5.0"
|
||||||
|
semver = "1.0.27"
|
||||||
serde = { version = "1.0.228", features = ["derive"] }
|
serde = { version = "1.0.228", features = ["derive"] }
|
||||||
serde_json = "1.0.149"
|
serde_json = "1.0.149"
|
||||||
|
sha2 = "0.10.9"
|
||||||
sqlx = { version = "0.8.6", features = ["runtime-tokio", "tls-rustls", "postgres", "uuid", "json", "chrono"] }
|
sqlx = { version = "0.8.6", features = ["runtime-tokio", "tls-rustls", "postgres", "uuid", "json", "chrono"] }
|
||||||
|
tar = "0.4.44"
|
||||||
|
tempfile = "3.19"
|
||||||
tokio = { version = "1.50.0", features = ["full"] }
|
tokio = { version = "1.50.0", features = ["full"] }
|
||||||
toml = "1.0.7"
|
toml = "1.0.7"
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||||
uuid = { version = "1.22.0", features = ["serde", "v4"] }
|
uuid = { version = "1.22.0", features = ["serde"] }
|
||||||
|
zip = { version = "8.2.0", default-features = false, features = ["deflate"] }
|
||||||
|
|||||||
82
README.md
82
README.md
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
跨设备密钥与配置管理 CLI,基于 Rust + PostgreSQL 18。
|
跨设备密钥与配置管理 CLI,基于 Rust + PostgreSQL 18。
|
||||||
|
|
||||||
将服务器信息、服务凭据统一存入数据库,供本地工具和 AI 读取上下文。
|
将服务器信息、服务凭据统一存入数据库,供本地工具和 AI 读取上下文。敏感数据(`encrypted` 字段)使用 AES-256-GCM 加密存储,主密钥由 Argon2id 从主密码派生并存入系统钥匙串。
|
||||||
|
|
||||||
## 安装
|
## 安装
|
||||||
|
|
||||||
@@ -11,12 +11,24 @@ cargo build --release
|
|||||||
# 或从 Release 页面下载预编译二进制
|
# 或从 Release 页面下载预编译二进制
|
||||||
```
|
```
|
||||||
|
|
||||||
配置数据库连接(首次使用需执行一次,之后在该设备上持久生效):
|
已有旧版本时,可执行 `secrets upgrade` 自动下载最新版并替换。该命令会校验 Release 附带的 `.sha256` 摘要后再安装。
|
||||||
|
|
||||||
|
## 首次使用(每台设备各执行一次)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
# 1. 配置数据库连接(会先验证连接可用再写入)
|
||||||
secrets config set-db "postgres://postgres:<password>@<host>:<port>/secrets"
|
secrets config set-db "postgres://postgres:<password>@<host>:<port>/secrets"
|
||||||
|
|
||||||
|
# 2. 初始化主密钥(提示输入至少 8 位的主密码,派生后存入 OS 钥匙串)
|
||||||
|
secrets init
|
||||||
```
|
```
|
||||||
|
|
||||||
|
主密码不会存储,仅用于派生主密钥,且至少需 8 位。同一主密码在所有设备上会得到相同主密钥(salt 存于数据库,首台设备生成后共享)。
|
||||||
|
|
||||||
|
**主密钥存储**:macOS → Keychain;Windows → Credential Manager;Linux → keyutils(会话级,重启后需再次 `secrets init`)。
|
||||||
|
|
||||||
|
**从旧版(明文存储)升级**:升级后首次运行需执行 `secrets init` 即可(明文记录需手动重新 add 或通过 update 更新)。
|
||||||
|
|
||||||
## AI Agent 快速指南
|
## AI Agent 快速指南
|
||||||
|
|
||||||
这个 CLI 以 AI 使用优先设计。核心路径只有一条:**读取用 `search`,写入用 `add` / `update`**。
|
这个 CLI 以 AI 使用优先设计。核心路径只有一条:**读取用 `search`,写入用 `add` / `update`**。
|
||||||
@@ -42,37 +54,46 @@ secrets search --sort updated --limit 10 --summary
|
|||||||
# 精确定位(namespace + kind + name 三元组)
|
# 精确定位(namespace + kind + name 三元组)
|
||||||
secrets search -n refining --kind service --name gitea
|
secrets search -n refining --kind service --name gitea
|
||||||
|
|
||||||
# 获取完整记录含 secrets(JSON 格式,AI 最易解析)
|
# 获取完整记录(secrets 保持加密占位)
|
||||||
secrets search -n refining --kind service --name gitea -o json --show-secrets
|
secrets search -n refining --kind service --name gitea -o json
|
||||||
|
|
||||||
# 直接提取单个字段值(最短路径)
|
# 直接提取单个 metadata 字段值(最短路径)
|
||||||
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
|
||||||
|
|
||||||
# 同时提取多个字段
|
# 同时提取多个 metadata 字段
|
||||||
secrets search -n refining --kind service --name gitea \
|
secrets search -n refining --kind service --name gitea \
|
||||||
-f metadata.url -f metadata.default_org -f secret.token
|
-f metadata.url -f metadata.default_org
|
||||||
|
|
||||||
|
# 需要 secrets 时,改用 inject / run
|
||||||
|
secrets inject -n refining --kind service --name gitea
|
||||||
|
secrets run -n refining --kind service --name gitea -- printenv
|
||||||
```
|
```
|
||||||
|
|
||||||
`-f secret.*` 会自动解锁 secrets,无需额外加 `--show-secrets`。
|
`search` 只负责发现、定位和读取 metadata,不直接展示 secrets。
|
||||||
|
|
||||||
### 输出格式
|
### 输出格式
|
||||||
|
|
||||||
| 场景 | 推荐命令 |
|
| 场景 | 推荐命令 |
|
||||||
|------|----------|
|
|------|----------|
|
||||||
| AI 解析 / 管道处理 | `-o json` 或 `-o json-compact` |
|
| AI 解析 / 管道处理 | `-o json` 或 `-o json-compact` |
|
||||||
| 写入 `.env` 文件 | `-o env --show-secrets` |
|
| 写入 metadata `.env` 文件 | `-o env` |
|
||||||
|
| 注入 secrets 到环境变量 | `inject` / `run` |
|
||||||
| 人类查看 | 默认 `text`(TTY 下自动启用) |
|
| 人类查看 | 默认 `text`(TTY 下自动启用) |
|
||||||
| 非 TTY(管道/重定向) | 自动 `json-compact` |
|
| 非 TTY(管道/重定向) | 自动 `json-compact` |
|
||||||
|
|
||||||
|
说明:`text` 输出中的时间会按当前机器本地时区显示;`json/json-compact` 继续使用 UTC(RFC3339 风格)以便脚本和 AI 稳定解析。
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 管道直接 jq 解析(非 TTY 自动 json-compact)
|
# 管道直接 jq 解析(非 TTY 自动 json-compact)
|
||||||
secrets search -n refining --kind service | jq '.[].name'
|
secrets search -n refining --kind service | jq '.[].name'
|
||||||
secrets search -n refining --kind service --name gitea --show-secrets | jq '.secrets.token'
|
|
||||||
|
|
||||||
# 导出为可 source 的 env 文件(单条记录)
|
# 导出 metadata 为可 source 的 env 文件(单条记录)
|
||||||
secrets search -n refining --kind service --name gitea -o env --show-secrets \
|
secrets search -n refining --kind service --name gitea -o env \
|
||||||
> ~/.config/gitea/config.env
|
> ~/.config/gitea/config.env
|
||||||
|
|
||||||
|
# 需要 secrets 时,使用 inject / run
|
||||||
|
secrets inject -n refining --kind service --name gitea > ~/.config/gitea/secrets.env
|
||||||
|
secrets run -n refining --kind service --name gitea -- ./deploy.sh
|
||||||
```
|
```
|
||||||
|
|
||||||
## 完整命令参考
|
## 完整命令参考
|
||||||
@@ -80,11 +101,13 @@ secrets search -n refining --kind service --name gitea -o env --show-secrets \
|
|||||||
```bash
|
```bash
|
||||||
# 查看帮助(包含各子命令 EXAMPLES)
|
# 查看帮助(包含各子命令 EXAMPLES)
|
||||||
secrets --help
|
secrets --help
|
||||||
|
secrets init --help # 主密钥初始化
|
||||||
secrets search --help
|
secrets search --help
|
||||||
secrets add --help
|
secrets add --help
|
||||||
secrets update --help
|
secrets update --help
|
||||||
secrets delete --help
|
secrets delete --help
|
||||||
secrets config --help
|
secrets config --help
|
||||||
|
secrets upgrade --help # 检查并更新 CLI 版本
|
||||||
|
|
||||||
# ── search ──────────────────────────────────────────────────────────────────
|
# ── search ──────────────────────────────────────────────────────────────────
|
||||||
secrets search --summary --limit 20 # 发现概览
|
secrets search --summary --limit 20 # 发现概览
|
||||||
@@ -92,8 +115,8 @@ secrets search -n refining --kind service # 按 namespace + kin
|
|||||||
secrets search -n refining --kind service --name gitea # 精确查找
|
secrets search -n refining --kind service --name gitea # 精确查找
|
||||||
secrets search -q mqtt # 关键词模糊搜索
|
secrets search -q mqtt # 关键词模糊搜索
|
||||||
secrets search --tag hongkong # 按 tag 过滤
|
secrets search --tag hongkong # 按 tag 过滤
|
||||||
secrets search -n refining --kind service --name gitea -f secret.token # 提取字段
|
secrets search -n refining --kind service --name gitea -f metadata.url # 提取 metadata 字段
|
||||||
secrets search -n refining --kind service --name gitea -o json --show-secrets # 完整 JSON
|
secrets search -n refining --kind service --name gitea -o json # 完整记录(secrets 保持占位)
|
||||||
secrets search --sort updated --limit 10 --summary # 最近改动
|
secrets search --sort updated --limit 10 --summary # 最近改动
|
||||||
secrets search -n refining --summary --limit 10 --offset 10 # 翻页
|
secrets search -n refining --summary --limit 10 --offset 10 # 翻页
|
||||||
|
|
||||||
@@ -116,11 +139,18 @@ secrets update -n refining --kind service --name mqtt --remove-meta old_port --r
|
|||||||
# ── delete ───────────────────────────────────────────────────────────────────
|
# ── delete ───────────────────────────────────────────────────────────────────
|
||||||
secrets delete -n refining --kind service --name legacy-mqtt
|
secrets delete -n refining --kind service --name legacy-mqtt
|
||||||
|
|
||||||
|
# ── init ─────────────────────────────────────────────────────────────────────
|
||||||
|
secrets init # 主密钥初始化(每台设备一次,主密码至少 8 位,派生后存钥匙串)
|
||||||
|
|
||||||
# ── config ───────────────────────────────────────────────────────────────────
|
# ── config ───────────────────────────────────────────────────────────────────
|
||||||
secrets config set-db "postgres://postgres:<password>@<host>:<port>/secrets"
|
secrets config set-db "postgres://postgres:<password>@<host>:<port>/secrets" # 先验证再写入
|
||||||
secrets config show # 密码脱敏展示
|
secrets config show # 密码脱敏展示
|
||||||
secrets config path # 打印配置文件路径
|
secrets config path # 打印配置文件路径
|
||||||
|
|
||||||
|
# ── upgrade ──────────────────────────────────────────────────────────────────
|
||||||
|
secrets upgrade --check # 仅检查是否有新版本
|
||||||
|
secrets upgrade # 下载、校验 SHA-256 并安装最新版(从 Gitea Release)
|
||||||
|
|
||||||
# ── 调试 ──────────────────────────────────────────────────────────────────────
|
# ── 调试 ──────────────────────────────────────────────────────────────────────
|
||||||
secrets --verbose search -q mqtt
|
secrets --verbose search -q mqtt
|
||||||
RUST_LOG=secrets=trace secrets search
|
RUST_LOG=secrets=trace secrets search
|
||||||
@@ -137,9 +167,9 @@ RUST_LOG=secrets=trace secrets search
|
|||||||
| `name` | 人类可读唯一标识 |
|
| `name` | 人类可读唯一标识 |
|
||||||
| `tags` | 多维标签,如 `["aliyun","hongkong"]` |
|
| `tags` | 多维标签,如 `["aliyun","hongkong"]` |
|
||||||
| `metadata` | 明文描述信息(ip、desc、domains 等) |
|
| `metadata` | 明文描述信息(ip、desc、domains 等) |
|
||||||
| `encrypted` | 敏感凭据(ssh_key、password、token 等),MVP 阶段明文存储,预留加密字段 |
|
| `encrypted` | 敏感凭据(ssh_key、password、token 等),AES-256-GCM 加密存储 |
|
||||||
|
|
||||||
`-m` / `--meta` 写入 `metadata`,`-s` / `--secret` 写入 `encrypted`,`value=@file` 从文件读取内容。
|
`-m` / `--meta` 写入 `metadata`,`-s` / `--secret` 写入 `encrypted`,`value=@file` 从文件读取内容。加解密使用主密钥(由 `secrets init` 设置)。
|
||||||
|
|
||||||
## 审计日志
|
## 审计日志
|
||||||
|
|
||||||
@@ -160,22 +190,25 @@ src/
|
|||||||
main.rs # CLI 入口(clap),含各子命令 after_help 示例
|
main.rs # CLI 入口(clap),含各子命令 after_help 示例
|
||||||
output.rs # OutputMode 枚举 + TTY 检测
|
output.rs # OutputMode 枚举 + TTY 检测
|
||||||
config.rs # 配置读写(~/.config/secrets/config.toml)
|
config.rs # 配置读写(~/.config/secrets/config.toml)
|
||||||
db.rs # 连接池 + auto-migrate(secrets + audit_log)
|
db.rs # 连接池 + auto-migrate(secrets + audit_log + kv_config)
|
||||||
|
crypto.rs # AES-256-GCM 加解密、Argon2id 派生、OS 钥匙串
|
||||||
models.rs # Secret 结构体
|
models.rs # Secret 结构体
|
||||||
audit.rs # 审计日志写入(audit_log 表)
|
audit.rs # 审计日志写入(audit_log 表)
|
||||||
commands/
|
commands/
|
||||||
|
init.rs # 主密钥初始化(首次/新设备)
|
||||||
add.rs # upsert,支持 -o json
|
add.rs # upsert,支持 -o json
|
||||||
config.rs # config set-db/show/path
|
config.rs # config set-db/show/path
|
||||||
search.rs # 多条件查询,支持 -f/-o/--summary/--limit/--offset/--sort
|
search.rs # 多条件查询,支持 -f/-o/--summary/--limit/--offset/--sort
|
||||||
delete.rs # 删除
|
delete.rs # 删除
|
||||||
update.rs # 增量更新(合并 tags/metadata/encrypted)
|
update.rs # 增量更新(合并 tags/metadata/encrypted)
|
||||||
|
upgrade.rs # 从 Gitea Release 自更新
|
||||||
scripts/
|
scripts/
|
||||||
seed-data.sh # 导入 refining / ricnsmart 全量数据
|
setup-gitea-actions.sh # 配置 Gitea Actions 变量与 Secrets
|
||||||
```
|
```
|
||||||
|
|
||||||
## CI/CD(Gitea Actions)
|
## CI/CD(Gitea Actions)
|
||||||
|
|
||||||
推送 `main` 分支时自动:fmt/clippy 检查 → musl 构建 → 创建 Release 并上传二进制。
|
推送 `main` 分支时自动:fmt/clippy/test 检查 → Linux/macOS/Windows 构建 → 上传二进制与 `.sha256` 摘要 → 所有平台成功后发布 Release。
|
||||||
|
|
||||||
**首次使用需配置 Actions 变量和 Secrets:**
|
**首次使用需配置 Actions 变量和 Secrets:**
|
||||||
|
|
||||||
@@ -186,5 +219,12 @@ scripts/
|
|||||||
|
|
||||||
- `RELEASE_TOKEN`(Secret):Gitea PAT,用于创建 Release 上传二进制
|
- `RELEASE_TOKEN`(Secret):Gitea PAT,用于创建 Release 上传二进制
|
||||||
- `WEBHOOK_URL`(Variable):飞书通知,可选
|
- `WEBHOOK_URL`(Variable):飞书通知,可选
|
||||||
|
- **注意**:Secret/Variable 的 `data`/`value` 字段需传入原始值,不要 base64 编码
|
||||||
|
|
||||||
|
当前 Release 预编译产物覆盖:
|
||||||
|
- Linux `x86_64-unknown-linux-musl`
|
||||||
|
- macOS Apple Silicon `aarch64-apple-darwin`
|
||||||
|
- macOS Intel `x86_64-apple-darwin`(由 ARM mac runner 交叉编译)
|
||||||
|
- Windows `x86_64-pc-windows-msvc`
|
||||||
|
|
||||||
详见 [AGENTS.md](AGENTS.md)。
|
详见 [AGENTS.md](AGENTS.md)。
|
||||||
|
|||||||
23
scripts/release-check.sh
Executable file
23
scripts/release-check.sh
Executable file
@@ -0,0 +1,23 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
cd "$repo_root"
|
||||||
|
|
||||||
|
version="$(grep -m1 '^version' Cargo.toml | sed 's/.*"\(.*\)".*/\1/')"
|
||||||
|
tag="secrets-${version}"
|
||||||
|
|
||||||
|
echo "==> 当前版本: ${version}"
|
||||||
|
echo "==> 检查是否已存在 tag: ${tag}"
|
||||||
|
|
||||||
|
if git rev-parse "refs/tags/${tag}" >/dev/null 2>&1; then
|
||||||
|
echo "错误: 已存在 tag ${tag}"
|
||||||
|
echo "请先 bump Cargo.toml 中的 version,再执行 cargo build 同步 Cargo.lock。"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "==> 未发现重复 tag,开始执行检查"
|
||||||
|
cargo fmt -- --check
|
||||||
|
cargo clippy --locked -- -D warnings
|
||||||
|
cargo test --locked
|
||||||
@@ -7,7 +7,9 @@
|
|||||||
# - secrets.RELEASE_TOKEN (必选) Release 上传用,值为 Gitea PAT
|
# - secrets.RELEASE_TOKEN (必选) Release 上传用,值为 Gitea PAT
|
||||||
# - vars.WEBHOOK_URL (可选) 飞书通知
|
# - vars.WEBHOOK_URL (可选) 飞书通知
|
||||||
#
|
#
|
||||||
# 注意: Gitea 不允许 secret/variable 名以 GITEA_ 或 GITHUB_ 开头,故使用 RELEASE_TOKEN
|
# 注意:
|
||||||
|
# - Gitea 不允许 secret/variable 名以 GITEA_ 或 GITHUB_ 开头,故使用 RELEASE_TOKEN
|
||||||
|
# - Secret/Variable 的 data/value 字段需传入原始值,不要使用 base64 编码
|
||||||
#
|
#
|
||||||
# 用法:
|
# 用法:
|
||||||
# 1. 从 ~/.config/gitea/config.env 读取 GITEA_URL, GITEA_TOKEN, GITEA_WEBHOOK_URL
|
# 1. 从 ~/.config/gitea/config.env 读取 GITEA_URL, GITEA_TOKEN, GITEA_WEBHOOK_URL
|
||||||
@@ -108,11 +110,13 @@ echo "━━━━━━━━━━━━━━━━━━━━━━━━
|
|||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
# 1. 创建 Secret: RELEASE_TOKEN
|
# 1. 创建 Secret: RELEASE_TOKEN
|
||||||
|
# 注意: Gitea Actions API 的 data 字段需传入原始值,不要使用 base64 编码
|
||||||
echo "1. 创建 Secret: RELEASE_TOKEN"
|
echo "1. 创建 Secret: RELEASE_TOKEN"
|
||||||
|
secret_payload=$(jq -n --arg t "$GITEA_TOKEN" '{data: $t}')
|
||||||
resp=$(curl -s -w "\n%{http_code}" -X PUT \
|
resp=$(curl -s -w "\n%{http_code}" -X PUT \
|
||||||
-H "Authorization: token $GITEA_TOKEN" \
|
-H "Authorization: token $GITEA_TOKEN" \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-d "{\"data\":\"${GITEA_TOKEN}\"}" \
|
-d "$secret_payload" \
|
||||||
"${API_BASE}/repos/${OWNER}/${REPO}/actions/secrets/RELEASE_TOKEN")
|
"${API_BASE}/repos/${OWNER}/${REPO}/actions/secrets/RELEASE_TOKEN")
|
||||||
http_code=$(echo "$resp" | tail -n1)
|
http_code=$(echo "$resp" | tail -n1)
|
||||||
body=$(echo "$resp" | sed '$d')
|
body=$(echo "$resp" | sed '$d')
|
||||||
@@ -126,14 +130,16 @@ else
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
# 2. 创建/更新 Variable: WEBHOOK_URL(可选)
|
# 2. 创建/更新 Variable: WEBHOOK_URL(可选)
|
||||||
|
# 注意: Secret 和 Variable 均使用原始值,不要 base64 编码
|
||||||
WEBHOOK_VALUE="${WEBHOOK_URL:-$GITEA_WEBHOOK_URL}"
|
WEBHOOK_VALUE="${WEBHOOK_URL:-$GITEA_WEBHOOK_URL}"
|
||||||
if [[ -n "$WEBHOOK_VALUE" ]]; then
|
if [[ -n "$WEBHOOK_VALUE" ]]; then
|
||||||
echo ""
|
echo ""
|
||||||
echo "2. 创建/更新 Variable: WEBHOOK_URL"
|
echo "2. 创建/更新 Variable: WEBHOOK_URL"
|
||||||
|
var_payload=$(jq -n --arg v "$WEBHOOK_VALUE" '{value: $v}')
|
||||||
resp=$(curl -s -w "\n%{http_code}" -X POST \
|
resp=$(curl -s -w "\n%{http_code}" -X POST \
|
||||||
-H "Authorization: token $GITEA_TOKEN" \
|
-H "Authorization: token $GITEA_TOKEN" \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-d "{\"value\":\"${WEBHOOK_VALUE}\"}" \
|
-d "$var_payload" \
|
||||||
"${API_BASE}/repos/${OWNER}/${REPO}/actions/variables/WEBHOOK_URL")
|
"${API_BASE}/repos/${OWNER}/${REPO}/actions/variables/WEBHOOK_URL")
|
||||||
http_code=$(echo "$resp" | tail -n1)
|
http_code=$(echo "$resp" | tail -n1)
|
||||||
body=$(echo "$resp" | sed '$d')
|
body=$(echo "$resp" | sed '$d')
|
||||||
@@ -145,7 +151,7 @@ if [[ -n "$WEBHOOK_VALUE" ]]; then
|
|||||||
resp=$(curl -s -w "\n%{http_code}" -X PUT \
|
resp=$(curl -s -w "\n%{http_code}" -X PUT \
|
||||||
-H "Authorization: token $GITEA_TOKEN" \
|
-H "Authorization: token $GITEA_TOKEN" \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-d "{\"value\":\"${WEBHOOK_VALUE}\"}" \
|
-d "$var_payload" \
|
||||||
"${API_BASE}/repos/${OWNER}/${REPO}/actions/variables/WEBHOOK_URL")
|
"${API_BASE}/repos/${OWNER}/${REPO}/actions/variables/WEBHOOK_URL")
|
||||||
http_code=$(echo "$resp" | tail -n1)
|
http_code=$(echo "$resp" | tail -n1)
|
||||||
if [[ "$http_code" == "200" || "$http_code" == "204" ]]; then
|
if [[ "$http_code" == "200" || "$http_code" == "204" ]]; then
|
||||||
|
|||||||
12
src/audit.rs
12
src/audit.rs
@@ -1,11 +1,9 @@
|
|||||||
use anyhow::Result;
|
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use sqlx::PgPool;
|
use sqlx::{Postgres, Transaction};
|
||||||
|
|
||||||
/// Write an audit entry for a write operation. Failures are logged as warnings
|
/// Write an audit entry within an existing transaction.
|
||||||
/// and do not interrupt the main flow.
|
pub async fn log_tx(
|
||||||
pub async fn log(
|
tx: &mut Transaction<'_, Postgres>,
|
||||||
pool: &PgPool,
|
|
||||||
action: &str,
|
action: &str,
|
||||||
namespace: &str,
|
namespace: &str,
|
||||||
kind: &str,
|
kind: &str,
|
||||||
@@ -23,7 +21,7 @@ pub async fn log(
|
|||||||
.bind(name)
|
.bind(name)
|
||||||
.bind(&detail)
|
.bind(&detail)
|
||||||
.bind(&actor)
|
.bind(&actor)
|
||||||
.execute(pool)
|
.execute(&mut **tx)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
if let Err(e) = result {
|
if let Err(e) = result {
|
||||||
|
|||||||
@@ -4,13 +4,30 @@ use sqlx::PgPool;
|
|||||||
use std::fs;
|
use std::fs;
|
||||||
|
|
||||||
use crate::crypto;
|
use crate::crypto;
|
||||||
|
use crate::db;
|
||||||
use crate::output::OutputMode;
|
use crate::output::OutputMode;
|
||||||
|
|
||||||
/// Parse "key=value" entries. Value starting with '@' reads from file.
|
/// Parse "key=value" or "key:=<json>" entries.
|
||||||
pub(crate) fn parse_kv(entry: &str) -> Result<(String, String)> {
|
/// - `key=value` → stores the literal string `value`
|
||||||
|
/// - `key:=<json>` → parses `<json>` as a typed JSON value (number, bool, null, array, object)
|
||||||
|
/// - `value=@file` → reads the file content as a string (only for `=` form)
|
||||||
|
pub(crate) fn parse_kv(entry: &str) -> Result<(String, Value)> {
|
||||||
|
// Typed JSON form: key:=<json>
|
||||||
|
if let Some((key, json_str)) = entry.split_once(":=") {
|
||||||
|
let val: Value = serde_json::from_str(json_str).map_err(|e| {
|
||||||
|
anyhow::anyhow!(
|
||||||
|
"Invalid JSON value for key '{}': {} (use key=value for plain strings)",
|
||||||
|
key,
|
||||||
|
e
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
return Ok((key.to_string(), val));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Plain string form: key=value or key=@file
|
||||||
let (key, raw_val) = entry.split_once('=').ok_or_else(|| {
|
let (key, raw_val) = entry.split_once('=').ok_or_else(|| {
|
||||||
anyhow::anyhow!(
|
anyhow::anyhow!(
|
||||||
"Invalid format '{}'. Expected: key=value or key=@file",
|
"Invalid format '{}'. Expected: key=value, key=@file, or key:=<json>",
|
||||||
entry
|
entry
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
@@ -22,14 +39,14 @@ pub(crate) fn parse_kv(entry: &str) -> Result<(String, String)> {
|
|||||||
raw_val.to_string()
|
raw_val.to_string()
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok((key.to_string(), value))
|
Ok((key.to_string(), Value::String(value)))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn build_json(entries: &[String]) -> Result<Value> {
|
pub(crate) fn build_json(entries: &[String]) -> Result<Value> {
|
||||||
let mut map = Map::new();
|
let mut map = Map::new();
|
||||||
for entry in entries {
|
for entry in entries {
|
||||||
let (key, value) = parse_kv(entry)?;
|
let (key, value) = parse_kv(entry)?;
|
||||||
map.insert(key, Value::String(value));
|
map.insert(key, value);
|
||||||
}
|
}
|
||||||
Ok(Value::Object(map))
|
Ok(Value::Object(map))
|
||||||
}
|
}
|
||||||
@@ -47,21 +64,72 @@ pub struct AddArgs<'a> {
|
|||||||
pub async fn run(pool: &PgPool, args: AddArgs<'_>, master_key: &[u8; 32]) -> Result<()> {
|
pub async fn run(pool: &PgPool, args: AddArgs<'_>, master_key: &[u8; 32]) -> Result<()> {
|
||||||
let metadata = build_json(args.meta_entries)?;
|
let metadata = build_json(args.meta_entries)?;
|
||||||
let secret_json = build_json(args.secret_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)?;
|
let encrypted_bytes = crypto::encrypt_json(master_key, &secret_json)?;
|
||||||
|
|
||||||
tracing::debug!(args.namespace, args.kind, args.name, "upserting record");
|
tracing::debug!(args.namespace, args.kind, args.name, "upserting record");
|
||||||
|
|
||||||
|
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();
|
||||||
|
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
|
||||||
|
// Snapshot existing row into history before overwriting (if it exists).
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct ExistingRow {
|
||||||
|
id: uuid::Uuid,
|
||||||
|
version: i64,
|
||||||
|
tags: Vec<String>,
|
||||||
|
metadata: serde_json::Value,
|
||||||
|
encrypted: Vec<u8>,
|
||||||
|
}
|
||||||
|
let existing: Option<ExistingRow> = sqlx::query_as(
|
||||||
|
"SELECT id, version, 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(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if let Some(ex) = existing
|
||||||
|
&& let Err(e) = db::snapshot_history(
|
||||||
|
&mut tx,
|
||||||
|
db::SnapshotParams {
|
||||||
|
secret_id: ex.id,
|
||||||
|
namespace: args.namespace,
|
||||||
|
kind: args.kind,
|
||||||
|
name: args.name,
|
||||||
|
version: ex.version,
|
||||||
|
action: "add",
|
||||||
|
tags: &ex.tags,
|
||||||
|
metadata: &ex.metadata,
|
||||||
|
encrypted: &ex.encrypted,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
tracing::warn!(error = %e, "failed to snapshot history before upsert");
|
||||||
|
}
|
||||||
|
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
r#"
|
r#"
|
||||||
INSERT INTO secrets (namespace, kind, name, tags, metadata, encrypted, updated_at)
|
INSERT INTO secrets (namespace, kind, name, tags, metadata, encrypted, version, updated_at)
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, NOW())
|
VALUES ($1, $2, $3, $4, $5, $6, 1, NOW())
|
||||||
ON CONFLICT (namespace, kind, name)
|
ON CONFLICT (namespace, kind, name)
|
||||||
DO UPDATE SET
|
DO UPDATE SET
|
||||||
tags = EXCLUDED.tags,
|
tags = EXCLUDED.tags,
|
||||||
metadata = EXCLUDED.metadata,
|
metadata = EXCLUDED.metadata,
|
||||||
encrypted = EXCLUDED.encrypted,
|
encrypted = EXCLUDED.encrypted,
|
||||||
|
version = secrets.version + 1,
|
||||||
updated_at = NOW()
|
updated_at = NOW()
|
||||||
"#,
|
"#,
|
||||||
)
|
)
|
||||||
@@ -71,22 +139,11 @@ pub async fn run(pool: &PgPool, args: AddArgs<'_>, master_key: &[u8; 32]) -> Res
|
|||||||
.bind(args.tags)
|
.bind(args.tags)
|
||||||
.bind(&metadata)
|
.bind(&metadata)
|
||||||
.bind(&encrypted_bytes)
|
.bind(&encrypted_bytes)
|
||||||
.execute(pool)
|
.execute(&mut *tx)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let meta_keys: Vec<&str> = args
|
crate::audit::log_tx(
|
||||||
.meta_entries
|
&mut tx,
|
||||||
.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",
|
"add",
|
||||||
args.namespace,
|
args.namespace,
|
||||||
args.kind,
|
args.kind,
|
||||||
@@ -99,6 +156,8 @@ pub async fn run(pool: &PgPool, args: AddArgs<'_>, master_key: &[u8; 32]) -> Res
|
|||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
|
tx.commit().await?;
|
||||||
|
|
||||||
let result_json = json!({
|
let result_json = json!({
|
||||||
"action": "added",
|
"action": "added",
|
||||||
"namespace": args.namespace,
|
"namespace": args.namespace,
|
||||||
|
|||||||
@@ -1,43 +1,44 @@
|
|||||||
use crate::config::{self, Config, config_path};
|
use crate::config::{self, Config, config_path};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
|
||||||
pub enum ConfigAction {
|
pub async fn run(action: crate::ConfigAction) -> Result<()> {
|
||||||
SetDb { url: String },
|
|
||||||
Show,
|
|
||||||
Path,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn run(action: ConfigAction) -> Result<()> {
|
|
||||||
match action {
|
match action {
|
||||||
ConfigAction::SetDb { url } => {
|
crate::ConfigAction::SetDb { url } => {
|
||||||
|
// Verify connection before writing config
|
||||||
|
let pool = crate::db::create_pool(&url)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("Database connection failed: {}", e))?;
|
||||||
|
drop(pool);
|
||||||
|
println!("Database connection successful.");
|
||||||
|
|
||||||
let cfg = Config {
|
let cfg = Config {
|
||||||
database_url: Some(url.clone()),
|
database_url: Some(url.clone()),
|
||||||
};
|
};
|
||||||
config::save_config(&cfg)?;
|
config::save_config(&cfg)?;
|
||||||
println!("✓ 数据库连接串已保存到: {}", config_path().display());
|
println!("Database URL saved to: {}", config_path().display());
|
||||||
println!(" {}", mask_password(&url));
|
println!(" {}", mask_password(&url));
|
||||||
}
|
}
|
||||||
ConfigAction::Show => {
|
crate::ConfigAction::Show => {
|
||||||
let cfg = config::load_config()?;
|
let cfg = config::load_config()?;
|
||||||
match cfg.database_url {
|
match cfg.database_url {
|
||||||
Some(url) => {
|
Some(url) => {
|
||||||
println!("database_url = {}", mask_password(&url));
|
println!("database_url = {}", mask_password(&url));
|
||||||
println!("配置文件: {}", config_path().display());
|
println!("config file: {}", config_path().display());
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
println!("未配置数据库连接串。");
|
println!("Database URL not configured.");
|
||||||
println!("请运行:secrets config set-db <DATABASE_URL>");
|
println!("Run: secrets config set-db <DATABASE_URL>");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ConfigAction::Path => {
|
crate::ConfigAction::Path => {
|
||||||
println!("{}", config_path().display());
|
println!("{}", config_path().display());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 将 postgres://user:password@host/db 中的密码替换为 ***
|
/// Mask the password in a postgres://user:password@host/db URL.
|
||||||
fn mask_password(url: &str) -> String {
|
fn mask_password(url: &str) -> String {
|
||||||
if let Some(at_pos) = url.rfind('@')
|
if let Some(at_pos) = url.rfind('@')
|
||||||
&& let Some(scheme_end) = url.find("://")
|
&& let Some(scheme_end) = url.find("://")
|
||||||
|
|||||||
@@ -1,24 +1,107 @@
|
|||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use serde_json::json;
|
use serde_json::{Value, json};
|
||||||
use sqlx::PgPool;
|
use sqlx::{FromRow, PgPool};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
pub async fn run(pool: &PgPool, namespace: &str, kind: &str, name: &str) -> Result<()> {
|
use crate::db;
|
||||||
|
use crate::output::OutputMode;
|
||||||
|
|
||||||
|
#[derive(FromRow)]
|
||||||
|
struct DeleteRow {
|
||||||
|
id: Uuid,
|
||||||
|
version: i64,
|
||||||
|
tags: Vec<String>,
|
||||||
|
metadata: Value,
|
||||||
|
encrypted: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn run(
|
||||||
|
pool: &PgPool,
|
||||||
|
namespace: &str,
|
||||||
|
kind: &str,
|
||||||
|
name: &str,
|
||||||
|
output: OutputMode,
|
||||||
|
) -> Result<()> {
|
||||||
tracing::debug!(namespace, kind, name, "deleting record");
|
tracing::debug!(namespace, kind, name, "deleting record");
|
||||||
|
|
||||||
let result =
|
let mut tx = pool.begin().await?;
|
||||||
sqlx::query("DELETE FROM secrets WHERE namespace = $1 AND kind = $2 AND name = $3")
|
|
||||||
|
let row: Option<DeleteRow> = sqlx::query_as(
|
||||||
|
"SELECT id, version, tags, metadata, encrypted FROM secrets \
|
||||||
|
WHERE namespace = $1 AND kind = $2 AND name = $3 \
|
||||||
|
FOR UPDATE",
|
||||||
|
)
|
||||||
.bind(namespace)
|
.bind(namespace)
|
||||||
.bind(kind)
|
.bind(kind)
|
||||||
.bind(name)
|
.bind(name)
|
||||||
.execute(pool)
|
.fetch_optional(&mut *tx)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if result.rows_affected() == 0 {
|
let Some(row) = row else {
|
||||||
|
tx.rollback().await?;
|
||||||
tracing::warn!(namespace, kind, name, "record not found for deletion");
|
tracing::warn!(namespace, kind, name, "record not found for deletion");
|
||||||
println!("Not found: [{}/{}] {}", namespace, kind, name);
|
match output {
|
||||||
} else {
|
OutputMode::Json => println!(
|
||||||
crate::audit::log(pool, "delete", namespace, kind, name, json!({})).await;
|
"{}",
|
||||||
println!("Deleted: [{}/{}] {}", namespace, kind, name);
|
serde_json::to_string_pretty(
|
||||||
|
&json!({"action":"not_found","namespace":namespace,"kind":kind,"name":name})
|
||||||
|
)?
|
||||||
|
),
|
||||||
|
OutputMode::JsonCompact => println!(
|
||||||
|
"{}",
|
||||||
|
serde_json::to_string(
|
||||||
|
&json!({"action":"not_found","namespace":namespace,"kind":kind,"name":name})
|
||||||
|
)?
|
||||||
|
),
|
||||||
|
_ => println!("Not found: [{}/{}] {}", namespace, kind, name),
|
||||||
}
|
}
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
|
||||||
|
// Snapshot before physical delete so the row can be restored via rollback.
|
||||||
|
if let Err(e) = db::snapshot_history(
|
||||||
|
&mut tx,
|
||||||
|
db::SnapshotParams {
|
||||||
|
secret_id: row.id,
|
||||||
|
namespace,
|
||||||
|
kind,
|
||||||
|
name,
|
||||||
|
version: row.version,
|
||||||
|
action: "delete",
|
||||||
|
tags: &row.tags,
|
||||||
|
metadata: &row.metadata,
|
||||||
|
encrypted: &row.encrypted,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
tracing::warn!(error = %e, "failed to snapshot history before delete");
|
||||||
|
}
|
||||||
|
|
||||||
|
sqlx::query("DELETE FROM secrets WHERE id = $1")
|
||||||
|
.bind(row.id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
crate::audit::log_tx(&mut tx, "delete", namespace, kind, name, json!({})).await;
|
||||||
|
|
||||||
|
tx.commit().await?;
|
||||||
|
|
||||||
|
match output {
|
||||||
|
OutputMode::Json => println!(
|
||||||
|
"{}",
|
||||||
|
serde_json::to_string_pretty(
|
||||||
|
&json!({"action":"deleted","namespace":namespace,"kind":kind,"name":name})
|
||||||
|
)?
|
||||||
|
),
|
||||||
|
OutputMode::JsonCompact => println!(
|
||||||
|
"{}",
|
||||||
|
serde_json::to_string(
|
||||||
|
&json!({"action":"deleted","namespace":namespace,"kind":kind,"name":name})
|
||||||
|
)?
|
||||||
|
),
|
||||||
|
_ => println!("Deleted: [{}/{}] {}", namespace, kind, name),
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,15 +4,23 @@ use sqlx::PgPool;
|
|||||||
|
|
||||||
use crate::{crypto, db};
|
use crate::{crypto, db};
|
||||||
|
|
||||||
|
const MIN_MASTER_PASSWORD_LEN: usize = 8;
|
||||||
|
|
||||||
pub async fn run(pool: &PgPool) -> Result<()> {
|
pub async fn run(pool: &PgPool) -> Result<()> {
|
||||||
println!("Initializing secrets master key...");
|
println!("Initializing secrets master key...");
|
||||||
println!();
|
println!();
|
||||||
|
|
||||||
// Read password (no echo)
|
// Read password (no echo)
|
||||||
let password =
|
let password = rpassword::prompt_password(format!(
|
||||||
rpassword::prompt_password("Enter master password: ").context("failed to read password")?;
|
"Enter master password (at least {} characters): ",
|
||||||
if password.is_empty() {
|
MIN_MASTER_PASSWORD_LEN
|
||||||
anyhow::bail!("Master password must not be empty.");
|
))
|
||||||
|
.context("failed to read password")?;
|
||||||
|
if password.chars().count() < MIN_MASTER_PASSWORD_LEN {
|
||||||
|
anyhow::bail!(
|
||||||
|
"Master password must be at least {} characters.",
|
||||||
|
MIN_MASTER_PASSWORD_LEN
|
||||||
|
);
|
||||||
}
|
}
|
||||||
let confirm = rpassword::prompt_password("Confirm master password: ")
|
let confirm = rpassword::prompt_password("Confirm master password: ")
|
||||||
.context("failed to read password confirmation")?;
|
.context("failed to read password confirmation")?;
|
||||||
|
|||||||
@@ -1,85 +0,0 @@
|
|||||||
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(())
|
|
||||||
}
|
|
||||||
@@ -2,6 +2,8 @@ pub mod add;
|
|||||||
pub mod config;
|
pub mod config;
|
||||||
pub mod delete;
|
pub mod delete;
|
||||||
pub mod init;
|
pub mod init;
|
||||||
pub mod migrate_encrypt;
|
pub mod rollback;
|
||||||
|
pub mod run;
|
||||||
pub mod search;
|
pub mod search;
|
||||||
pub mod update;
|
pub mod update;
|
||||||
|
pub mod upgrade;
|
||||||
|
|||||||
239
src/commands/rollback.rs
Normal file
239
src/commands/rollback.rs
Normal file
@@ -0,0 +1,239 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use sqlx::{FromRow, PgPool};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::output::{OutputMode, format_local_time};
|
||||||
|
|
||||||
|
#[derive(FromRow)]
|
||||||
|
struct HistoryRow {
|
||||||
|
secret_id: Uuid,
|
||||||
|
version: i64,
|
||||||
|
action: String,
|
||||||
|
tags: Vec<String>,
|
||||||
|
metadata: Value,
|
||||||
|
encrypted: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct RollbackArgs<'a> {
|
||||||
|
pub namespace: &'a str,
|
||||||
|
pub kind: &'a str,
|
||||||
|
pub name: &'a str,
|
||||||
|
/// Target version to restore. None → restore the most recent history entry.
|
||||||
|
pub to_version: Option<i64>,
|
||||||
|
pub output: OutputMode,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn run(pool: &PgPool, args: RollbackArgs<'_>, master_key: &[u8; 32]) -> Result<()> {
|
||||||
|
let snap: Option<HistoryRow> = if let Some(ver) = args.to_version {
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT secret_id, version, action, tags, metadata, encrypted \
|
||||||
|
FROM secrets_history \
|
||||||
|
WHERE namespace = $1 AND kind = $2 AND name = $3 AND version = $4 \
|
||||||
|
ORDER BY id DESC LIMIT 1",
|
||||||
|
)
|
||||||
|
.bind(args.namespace)
|
||||||
|
.bind(args.kind)
|
||||||
|
.bind(args.name)
|
||||||
|
.bind(ver)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?
|
||||||
|
} else {
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT secret_id, version, action, tags, metadata, encrypted \
|
||||||
|
FROM secrets_history \
|
||||||
|
WHERE namespace = $1 AND kind = $2 AND name = $3 \
|
||||||
|
ORDER BY id DESC LIMIT 1",
|
||||||
|
)
|
||||||
|
.bind(args.namespace)
|
||||||
|
.bind(args.kind)
|
||||||
|
.bind(args.name)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?
|
||||||
|
};
|
||||||
|
|
||||||
|
let snap = snap.ok_or_else(|| {
|
||||||
|
anyhow::anyhow!(
|
||||||
|
"No history found for [{}/{}] {}{}.",
|
||||||
|
args.namespace,
|
||||||
|
args.kind,
|
||||||
|
args.name,
|
||||||
|
args.to_version
|
||||||
|
.map(|v| format!(" at version {}", v))
|
||||||
|
.unwrap_or_default()
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
// Validate encrypted blob is non-trivial (re-encrypt guard).
|
||||||
|
if !snap.encrypted.is_empty() {
|
||||||
|
// Probe decrypt to ensure the blob is valid before restoring.
|
||||||
|
crate::crypto::decrypt_json(master_key, &snap.encrypted)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
|
||||||
|
// Snapshot current live row (if it exists) before overwriting.
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct LiveRow {
|
||||||
|
id: Uuid,
|
||||||
|
version: i64,
|
||||||
|
tags: Vec<String>,
|
||||||
|
metadata: Value,
|
||||||
|
encrypted: Vec<u8>,
|
||||||
|
}
|
||||||
|
let live: Option<LiveRow> = sqlx::query_as(
|
||||||
|
"SELECT id, version, tags, metadata, encrypted FROM secrets \
|
||||||
|
WHERE namespace = $1 AND kind = $2 AND name = $3 FOR UPDATE",
|
||||||
|
)
|
||||||
|
.bind(args.namespace)
|
||||||
|
.bind(args.kind)
|
||||||
|
.bind(args.name)
|
||||||
|
.fetch_optional(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if let Some(lr) = live
|
||||||
|
&& let Err(e) = crate::db::snapshot_history(
|
||||||
|
&mut tx,
|
||||||
|
crate::db::SnapshotParams {
|
||||||
|
secret_id: lr.id,
|
||||||
|
namespace: args.namespace,
|
||||||
|
kind: args.kind,
|
||||||
|
name: args.name,
|
||||||
|
version: lr.version,
|
||||||
|
action: "rollback",
|
||||||
|
tags: &lr.tags,
|
||||||
|
metadata: &lr.metadata,
|
||||||
|
encrypted: &lr.encrypted,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
tracing::warn!(error = %e, "failed to snapshot current row before rollback");
|
||||||
|
}
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO secrets (id, namespace, kind, name, tags, metadata, encrypted, version, updated_at) \
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NOW()) \
|
||||||
|
ON CONFLICT (namespace, kind, name) DO UPDATE SET \
|
||||||
|
tags = EXCLUDED.tags, \
|
||||||
|
metadata = EXCLUDED.metadata, \
|
||||||
|
encrypted = EXCLUDED.encrypted, \
|
||||||
|
version = secrets.version + 1, \
|
||||||
|
updated_at = NOW()",
|
||||||
|
)
|
||||||
|
.bind(snap.secret_id)
|
||||||
|
.bind(args.namespace)
|
||||||
|
.bind(args.kind)
|
||||||
|
.bind(args.name)
|
||||||
|
.bind(&snap.tags)
|
||||||
|
.bind(&snap.metadata)
|
||||||
|
.bind(&snap.encrypted)
|
||||||
|
.bind(snap.version)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
crate::audit::log_tx(
|
||||||
|
&mut tx,
|
||||||
|
"rollback",
|
||||||
|
args.namespace,
|
||||||
|
args.kind,
|
||||||
|
args.name,
|
||||||
|
json!({
|
||||||
|
"restored_version": snap.version,
|
||||||
|
"original_action": snap.action,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
tx.commit().await?;
|
||||||
|
|
||||||
|
let result_json = json!({
|
||||||
|
"action": "rolled_back",
|
||||||
|
"namespace": args.namespace,
|
||||||
|
"kind": args.kind,
|
||||||
|
"name": args.name,
|
||||||
|
"restored_version": snap.version,
|
||||||
|
});
|
||||||
|
|
||||||
|
match args.output {
|
||||||
|
OutputMode::Json => println!("{}", serde_json::to_string_pretty(&result_json)?),
|
||||||
|
OutputMode::JsonCompact => println!("{}", serde_json::to_string(&result_json)?),
|
||||||
|
_ => println!(
|
||||||
|
"Rolled back: [{}/{}] {} → version {}",
|
||||||
|
args.namespace, args.kind, args.name, snap.version
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// List history entries for a record.
|
||||||
|
pub async fn list_history(
|
||||||
|
pool: &PgPool,
|
||||||
|
namespace: &str,
|
||||||
|
kind: &str,
|
||||||
|
name: &str,
|
||||||
|
limit: u32,
|
||||||
|
output: OutputMode,
|
||||||
|
) -> Result<()> {
|
||||||
|
#[derive(FromRow)]
|
||||||
|
struct HistorySummary {
|
||||||
|
version: i64,
|
||||||
|
action: String,
|
||||||
|
actor: String,
|
||||||
|
created_at: chrono::DateTime<chrono::Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
let rows: Vec<HistorySummary> = sqlx::query_as(
|
||||||
|
"SELECT version, action, actor, created_at FROM secrets_history \
|
||||||
|
WHERE namespace = $1 AND kind = $2 AND name = $3 \
|
||||||
|
ORDER BY id DESC LIMIT $4",
|
||||||
|
)
|
||||||
|
.bind(namespace)
|
||||||
|
.bind(kind)
|
||||||
|
.bind(name)
|
||||||
|
.bind(limit as i64)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
match output {
|
||||||
|
OutputMode::Json | OutputMode::JsonCompact => {
|
||||||
|
let arr: Vec<Value> = rows
|
||||||
|
.iter()
|
||||||
|
.map(|r| {
|
||||||
|
json!({
|
||||||
|
"version": r.version,
|
||||||
|
"action": r.action,
|
||||||
|
"actor": r.actor,
|
||||||
|
"created_at": r.created_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let out = if output == OutputMode::Json {
|
||||||
|
serde_json::to_string_pretty(&arr)?
|
||||||
|
} else {
|
||||||
|
serde_json::to_string(&arr)?
|
||||||
|
};
|
||||||
|
println!("{}", out);
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
if rows.is_empty() {
|
||||||
|
println!("No history found for [{}/{}] {}.", namespace, kind, name);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
println!("History for [{}/{}] {}:", namespace, kind, name);
|
||||||
|
for r in &rows {
|
||||||
|
println!(
|
||||||
|
" v{:<4} {:8} {} {}",
|
||||||
|
r.version,
|
||||||
|
r.action,
|
||||||
|
r.actor,
|
||||||
|
format_local_time(r.created_at)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
println!(" (use `secrets rollback --to-version <N>` to restore)");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
143
src/commands/run.rs
Normal file
143
src/commands/run.rs
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
use serde_json::Value;
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use crate::commands::search::build_injected_env_map;
|
||||||
|
use crate::output::OutputMode;
|
||||||
|
|
||||||
|
pub struct InjectArgs<'a> {
|
||||||
|
pub namespace: Option<&'a str>,
|
||||||
|
pub kind: Option<&'a str>,
|
||||||
|
pub name: Option<&'a str>,
|
||||||
|
pub tags: &'a [String],
|
||||||
|
/// Prefix to prepend to every variable name. Empty string means no prefix.
|
||||||
|
pub prefix: &'a str,
|
||||||
|
pub output: OutputMode,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct RunArgs<'a> {
|
||||||
|
pub namespace: Option<&'a str>,
|
||||||
|
pub kind: Option<&'a str>,
|
||||||
|
pub name: Option<&'a str>,
|
||||||
|
pub tags: &'a [String],
|
||||||
|
pub prefix: &'a str,
|
||||||
|
/// The command and its arguments to execute with injected secrets.
|
||||||
|
pub command: &'a [String],
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetch secrets matching the filter and build a flat env map.
|
||||||
|
/// Metadata and secret fields are merged; naming: `<PREFIX_><NAME>_<KEY>` (uppercased).
|
||||||
|
pub async fn collect_env_map(
|
||||||
|
pool: &PgPool,
|
||||||
|
namespace: Option<&str>,
|
||||||
|
kind: Option<&str>,
|
||||||
|
name: Option<&str>,
|
||||||
|
tags: &[String],
|
||||||
|
prefix: &str,
|
||||||
|
master_key: &[u8; 32],
|
||||||
|
) -> Result<HashMap<String, String>> {
|
||||||
|
if namespace.is_none() && kind.is_none() && name.is_none() && tags.is_empty() {
|
||||||
|
anyhow::bail!(
|
||||||
|
"At least one filter (--namespace, --kind, --name, or --tag) is required for inject/run"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let rows = crate::commands::search::fetch_rows(pool, namespace, kind, name, tags, None).await?;
|
||||||
|
if rows.is_empty() {
|
||||||
|
anyhow::bail!("No records matched the given filters.");
|
||||||
|
}
|
||||||
|
let mut map = HashMap::new();
|
||||||
|
for row in &rows {
|
||||||
|
let row_map = build_injected_env_map(row, prefix, master_key)?;
|
||||||
|
for (k, v) in row_map {
|
||||||
|
map.insert(k, v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(map)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `inject` command: print env vars to stdout (suitable for `eval $(...)` or export).
|
||||||
|
pub async fn run_inject(pool: &PgPool, args: InjectArgs<'_>, master_key: &[u8; 32]) -> Result<()> {
|
||||||
|
let env_map = collect_env_map(
|
||||||
|
pool,
|
||||||
|
args.namespace,
|
||||||
|
args.kind,
|
||||||
|
args.name,
|
||||||
|
args.tags,
|
||||||
|
args.prefix,
|
||||||
|
master_key,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
match args.output {
|
||||||
|
OutputMode::Json => {
|
||||||
|
let obj: serde_json::Map<String, Value> = env_map
|
||||||
|
.into_iter()
|
||||||
|
.map(|(k, v)| (k, Value::String(v)))
|
||||||
|
.collect();
|
||||||
|
println!("{}", serde_json::to_string_pretty(&Value::Object(obj))?);
|
||||||
|
}
|
||||||
|
OutputMode::JsonCompact => {
|
||||||
|
let obj: serde_json::Map<String, Value> = env_map
|
||||||
|
.into_iter()
|
||||||
|
.map(|(k, v)| (k, Value::String(v)))
|
||||||
|
.collect();
|
||||||
|
println!("{}", serde_json::to_string(&Value::Object(obj))?);
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
// Shell-safe KEY=VALUE output, one per line.
|
||||||
|
let mut pairs: Vec<(String, String)> = env_map.into_iter().collect();
|
||||||
|
pairs.sort_by(|a, b| a.0.cmp(&b.0));
|
||||||
|
for (k, v) in pairs {
|
||||||
|
println!("{}={}", k, shell_quote(&v));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `run` command: inject secrets into a child process environment and execute.
|
||||||
|
pub async fn run_exec(pool: &PgPool, args: RunArgs<'_>, master_key: &[u8; 32]) -> Result<()> {
|
||||||
|
if args.command.is_empty() {
|
||||||
|
anyhow::bail!(
|
||||||
|
"No command specified. Usage: secrets run [filter flags] -- <command> [args]"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let env_map = collect_env_map(
|
||||||
|
pool,
|
||||||
|
args.namespace,
|
||||||
|
args.kind,
|
||||||
|
args.name,
|
||||||
|
args.tags,
|
||||||
|
args.prefix,
|
||||||
|
master_key,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
tracing::debug!(
|
||||||
|
vars = env_map.len(),
|
||||||
|
cmd = args.command[0].as_str(),
|
||||||
|
"injecting secrets into child process"
|
||||||
|
);
|
||||||
|
|
||||||
|
let status = std::process::Command::new(&args.command[0])
|
||||||
|
.args(&args.command[1..])
|
||||||
|
.envs(&env_map)
|
||||||
|
.status()
|
||||||
|
.map_err(|e| anyhow::anyhow!("Failed to execute '{}': {}", args.command[0], e))?;
|
||||||
|
|
||||||
|
if !status.success() {
|
||||||
|
let code = status.code().unwrap_or(1);
|
||||||
|
std::process::exit(code);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Quote a value for safe shell output. Wraps the value in single quotes,
|
||||||
|
/// escaping any single quotes within the value.
|
||||||
|
fn shell_quote(s: &str) -> String {
|
||||||
|
format!("'{}'", s.replace('\'', "'\\''"))
|
||||||
|
}
|
||||||
@@ -1,16 +1,17 @@
|
|||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use crate::crypto;
|
use crate::crypto;
|
||||||
use crate::models::Secret;
|
use crate::models::Secret;
|
||||||
use crate::output::OutputMode;
|
use crate::output::{OutputMode, format_local_time};
|
||||||
|
|
||||||
pub struct SearchArgs<'a> {
|
pub struct SearchArgs<'a> {
|
||||||
pub namespace: Option<&'a str>,
|
pub namespace: Option<&'a str>,
|
||||||
pub kind: Option<&'a str>,
|
pub kind: Option<&'a str>,
|
||||||
pub name: Option<&'a str>,
|
pub name: Option<&'a str>,
|
||||||
pub tag: Option<&'a str>,
|
pub tags: &'a [String],
|
||||||
pub query: Option<&'a str>,
|
pub query: Option<&'a str>,
|
||||||
pub show_secrets: bool,
|
pub show_secrets: bool,
|
||||||
pub fields: &'a [String],
|
pub fields: &'a [String],
|
||||||
@@ -21,29 +22,171 @@ pub struct SearchArgs<'a> {
|
|||||||
pub output: OutputMode,
|
pub output: OutputMode,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn run(pool: &PgPool, args: SearchArgs<'_>, master_key: Option<&[u8; 32]>) -> Result<()> {
|
pub async fn run(pool: &PgPool, args: SearchArgs<'_>) -> Result<()> {
|
||||||
|
validate_safe_search_args(args.show_secrets, args.fields)?;
|
||||||
|
|
||||||
|
let rows = fetch_rows_paged(
|
||||||
|
pool,
|
||||||
|
PagedFetchArgs {
|
||||||
|
namespace: args.namespace,
|
||||||
|
kind: args.kind,
|
||||||
|
name: args.name,
|
||||||
|
tags: args.tags,
|
||||||
|
query: args.query,
|
||||||
|
sort: args.sort,
|
||||||
|
limit: args.limit,
|
||||||
|
offset: args.offset,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// -f/--field: extract specific field values directly
|
||||||
|
if !args.fields.is_empty() {
|
||||||
|
return print_fields(&rows, args.fields);
|
||||||
|
}
|
||||||
|
|
||||||
|
match args.output {
|
||||||
|
OutputMode::Json | OutputMode::JsonCompact => {
|
||||||
|
let arr: Vec<Value> = rows.iter().map(|r| to_json(r, args.summary)).collect();
|
||||||
|
let out = if args.output == OutputMode::Json {
|
||||||
|
serde_json::to_string_pretty(&arr)?
|
||||||
|
} else {
|
||||||
|
serde_json::to_string(&arr)?
|
||||||
|
};
|
||||||
|
println!("{}", out);
|
||||||
|
}
|
||||||
|
OutputMode::Env => {
|
||||||
|
if rows.len() > 1 {
|
||||||
|
anyhow::bail!(
|
||||||
|
"env output requires exactly one record; got {}. Add more filters.",
|
||||||
|
rows.len()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if let Some(row) = rows.first() {
|
||||||
|
let map = build_metadata_env_map(row, "");
|
||||||
|
let mut pairs: Vec<(String, String)> = map.into_iter().collect();
|
||||||
|
pairs.sort_by(|a, b| a.0.cmp(&b.0));
|
||||||
|
for (k, v) in pairs {
|
||||||
|
println!("{}={}", k, shell_quote(&v));
|
||||||
|
}
|
||||||
|
} 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.summary)?;
|
||||||
|
}
|
||||||
|
println!("{} record(s) found.", rows.len());
|
||||||
|
if rows.len() == args.limit as usize {
|
||||||
|
println!(
|
||||||
|
" (showing up to {}; use --offset {} to see more)",
|
||||||
|
args.limit,
|
||||||
|
args.offset + args.limit
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_safe_search_args(show_secrets: bool, fields: &[String]) -> Result<()> {
|
||||||
|
if show_secrets {
|
||||||
|
anyhow::bail!(
|
||||||
|
"`search` no longer reveals secrets. Use `secrets inject` or `secrets run` instead."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(field) = fields.iter().find(|field| is_secret_field(field)) {
|
||||||
|
anyhow::bail!(
|
||||||
|
"Field '{}' is sensitive. `search -f` only supports metadata.* fields; use `secrets inject` or `secrets run` for secrets.",
|
||||||
|
field
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_secret_field(field: &str) -> bool {
|
||||||
|
matches!(
|
||||||
|
field.split_once('.').map(|(section, _)| section),
|
||||||
|
Some("secret" | "secrets" | "encrypted")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetch rows with simple equality/tag filters (no pagination). Used by inject/run.
|
||||||
|
pub async fn fetch_rows(
|
||||||
|
pool: &PgPool,
|
||||||
|
namespace: Option<&str>,
|
||||||
|
kind: Option<&str>,
|
||||||
|
name: Option<&str>,
|
||||||
|
tags: &[String],
|
||||||
|
query: Option<&str>,
|
||||||
|
) -> Result<Vec<Secret>> {
|
||||||
|
fetch_rows_paged(
|
||||||
|
pool,
|
||||||
|
PagedFetchArgs {
|
||||||
|
namespace,
|
||||||
|
kind,
|
||||||
|
name,
|
||||||
|
tags,
|
||||||
|
query,
|
||||||
|
sort: "name",
|
||||||
|
limit: 200,
|
||||||
|
offset: 0,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Arguments for the internal paged fetch. Grouped to avoid too-many-arguments lint.
|
||||||
|
struct PagedFetchArgs<'a> {
|
||||||
|
namespace: Option<&'a str>,
|
||||||
|
kind: Option<&'a str>,
|
||||||
|
name: Option<&'a str>,
|
||||||
|
tags: &'a [String],
|
||||||
|
query: Option<&'a str>,
|
||||||
|
sort: &'a str,
|
||||||
|
limit: u32,
|
||||||
|
offset: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_rows_paged(pool: &PgPool, a: PagedFetchArgs<'_>) -> Result<Vec<Secret>> {
|
||||||
let mut conditions: Vec<String> = Vec::new();
|
let mut conditions: Vec<String> = Vec::new();
|
||||||
let mut idx: i32 = 1;
|
let mut idx: i32 = 1;
|
||||||
|
|
||||||
if args.namespace.is_some() {
|
if a.namespace.is_some() {
|
||||||
conditions.push(format!("namespace = ${}", idx));
|
conditions.push(format!("namespace = ${}", idx));
|
||||||
idx += 1;
|
idx += 1;
|
||||||
}
|
}
|
||||||
if args.kind.is_some() {
|
if a.kind.is_some() {
|
||||||
conditions.push(format!("kind = ${}", idx));
|
conditions.push(format!("kind = ${}", idx));
|
||||||
idx += 1;
|
idx += 1;
|
||||||
}
|
}
|
||||||
if args.name.is_some() {
|
if a.name.is_some() {
|
||||||
conditions.push(format!("name = ${}", idx));
|
conditions.push(format!("name = ${}", idx));
|
||||||
idx += 1;
|
idx += 1;
|
||||||
}
|
}
|
||||||
if args.tag.is_some() {
|
if !a.tags.is_empty() {
|
||||||
conditions.push(format!("tags @> ARRAY[${}]", idx));
|
let placeholders: Vec<String> = a
|
||||||
|
.tags
|
||||||
|
.iter()
|
||||||
|
.map(|_| {
|
||||||
|
let p = format!("${}", idx);
|
||||||
idx += 1;
|
idx += 1;
|
||||||
|
p
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
conditions.push(format!("tags @> ARRAY[{}]", placeholders.join(", ")));
|
||||||
}
|
}
|
||||||
if args.query.is_some() {
|
if a.query.is_some() {
|
||||||
conditions.push(format!(
|
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}))",
|
"(name ILIKE ${i} ESCAPE '\\' OR namespace ILIKE ${i} ESCAPE '\\' OR kind ILIKE ${i} ESCAPE '\\' OR metadata::text ILIKE ${i} ESCAPE '\\' OR EXISTS (SELECT 1 FROM unnest(tags) t WHERE t ILIKE ${i} ESCAPE '\\'))",
|
||||||
i = idx
|
i = idx
|
||||||
));
|
));
|
||||||
idx += 1;
|
idx += 1;
|
||||||
@@ -55,7 +198,7 @@ pub async fn run(pool: &PgPool, args: SearchArgs<'_>, master_key: Option<&[u8; 3
|
|||||||
format!("WHERE {}", conditions.join(" AND "))
|
format!("WHERE {}", conditions.join(" AND "))
|
||||||
};
|
};
|
||||||
|
|
||||||
let order = match args.sort {
|
let order = match a.sort {
|
||||||
"updated" => "updated_at DESC",
|
"updated" => "updated_at DESC",
|
||||||
"created" => "created_at DESC",
|
"created" => "created_at DESC",
|
||||||
_ => "namespace, kind, name",
|
_ => "namespace, kind, name",
|
||||||
@@ -72,96 +215,109 @@ pub async fn run(pool: &PgPool, args: SearchArgs<'_>, master_key: Option<&[u8; 3
|
|||||||
tracing::debug!(sql, "executing search query");
|
tracing::debug!(sql, "executing search query");
|
||||||
|
|
||||||
let mut q = sqlx::query_as::<_, Secret>(&sql);
|
let mut q = sqlx::query_as::<_, Secret>(&sql);
|
||||||
if let Some(v) = args.namespace {
|
if let Some(v) = a.namespace {
|
||||||
q = q.bind(v);
|
q = q.bind(v);
|
||||||
}
|
}
|
||||||
if let Some(v) = args.kind {
|
if let Some(v) = a.kind {
|
||||||
q = q.bind(v);
|
q = q.bind(v);
|
||||||
}
|
}
|
||||||
if let Some(v) = args.name {
|
if let Some(v) = a.name {
|
||||||
q = q.bind(v);
|
q = q.bind(v);
|
||||||
}
|
}
|
||||||
if let Some(v) = args.tag {
|
for v in a.tags {
|
||||||
q = q.bind(v);
|
q = q.bind(v.as_str());
|
||||||
}
|
}
|
||||||
if let Some(v) = args.query {
|
if let Some(v) = a.query {
|
||||||
q = q.bind(format!("%{}%", v));
|
q = q.bind(format!(
|
||||||
|
"%{}%",
|
||||||
|
v.replace('\\', "\\\\")
|
||||||
|
.replace('%', "\\%")
|
||||||
|
.replace('_', "\\_")
|
||||||
|
));
|
||||||
}
|
}
|
||||||
q = q.bind(args.limit as i64).bind(args.offset as i64);
|
q = q.bind(a.limit as i64).bind(a.offset as i64);
|
||||||
|
|
||||||
let rows = q.fetch_all(pool).await?;
|
let rows = q.fetch_all(pool).await?;
|
||||||
|
Ok(rows)
|
||||||
// -f/--field: extract specific field values directly
|
|
||||||
if !args.fields.is_empty() {
|
|
||||||
return print_fields(&rows, args.fields, master_key);
|
|
||||||
}
|
|
||||||
|
|
||||||
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.
|
fn env_prefix(row: &Secret, prefix: &str) -> String {
|
||||||
/// Returns an error value on decrypt failure (so callers can decide how to handle).
|
let name_part = row.name.to_uppercase().replace(['-', '.', ' '], "_");
|
||||||
fn try_decrypt(row: &Secret, master_key: Option<&[u8; 32]>) -> Result<Value> {
|
if prefix.is_empty() {
|
||||||
if row.encrypted.is_empty() {
|
name_part
|
||||||
return Ok(Value::Object(Default::default()));
|
} else {
|
||||||
|
format!(
|
||||||
|
"{}_{}",
|
||||||
|
prefix.to_uppercase().replace(['-', '.', ' '], "_"),
|
||||||
|
name_part
|
||||||
|
)
|
||||||
}
|
}
|
||||||
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(
|
/// Build a flat `KEY=VALUE` map from metadata only.
|
||||||
|
/// Variable names: `<PREFIX><NAME>_<FIELD>` (all uppercased, hyphens/dots → underscores).
|
||||||
|
/// If `prefix` is empty, the name segment alone is used as the prefix.
|
||||||
|
pub fn build_metadata_env_map(row: &Secret, prefix: &str) -> HashMap<String, String> {
|
||||||
|
let effective_prefix = env_prefix(row, prefix);
|
||||||
|
|
||||||
|
let mut map = HashMap::new();
|
||||||
|
|
||||||
|
if let Some(meta) = row.metadata.as_object() {
|
||||||
|
for (k, v) in meta {
|
||||||
|
let key = format!(
|
||||||
|
"{}_{}",
|
||||||
|
effective_prefix,
|
||||||
|
k.to_uppercase().replace(['-', '.'], "_")
|
||||||
|
);
|
||||||
|
map.insert(key, json_value_to_env_string(v));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
map
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build a flat `KEY=VALUE` map from metadata and decrypted secrets.
|
||||||
|
pub fn build_injected_env_map(
|
||||||
row: &Secret,
|
row: &Secret,
|
||||||
show_secrets: bool,
|
prefix: &str,
|
||||||
summary: bool,
|
master_key: &[u8; 32],
|
||||||
master_key: Option<&[u8; 32]>,
|
) -> Result<HashMap<String, String>> {
|
||||||
) -> Value {
|
let effective_prefix = env_prefix(row, prefix);
|
||||||
|
let mut map = build_metadata_env_map(row, prefix);
|
||||||
|
|
||||||
|
if !row.encrypted.is_empty() {
|
||||||
|
let decrypted = crypto::decrypt_json(master_key, &row.encrypted)?;
|
||||||
|
if let Some(enc) = decrypted.as_object() {
|
||||||
|
for (k, v) in enc {
|
||||||
|
let key = format!(
|
||||||
|
"{}_{}",
|
||||||
|
effective_prefix,
|
||||||
|
k.to_uppercase().replace(['-', '.'], "_")
|
||||||
|
);
|
||||||
|
map.insert(key, json_value_to_env_string(v));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(map)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Quote a value for safe shell / env output. Wraps in single quotes,
|
||||||
|
/// escaping any single quotes within the value.
|
||||||
|
fn shell_quote(s: &str) -> String {
|
||||||
|
format!("'{}'", s.replace('\'', "'\\''"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convert a JSON value to its string representation suitable for env vars.
|
||||||
|
fn json_value_to_env_string(v: &Value) -> String {
|
||||||
|
match v {
|
||||||
|
Value::String(s) => s.clone(),
|
||||||
|
Value::Null => String::new(),
|
||||||
|
other => other.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn to_json(row: &Secret, summary: bool) -> Value {
|
||||||
if summary {
|
if summary {
|
||||||
let desc = row
|
let desc = row
|
||||||
.metadata
|
.metadata
|
||||||
@@ -180,13 +336,10 @@ fn to_json(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let secrets_val = if show_secrets {
|
let secrets_val = if row.encrypted.is_empty() {
|
||||||
match try_decrypt(row, master_key) {
|
Value::Object(Default::default())
|
||||||
Ok(v) => v,
|
|
||||||
Err(e) => json!({"_error": e.to_string()}),
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
json!({"_encrypted": true, "_key_count": encrypted_key_count(row, master_key)})
|
json!({"_encrypted": true})
|
||||||
};
|
};
|
||||||
|
|
||||||
json!({
|
json!({
|
||||||
@@ -197,29 +350,13 @@ fn to_json(
|
|||||||
"tags": row.tags,
|
"tags": row.tags,
|
||||||
"metadata": row.metadata,
|
"metadata": row.metadata,
|
||||||
"secrets": secrets_val,
|
"secrets": secrets_val,
|
||||||
|
"version": row.version,
|
||||||
"created_at": row.created_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
|
"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(),
|
"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 print_text(row: &Secret, summary: bool) -> Result<()> {
|
||||||
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);
|
println!("[{}/{}] {}", row.namespace, row.kind, row.name);
|
||||||
if summary {
|
if summary {
|
||||||
let desc = row
|
let desc = row
|
||||||
@@ -232,10 +369,7 @@ fn print_text(
|
|||||||
println!(" tags: [{}]", row.tags.join(", "));
|
println!(" tags: [{}]", row.tags.join(", "));
|
||||||
}
|
}
|
||||||
println!(" desc: {}", desc);
|
println!(" desc: {}", desc);
|
||||||
println!(
|
println!(" updated: {}", format_local_time(row.updated_at));
|
||||||
" updated: {}",
|
|
||||||
row.updated_at.format("%Y-%m-%d %H:%M:%S UTC")
|
|
||||||
);
|
|
||||||
} else {
|
} else {
|
||||||
println!(" id: {}", row.id);
|
println!(" id: {}", row.id);
|
||||||
if !row.tags.is_empty() {
|
if !row.tags.is_empty() {
|
||||||
@@ -248,82 +382,33 @@ fn print_text(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
if !row.encrypted.is_empty() {
|
if !row.encrypted.is_empty() {
|
||||||
if show_secrets {
|
println!(" secrets: [encrypted] (use `secrets inject` or `secrets run`)");
|
||||||
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!(" created: {}", format_local_time(row.created_at));
|
||||||
println!(" secrets: [encrypted] (--show-secrets to reveal)");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
println!(
|
|
||||||
" created: {}",
|
|
||||||
row.created_at.format("%Y-%m-%d %H:%M:%S UTC")
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
println!();
|
println!();
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn print_env(row: &Secret, show_secrets: bool, master_key: Option<&[u8; 32]>) -> Result<()> {
|
/// Extract one or more field paths like `metadata.url`.
|
||||||
let prefix = row.name.to_uppercase().replace(['-', '.'], "_");
|
fn print_fields(rows: &[Secret], fields: &[String]) -> Result<()> {
|
||||||
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 {
|
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 {
|
for field in fields {
|
||||||
let val = extract_field(row, field, decrypted.as_ref())?;
|
let val = extract_field(row, field)?;
|
||||||
println!("{}", val);
|
println!("{}", val);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn extract_field(row: &Secret, field: &str, decrypted: Option<&Value>) -> Result<String> {
|
fn extract_field(row: &Secret, field: &str) -> Result<String> {
|
||||||
let (section, key) = field.split_once('.').ok_or_else(|| {
|
let (section, key) = field
|
||||||
anyhow::anyhow!(
|
.split_once('.')
|
||||||
"Invalid field path '{}'. Use metadata.<key> or secret.<key>",
|
.ok_or_else(|| anyhow::anyhow!("Invalid field path '{}'. Use metadata.<key>.", field))?;
|
||||||
field
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
|
|
||||||
let obj = match section {
|
let obj = match section {
|
||||||
"metadata" | "meta" => &row.metadata,
|
"metadata" | "meta" => &row.metadata,
|
||||||
"secret" | "secrets" | "encrypted" => {
|
other => anyhow::bail!("Unknown field section '{}'. Use 'metadata'.", other),
|
||||||
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)
|
obj.get(key)
|
||||||
@@ -342,3 +427,70 @@ fn extract_field(row: &Secret, field: &str, decrypted: Option<&Value>) -> Result
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use chrono::Utc;
|
||||||
|
use serde_json::json;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
fn sample_secret() -> Secret {
|
||||||
|
let key = [0x42u8; 32];
|
||||||
|
let encrypted = crypto::encrypt_json(&key, &json!({"token": "abc123"})).unwrap();
|
||||||
|
|
||||||
|
Secret {
|
||||||
|
id: Uuid::nil(),
|
||||||
|
namespace: "refining".to_string(),
|
||||||
|
kind: "service".to_string(),
|
||||||
|
name: "gitea.main".to_string(),
|
||||||
|
tags: vec!["prod".to_string()],
|
||||||
|
metadata: json!({"url": "https://gitea.refining.dev", "enabled": true}),
|
||||||
|
encrypted,
|
||||||
|
version: 1,
|
||||||
|
created_at: Utc::now(),
|
||||||
|
updated_at: Utc::now(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_show_secrets_flag() {
|
||||||
|
let err = validate_safe_search_args(true, &[]).unwrap_err();
|
||||||
|
assert!(err.to_string().contains("no longer reveals secrets"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_secret_field_extraction() {
|
||||||
|
let fields = vec!["secret.token".to_string()];
|
||||||
|
let err = validate_safe_search_args(false, &fields).unwrap_err();
|
||||||
|
assert!(err.to_string().contains("sensitive"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn metadata_env_map_excludes_secret_values() {
|
||||||
|
let row = sample_secret();
|
||||||
|
let map = build_metadata_env_map(&row, "");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
map.get("GITEA_MAIN_URL").map(String::as_str),
|
||||||
|
Some("https://gitea.refining.dev")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
map.get("GITEA_MAIN_ENABLED").map(String::as_str),
|
||||||
|
Some("true")
|
||||||
|
);
|
||||||
|
assert!(!map.contains_key("GITEA_MAIN_TOKEN"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn injected_env_map_includes_secret_values() {
|
||||||
|
let row = sample_secret();
|
||||||
|
let key = [0x42u8; 32];
|
||||||
|
let map = build_injected_env_map(&row, "", &key).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
map.get("GITEA_MAIN_TOKEN").map(String::as_str),
|
||||||
|
Some("abc123")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,10 +5,13 @@ use uuid::Uuid;
|
|||||||
|
|
||||||
use super::add::parse_kv;
|
use super::add::parse_kv;
|
||||||
use crate::crypto;
|
use crate::crypto;
|
||||||
|
use crate::db;
|
||||||
|
use crate::output::OutputMode;
|
||||||
|
|
||||||
#[derive(FromRow)]
|
#[derive(FromRow)]
|
||||||
struct UpdateRow {
|
struct UpdateRow {
|
||||||
id: Uuid,
|
id: Uuid,
|
||||||
|
version: i64,
|
||||||
tags: Vec<String>,
|
tags: Vec<String>,
|
||||||
metadata: Value,
|
metadata: Value,
|
||||||
encrypted: Vec<u8>,
|
encrypted: Vec<u8>,
|
||||||
@@ -24,20 +27,22 @@ pub struct UpdateArgs<'a> {
|
|||||||
pub remove_meta: &'a [String],
|
pub remove_meta: &'a [String],
|
||||||
pub secret_entries: &'a [String],
|
pub secret_entries: &'a [String],
|
||||||
pub remove_secrets: &'a [String],
|
pub remove_secrets: &'a [String],
|
||||||
|
pub output: OutputMode,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn run(pool: &PgPool, args: UpdateArgs<'_>, master_key: &[u8; 32]) -> Result<()> {
|
pub async fn run(pool: &PgPool, args: UpdateArgs<'_>, master_key: &[u8; 32]) -> Result<()> {
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
|
||||||
let row: Option<UpdateRow> = sqlx::query_as(
|
let row: Option<UpdateRow> = sqlx::query_as(
|
||||||
r#"
|
"SELECT id, version, tags, metadata, encrypted \
|
||||||
SELECT id, tags, metadata, encrypted
|
FROM secrets \
|
||||||
FROM secrets
|
WHERE namespace = $1 AND kind = $2 AND name = $3 \
|
||||||
WHERE namespace = $1 AND kind = $2 AND name = $3
|
FOR UPDATE",
|
||||||
"#,
|
|
||||||
)
|
)
|
||||||
.bind(args.namespace)
|
.bind(args.namespace)
|
||||||
.bind(args.kind)
|
.bind(args.kind)
|
||||||
.bind(args.name)
|
.bind(args.name)
|
||||||
.fetch_optional(pool)
|
.fetch_optional(&mut *tx)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let row = row.ok_or_else(|| {
|
let row = row.ok_or_else(|| {
|
||||||
@@ -49,6 +54,26 @@ pub async fn run(pool: &PgPool, args: UpdateArgs<'_>, master_key: &[u8; 32]) ->
|
|||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
|
// Snapshot current state before modifying.
|
||||||
|
if let Err(e) = db::snapshot_history(
|
||||||
|
&mut tx,
|
||||||
|
db::SnapshotParams {
|
||||||
|
secret_id: row.id,
|
||||||
|
namespace: args.namespace,
|
||||||
|
kind: args.kind,
|
||||||
|
name: args.name,
|
||||||
|
version: row.version,
|
||||||
|
action: "update",
|
||||||
|
tags: &row.tags,
|
||||||
|
metadata: &row.metadata,
|
||||||
|
encrypted: &row.encrypted,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
tracing::warn!(error = %e, "failed to snapshot history before update");
|
||||||
|
}
|
||||||
|
|
||||||
// Merge tags
|
// Merge tags
|
||||||
let mut tags: Vec<String> = row.tags;
|
let mut tags: Vec<String> = row.tags;
|
||||||
for t in args.add_tags {
|
for t in args.add_tags {
|
||||||
@@ -65,7 +90,7 @@ pub async fn run(pool: &PgPool, args: UpdateArgs<'_>, master_key: &[u8; 32]) ->
|
|||||||
};
|
};
|
||||||
for entry in args.meta_entries {
|
for entry in args.meta_entries {
|
||||||
let (key, value) = parse_kv(entry)?;
|
let (key, value) = parse_kv(entry)?;
|
||||||
meta_map.insert(key, Value::String(value));
|
meta_map.insert(key, value);
|
||||||
}
|
}
|
||||||
for key in args.remove_meta {
|
for key in args.remove_meta {
|
||||||
meta_map.remove(key);
|
meta_map.remove(key);
|
||||||
@@ -84,7 +109,7 @@ pub async fn run(pool: &PgPool, args: UpdateArgs<'_>, master_key: &[u8; 32]) ->
|
|||||||
};
|
};
|
||||||
for entry in args.secret_entries {
|
for entry in args.secret_entries {
|
||||||
let (key, value) = parse_kv(entry)?;
|
let (key, value) = parse_kv(entry)?;
|
||||||
enc_map.insert(key, Value::String(value));
|
enc_map.insert(key, value);
|
||||||
}
|
}
|
||||||
for key in args.remove_secrets {
|
for key in args.remove_secrets {
|
||||||
enc_map.remove(key);
|
enc_map.remove(key);
|
||||||
@@ -99,33 +124,43 @@ pub async fn run(pool: &PgPool, args: UpdateArgs<'_>, master_key: &[u8; 32]) ->
|
|||||||
"updating record"
|
"updating record"
|
||||||
);
|
);
|
||||||
|
|
||||||
sqlx::query(
|
// CAS: update only if version hasn't changed (FOR UPDATE lock ensures this).
|
||||||
r#"
|
let result = sqlx::query(
|
||||||
UPDATE secrets
|
"UPDATE secrets \
|
||||||
SET tags = $1, metadata = $2, encrypted = $3, updated_at = NOW()
|
SET tags = $1, metadata = $2, encrypted = $3, version = version + 1, updated_at = NOW() \
|
||||||
WHERE id = $4
|
WHERE id = $4 AND version = $5",
|
||||||
"#,
|
|
||||||
)
|
)
|
||||||
.bind(&tags)
|
.bind(&tags)
|
||||||
.bind(metadata)
|
.bind(&metadata)
|
||||||
.bind(encrypted_bytes)
|
.bind(&encrypted_bytes)
|
||||||
.bind(row.id)
|
.bind(row.id)
|
||||||
.execute(pool)
|
.bind(row.version)
|
||||||
|
.execute(&mut *tx)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
if result.rows_affected() == 0 {
|
||||||
|
tx.rollback().await?;
|
||||||
|
anyhow::bail!(
|
||||||
|
"Concurrent modification detected for [{}/{}] {}. Please retry.",
|
||||||
|
args.namespace,
|
||||||
|
args.kind,
|
||||||
|
args.name
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
let meta_keys: Vec<&str> = args
|
let meta_keys: Vec<&str> = args
|
||||||
.meta_entries
|
.meta_entries
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
|
.filter_map(|s| s.split_once(['=', ':']).map(|(k, _)| k))
|
||||||
.collect();
|
.collect();
|
||||||
let secret_keys: Vec<&str> = args
|
let secret_keys: Vec<&str> = args
|
||||||
.secret_entries
|
.secret_entries
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
|
.filter_map(|s| s.split_once(['=', ':']).map(|(k, _)| k))
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
crate::audit::log(
|
crate::audit::log_tx(
|
||||||
pool,
|
&mut tx,
|
||||||
"update",
|
"update",
|
||||||
args.namespace,
|
args.namespace,
|
||||||
args.kind,
|
args.kind,
|
||||||
@@ -141,8 +176,30 @@ pub async fn run(pool: &PgPool, args: UpdateArgs<'_>, master_key: &[u8; 32]) ->
|
|||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
println!("Updated: [{}/{}] {}", args.namespace, args.kind, args.name);
|
tx.commit().await?;
|
||||||
|
|
||||||
|
let result_json = json!({
|
||||||
|
"action": "updated",
|
||||||
|
"namespace": args.namespace,
|
||||||
|
"kind": args.kind,
|
||||||
|
"name": args.name,
|
||||||
|
"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,
|
||||||
|
});
|
||||||
|
|
||||||
|
match args.output {
|
||||||
|
OutputMode::Json => {
|
||||||
|
println!("{}", serde_json::to_string_pretty(&result_json)?);
|
||||||
|
}
|
||||||
|
OutputMode::JsonCompact => {
|
||||||
|
println!("{}", serde_json::to_string(&result_json)?);
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
println!("Updated: [{}/{}] {}", args.namespace, args.kind, args.name);
|
||||||
if !args.add_tags.is_empty() {
|
if !args.add_tags.is_empty() {
|
||||||
println!(" +tags: {}", args.add_tags.join(", "));
|
println!(" +tags: {}", args.add_tags.join(", "));
|
||||||
}
|
}
|
||||||
@@ -150,27 +207,19 @@ pub async fn run(pool: &PgPool, args: UpdateArgs<'_>, master_key: &[u8; 32]) ->
|
|||||||
println!(" -tags: {}", args.remove_tags.join(", "));
|
println!(" -tags: {}", args.remove_tags.join(", "));
|
||||||
}
|
}
|
||||||
if !args.meta_entries.is_empty() {
|
if !args.meta_entries.is_empty() {
|
||||||
let keys: Vec<&str> = args
|
println!(" +metadata: {}", meta_keys.join(", "));
|
||||||
.meta_entries
|
|
||||||
.iter()
|
|
||||||
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
|
|
||||||
.collect();
|
|
||||||
println!(" +metadata: {}", keys.join(", "));
|
|
||||||
}
|
}
|
||||||
if !args.remove_meta.is_empty() {
|
if !args.remove_meta.is_empty() {
|
||||||
println!(" -metadata: {}", args.remove_meta.join(", "));
|
println!(" -metadata: {}", args.remove_meta.join(", "));
|
||||||
}
|
}
|
||||||
if !args.secret_entries.is_empty() {
|
if !args.secret_entries.is_empty() {
|
||||||
let keys: Vec<&str> = args
|
println!(" +secrets: {}", secret_keys.join(", "));
|
||||||
.secret_entries
|
|
||||||
.iter()
|
|
||||||
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
|
|
||||||
.collect();
|
|
||||||
println!(" +secrets: {}", keys.join(", "));
|
|
||||||
}
|
}
|
||||||
if !args.remove_secrets.is_empty() {
|
if !args.remove_secrets.is_empty() {
|
||||||
println!(" -secrets: {}", args.remove_secrets.join(", "));
|
println!(" -secrets: {}", args.remove_secrets.join(", "));
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
394
src/commands/upgrade.rs
Normal file
394
src/commands/upgrade.rs
Normal file
@@ -0,0 +1,394 @@
|
|||||||
|
use anyhow::{Context, Result, bail};
|
||||||
|
use flate2::read::GzDecoder;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use std::io::{Cursor, Read, Write};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
const GITEA_API: &str = "https://gitea.refining.dev/api/v1/repos/refining/secrets/releases/latest";
|
||||||
|
|
||||||
|
const CURRENT_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct Release {
|
||||||
|
tag_name: String,
|
||||||
|
assets: Vec<Asset>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct Asset {
|
||||||
|
name: String,
|
||||||
|
browser_download_url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn available_assets(assets: &[Asset]) -> String {
|
||||||
|
assets
|
||||||
|
.iter()
|
||||||
|
.map(|a| a.name.as_str())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn release_asset_name(tag_name: &str, suffix: &str) -> String {
|
||||||
|
format!("secrets-{tag_name}-{suffix}")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_asset_by_name<'a>(assets: &'a [Asset], name: &str) -> Result<&'a Asset> {
|
||||||
|
assets.iter().find(|a| a.name == name).with_context(|| {
|
||||||
|
format!(
|
||||||
|
"no matching release asset found: {name}\navailable: {}",
|
||||||
|
available_assets(assets)
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Detect the asset suffix for the current platform/arch at compile time.
|
||||||
|
fn platform_asset_suffix() -> Result<&'static str> {
|
||||||
|
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
|
||||||
|
{
|
||||||
|
Ok("x86_64-linux-musl.tar.gz")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
|
||||||
|
{
|
||||||
|
Ok("aarch64-macos.tar.gz")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
|
||||||
|
{
|
||||||
|
Ok("x86_64-macos.tar.gz")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(all(target_os = "windows", target_arch = "x86_64"))]
|
||||||
|
{
|
||||||
|
Ok("x86_64-windows.zip")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(any(
|
||||||
|
all(target_os = "linux", target_arch = "x86_64"),
|
||||||
|
all(target_os = "macos", target_arch = "aarch64"),
|
||||||
|
all(target_os = "macos", target_arch = "x86_64"),
|
||||||
|
all(target_os = "windows", target_arch = "x86_64"),
|
||||||
|
)))]
|
||||||
|
bail!(
|
||||||
|
"Unsupported platform: {}/{}",
|
||||||
|
std::env::consts::OS,
|
||||||
|
std::env::consts::ARCH
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Strip the "secrets-" prefix from the tag and parse as semver.
|
||||||
|
fn parse_tag_version(tag: &str) -> Result<semver::Version> {
|
||||||
|
let ver_str = tag
|
||||||
|
.strip_prefix("secrets-")
|
||||||
|
.with_context(|| format!("unexpected tag format: {tag}"))?;
|
||||||
|
semver::Version::parse(ver_str)
|
||||||
|
.with_context(|| format!("failed to parse version from tag: {tag}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sha256_hex(bytes: &[u8]) -> String {
|
||||||
|
let digest = Sha256::digest(bytes);
|
||||||
|
format!("{digest:x}")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_checksum(asset_name: &str, archive: &[u8], checksum_contents: &str) -> Result<String> {
|
||||||
|
let expected_checksum = parse_checksum_file(checksum_contents)?;
|
||||||
|
let actual_checksum = sha256_hex(archive);
|
||||||
|
|
||||||
|
if actual_checksum != expected_checksum {
|
||||||
|
bail!(
|
||||||
|
"checksum verification failed for {}: expected {}, got {}",
|
||||||
|
asset_name,
|
||||||
|
expected_checksum,
|
||||||
|
actual_checksum
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(actual_checksum)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_checksum_file(contents: &str) -> Result<String> {
|
||||||
|
let checksum = contents
|
||||||
|
.split_whitespace()
|
||||||
|
.next()
|
||||||
|
.context("checksum file is empty")?
|
||||||
|
.trim()
|
||||||
|
.to_ascii_lowercase();
|
||||||
|
|
||||||
|
if checksum.len() != 64 || !checksum.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||||
|
bail!("invalid SHA-256 checksum format")
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(checksum)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn download_bytes(client: &reqwest::Client, url: &str, context: &str) -> Result<Vec<u8>> {
|
||||||
|
Ok(client
|
||||||
|
.get(url)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.with_context(|| format!("{context}: request failed"))?
|
||||||
|
.error_for_status()
|
||||||
|
.with_context(|| format!("{context}: server returned an error"))?
|
||||||
|
.bytes()
|
||||||
|
.await
|
||||||
|
.with_context(|| format!("{context}: failed to read response body"))?
|
||||||
|
.to_vec())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extract the binary from a tar.gz archive (first file whose name == "secrets").
|
||||||
|
fn extract_from_targz(bytes: &[u8]) -> Result<Vec<u8>> {
|
||||||
|
let gz = GzDecoder::new(Cursor::new(bytes));
|
||||||
|
let mut archive = tar::Archive::new(gz);
|
||||||
|
for entry in archive.entries().context("failed to read tar entries")? {
|
||||||
|
let mut entry = entry.context("bad tar entry")?;
|
||||||
|
let path = entry.path().context("bad tar entry path")?.into_owned();
|
||||||
|
let fname = path
|
||||||
|
.file_name()
|
||||||
|
.and_then(|n| n.to_str())
|
||||||
|
.unwrap_or_default();
|
||||||
|
if fname == "secrets" || fname == "secrets.exe" {
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
entry.read_to_end(&mut buf).context("read tar entry")?;
|
||||||
|
return Ok(buf);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bail!("binary not found inside tar.gz archive")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extract the binary from a zip archive (first file whose name matches).
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
fn extract_from_zip(bytes: &[u8]) -> Result<Vec<u8>> {
|
||||||
|
let reader = Cursor::new(bytes);
|
||||||
|
let mut archive = zip::ZipArchive::new(reader).context("failed to open zip archive")?;
|
||||||
|
for i in 0..archive.len() {
|
||||||
|
let mut file = archive.by_index(i).context("bad zip entry")?;
|
||||||
|
let fname = file.name().to_owned();
|
||||||
|
if fname.ends_with("secrets.exe") || fname.ends_with("secrets") {
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
file.read_to_end(&mut buf).context("read zip entry")?;
|
||||||
|
return Ok(buf);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bail!("binary not found inside zip archive")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn run(check_only: bool) -> Result<()> {
|
||||||
|
let current = semver::Version::parse(CURRENT_VERSION).context("invalid current version")?;
|
||||||
|
|
||||||
|
println!("Current version: v{current}");
|
||||||
|
println!("Checking for updates...");
|
||||||
|
|
||||||
|
let client = reqwest::Client::builder()
|
||||||
|
.user_agent(format!("secrets-cli/{CURRENT_VERSION}"))
|
||||||
|
.connect_timeout(Duration::from_secs(10))
|
||||||
|
.timeout(Duration::from_secs(120))
|
||||||
|
.build()
|
||||||
|
.context("failed to build HTTP client")?;
|
||||||
|
|
||||||
|
let release: Release = client
|
||||||
|
.get(GITEA_API)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.context("failed to fetch release info from Gitea")?
|
||||||
|
.error_for_status()
|
||||||
|
.context("Gitea API returned an error")?
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.context("failed to parse release JSON")?;
|
||||||
|
|
||||||
|
let latest = parse_tag_version(&release.tag_name)?;
|
||||||
|
|
||||||
|
if latest <= current {
|
||||||
|
println!("Already up to date (v{current})");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("New version available: v{latest}");
|
||||||
|
|
||||||
|
if check_only {
|
||||||
|
println!("Run `secrets upgrade` to update.");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let suffix = platform_asset_suffix()?;
|
||||||
|
let asset_name = release_asset_name(&release.tag_name, suffix);
|
||||||
|
let asset = find_asset_by_name(&release.assets, &asset_name)?;
|
||||||
|
let checksum_name = format!("{}.sha256", asset.name);
|
||||||
|
let checksum_asset = find_asset_by_name(&release.assets, &checksum_name)?;
|
||||||
|
|
||||||
|
println!("Downloading {}...", asset.name);
|
||||||
|
|
||||||
|
let archive = download_bytes(&client, &asset.browser_download_url, "archive download").await?;
|
||||||
|
let checksum_contents = download_bytes(
|
||||||
|
&client,
|
||||||
|
&checksum_asset.browser_download_url,
|
||||||
|
"checksum download",
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let actual_checksum = verify_checksum(
|
||||||
|
&asset.name,
|
||||||
|
&archive,
|
||||||
|
std::str::from_utf8(&checksum_contents).context("checksum file is not valid UTF-8")?,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
println!("Verified SHA-256: {actual_checksum}");
|
||||||
|
|
||||||
|
println!("Extracting...");
|
||||||
|
|
||||||
|
let binary = if suffix.ends_with(".tar.gz") {
|
||||||
|
extract_from_targz(&archive)?
|
||||||
|
} else {
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
{
|
||||||
|
extract_from_zip(&archive)?
|
||||||
|
}
|
||||||
|
#[cfg(not(target_os = "windows"))]
|
||||||
|
bail!("zip extraction is only supported on Windows")
|
||||||
|
};
|
||||||
|
|
||||||
|
// Write to a temporary file, set executable permission, then atomically replace.
|
||||||
|
let mut tmp = tempfile::NamedTempFile::new().context("failed to create temp file")?;
|
||||||
|
tmp.write_all(&binary)
|
||||||
|
.context("failed to write temp binary")?;
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
let perms = std::fs::Permissions::from_mode(0o755);
|
||||||
|
std::fs::set_permissions(tmp.path(), perms).context("failed to chmod temp binary")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
self_replace::self_replace(tmp.path()).context("failed to replace current binary")?;
|
||||||
|
|
||||||
|
println!("Updated: v{current} → v{latest}");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use flate2::Compression;
|
||||||
|
use flate2::write::GzEncoder;
|
||||||
|
use tar::Builder;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_tag_version_accepts_release_tag() {
|
||||||
|
let version = parse_tag_version("secrets-0.6.1").expect("version should parse");
|
||||||
|
assert_eq!(version, semver::Version::new(0, 6, 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_tag_version_rejects_invalid_tag() {
|
||||||
|
let err = parse_tag_version("v0.6.1").expect_err("tag should be rejected");
|
||||||
|
assert!(err.to_string().contains("unexpected tag format"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_checksum_file_accepts_sha256sum_format() {
|
||||||
|
let checksum = parse_checksum_file(
|
||||||
|
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef secrets.tar.gz",
|
||||||
|
)
|
||||||
|
.expect("checksum should parse");
|
||||||
|
assert_eq!(
|
||||||
|
checksum,
|
||||||
|
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_checksum_file_rejects_invalid_checksum() {
|
||||||
|
let err = parse_checksum_file("not-a-sha256").expect_err("checksum should be rejected");
|
||||||
|
assert!(err.to_string().contains("invalid SHA-256 checksum format"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn release_asset_name_matches_release_tag() {
|
||||||
|
assert_eq!(
|
||||||
|
release_asset_name("secrets-0.7.0", "x86_64-linux-musl.tar.gz"),
|
||||||
|
"secrets-secrets-0.7.0-x86_64-linux-musl.tar.gz"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn find_asset_by_name_rejects_stale_platform_match() {
|
||||||
|
let assets = vec![
|
||||||
|
Asset {
|
||||||
|
name: "secrets-secrets-0.6.9-x86_64-linux-musl.tar.gz".into(),
|
||||||
|
browser_download_url: "https://example.invalid/old".into(),
|
||||||
|
},
|
||||||
|
Asset {
|
||||||
|
name: "secrets-secrets-0.7.0-aarch64-macos.tar.gz".into(),
|
||||||
|
browser_download_url: "https://example.invalid/other".into(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
let err = find_asset_by_name(&assets, "secrets-secrets-0.7.0-x86_64-linux-musl.tar.gz")
|
||||||
|
.expect_err("stale asset should not match");
|
||||||
|
|
||||||
|
assert!(err.to_string().contains("no matching release asset found"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sha256_hex_matches_known_value() {
|
||||||
|
assert_eq!(
|
||||||
|
sha256_hex(b"abc"),
|
||||||
|
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn verify_checksum_rejects_mismatch() {
|
||||||
|
let err = verify_checksum(
|
||||||
|
"secrets.tar.gz",
|
||||||
|
b"abc",
|
||||||
|
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef secrets.tar.gz",
|
||||||
|
)
|
||||||
|
.expect_err("checksum mismatch should fail");
|
||||||
|
|
||||||
|
assert!(err.to_string().contains("checksum verification failed"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn extract_from_targz_reads_binary() {
|
||||||
|
let payload = b"fake-secrets-binary";
|
||||||
|
let archive = make_test_targz("secrets", payload);
|
||||||
|
let extracted = extract_from_targz(&archive).expect("binary should extract");
|
||||||
|
assert_eq!(extracted, payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn make_test_targz(name: &str, payload: &[u8]) -> Vec<u8> {
|
||||||
|
let encoder = GzEncoder::new(Vec::new(), Compression::default());
|
||||||
|
let mut builder = Builder::new(encoder);
|
||||||
|
|
||||||
|
let mut header = tar::Header::new_gnu();
|
||||||
|
header.set_mode(0o755);
|
||||||
|
header.set_size(payload.len() as u64);
|
||||||
|
header.set_cksum();
|
||||||
|
builder
|
||||||
|
.append_data(&mut header, name, payload)
|
||||||
|
.expect("append tar entry");
|
||||||
|
|
||||||
|
let encoder = builder.into_inner().expect("finish tar builder");
|
||||||
|
encoder.finish().expect("finish gzip")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
#[test]
|
||||||
|
fn extract_from_zip_reads_binary() {
|
||||||
|
use zip::write::SimpleFileOptions;
|
||||||
|
|
||||||
|
let cursor = Cursor::new(Vec::<u8>::new());
|
||||||
|
let mut writer = zip::ZipWriter::new(cursor);
|
||||||
|
writer
|
||||||
|
.start_file("secrets.exe", SimpleFileOptions::default())
|
||||||
|
.expect("start zip file");
|
||||||
|
writer
|
||||||
|
.write_all(b"fake-secrets-binary")
|
||||||
|
.expect("write zip payload");
|
||||||
|
let bytes = writer.finish().expect("finish zip").into_inner();
|
||||||
|
|
||||||
|
let extracted = extract_from_zip(&bytes).expect("binary should extract");
|
||||||
|
assert_eq!(extracted, b"fake-secrets-binary");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,7 +10,8 @@ pub struct Config {
|
|||||||
|
|
||||||
pub fn config_dir() -> PathBuf {
|
pub fn config_dir() -> PathBuf {
|
||||||
dirs::config_dir()
|
dirs::config_dir()
|
||||||
.unwrap_or_else(|| PathBuf::from("~/.config"))
|
.or_else(|| dirs::home_dir().map(|h| h.join(".config")))
|
||||||
|
.unwrap_or_else(|| PathBuf::from(".config"))
|
||||||
.join("secrets")
|
.join("secrets")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -24,36 +25,38 @@ pub fn load_config() -> Result<Config> {
|
|||||||
return Ok(Config::default());
|
return Ok(Config::default());
|
||||||
}
|
}
|
||||||
let content = fs::read_to_string(&path)
|
let content = fs::read_to_string(&path)
|
||||||
.with_context(|| format!("读取配置文件失败: {}", path.display()))?;
|
.with_context(|| format!("failed to read config file: {}", path.display()))?;
|
||||||
let config: Config = toml::from_str(&content)
|
let config: Config = toml::from_str(&content)
|
||||||
.with_context(|| format!("解析配置文件失败: {}", path.display()))?;
|
.with_context(|| format!("failed to parse config file: {}", path.display()))?;
|
||||||
Ok(config)
|
Ok(config)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn save_config(config: &Config) -> Result<()> {
|
pub fn save_config(config: &Config) -> Result<()> {
|
||||||
let dir = config_dir();
|
let dir = config_dir();
|
||||||
fs::create_dir_all(&dir).with_context(|| format!("创建配置目录失败: {}", dir.display()))?;
|
fs::create_dir_all(&dir)
|
||||||
|
.with_context(|| format!("failed to create config dir: {}", dir.display()))?;
|
||||||
|
|
||||||
let path = config_path();
|
let path = config_path();
|
||||||
let content = toml::to_string_pretty(config).context("序列化配置失败")?;
|
let content = toml::to_string_pretty(config).context("failed to serialize config")?;
|
||||||
fs::write(&path, &content).with_context(|| format!("写入配置文件失败: {}", path.display()))?;
|
fs::write(&path, &content)
|
||||||
|
.with_context(|| format!("failed to write config file: {}", path.display()))?;
|
||||||
|
|
||||||
// 设置文件权限为 0600(仅所有者读写)
|
// Set file permissions to 0600 (owner read/write only)
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
{
|
{
|
||||||
use std::os::unix::fs::PermissionsExt;
|
use std::os::unix::fs::PermissionsExt;
|
||||||
let perms = fs::Permissions::from_mode(0o600);
|
let perms = fs::Permissions::from_mode(0o600);
|
||||||
fs::set_permissions(&path, perms)
|
fs::set_permissions(&path, perms)
|
||||||
.with_context(|| format!("设置文件权限失败: {}", path.display()))?;
|
.with_context(|| format!("failed to set file permissions: {}", path.display()))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 按优先级解析数据库连接串:
|
/// Resolve database URL by priority:
|
||||||
/// 1. --db-url CLI 参数(非空时使用)
|
/// 1. --db-url CLI flag (if non-empty)
|
||||||
/// 2. ~/.config/secrets/config.toml 中的 database_url
|
/// 2. database_url in ~/.config/secrets/config.toml
|
||||||
/// 3. 报错并提示用户配置
|
/// 3. Error with setup instructions
|
||||||
pub fn resolve_db_url(cli_db_url: &str) -> Result<String> {
|
pub fn resolve_db_url(cli_db_url: &str) -> Result<String> {
|
||||||
if !cli_db_url.is_empty() {
|
if !cli_db_url.is_empty() {
|
||||||
return Ok(cli_db_url.to_string());
|
return Ok(cli_db_url.to_string());
|
||||||
@@ -66,5 +69,5 @@ pub fn resolve_db_url(cli_db_url: &str) -> Result<String> {
|
|||||||
return Ok(url);
|
return Ok(url);
|
||||||
}
|
}
|
||||||
|
|
||||||
anyhow::bail!("数据库未配置。请先运行:\n\n secrets config set-db <DATABASE_URL>\n")
|
anyhow::bail!("Database not configured. Run:\n\n secrets config set-db <DATABASE_URL>\n")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -105,15 +105,6 @@ pub fn store_master_key(key: &[u8; 32]) -> Result<()> {
|
|||||||
Ok(())
|
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) ────────────────────────────────────
|
// ─── Minimal hex helpers (avoid extra dep) ────────────────────────────────────
|
||||||
|
|
||||||
mod hex {
|
mod hex {
|
||||||
|
|||||||
71
src/db.rs
71
src/db.rs
@@ -6,6 +6,7 @@ pub async fn create_pool(database_url: &str) -> Result<PgPool> {
|
|||||||
tracing::debug!("connecting to database");
|
tracing::debug!("connecting to database");
|
||||||
let pool = PgPoolOptions::new()
|
let pool = PgPoolOptions::new()
|
||||||
.max_connections(5)
|
.max_connections(5)
|
||||||
|
.acquire_timeout(std::time::Duration::from_secs(5))
|
||||||
.connect(database_url)
|
.connect(database_url)
|
||||||
.await?;
|
.await?;
|
||||||
tracing::debug!("database connection established");
|
tracing::debug!("database connection established");
|
||||||
@@ -24,6 +25,7 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
|
|||||||
tags TEXT[] NOT NULL DEFAULT '{}',
|
tags TEXT[] NOT NULL DEFAULT '{}',
|
||||||
metadata JSONB NOT NULL DEFAULT '{}',
|
metadata JSONB NOT NULL DEFAULT '{}',
|
||||||
encrypted BYTEA NOT NULL DEFAULT '\x',
|
encrypted BYTEA NOT NULL DEFAULT '\x',
|
||||||
|
version BIGINT NOT NULL DEFAULT 1,
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
UNIQUE(namespace, kind, name)
|
UNIQUE(namespace, kind, name)
|
||||||
@@ -35,10 +37,14 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
|
|||||||
EXCEPTION WHEN OTHERS THEN NULL;
|
EXCEPTION WHEN OTHERS THEN NULL;
|
||||||
END $$;
|
END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE secrets ADD COLUMN IF NOT EXISTS version BIGINT NOT NULL DEFAULT 1;
|
||||||
|
EXCEPTION WHEN OTHERS THEN NULL;
|
||||||
|
END $$;
|
||||||
|
|
||||||
-- Migrate encrypted column from JSONB to BYTEA if still JSONB type.
|
-- Migrate encrypted column from JSONB to BYTEA if still JSONB type.
|
||||||
-- After migration, old plaintext rows will have their JSONB data
|
-- After migration, old plaintext rows will have their JSONB data
|
||||||
-- stored as raw bytes (not yet re-encrypted); run `secrets migrate-encrypt`
|
-- stored as raw bytes (UTF-8 encoded).
|
||||||
-- to encrypt them with the master key.
|
|
||||||
DO $$ BEGIN
|
DO $$ BEGIN
|
||||||
IF EXISTS (
|
IF EXISTS (
|
||||||
SELECT 1 FROM information_schema.columns
|
SELECT 1 FROM information_schema.columns
|
||||||
@@ -79,6 +85,26 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
|
|||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_audit_log_created ON audit_log(created_at DESC);
|
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);
|
CREATE INDEX IF NOT EXISTS idx_audit_log_ns_kind ON audit_log(namespace, kind);
|
||||||
|
|
||||||
|
-- History table: snapshot of secrets before each write operation.
|
||||||
|
-- Supports rollback to any prior version via `secrets rollback`.
|
||||||
|
CREATE TABLE IF NOT EXISTS secrets_history (
|
||||||
|
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
|
secret_id UUID NOT NULL,
|
||||||
|
namespace VARCHAR(64) NOT NULL,
|
||||||
|
kind VARCHAR(64) NOT NULL,
|
||||||
|
name VARCHAR(256) NOT NULL,
|
||||||
|
version BIGINT NOT NULL,
|
||||||
|
action VARCHAR(16) NOT NULL,
|
||||||
|
tags TEXT[] NOT NULL DEFAULT '{}',
|
||||||
|
metadata JSONB NOT NULL DEFAULT '{}',
|
||||||
|
encrypted BYTEA NOT NULL DEFAULT '\x',
|
||||||
|
actor VARCHAR(128) NOT NULL DEFAULT '',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_history_secret_id ON secrets_history(secret_id, version DESC);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_history_ns_kind_name ON secrets_history(namespace, kind, name, version DESC);
|
||||||
"#,
|
"#,
|
||||||
)
|
)
|
||||||
.execute(pool)
|
.execute(pool)
|
||||||
@@ -87,6 +113,47 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Snapshot parameters grouped to avoid too-many-arguments lint.
|
||||||
|
pub struct SnapshotParams<'a> {
|
||||||
|
pub secret_id: uuid::Uuid,
|
||||||
|
pub namespace: &'a str,
|
||||||
|
pub kind: &'a str,
|
||||||
|
pub name: &'a str,
|
||||||
|
pub version: i64,
|
||||||
|
pub action: &'a str,
|
||||||
|
pub tags: &'a [String],
|
||||||
|
pub metadata: &'a serde_json::Value,
|
||||||
|
pub encrypted: &'a [u8],
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Snapshot a secrets row into `secrets_history` before a write operation.
|
||||||
|
/// `action` is one of "add", "update", "delete".
|
||||||
|
/// Failures are non-fatal (caller should warn).
|
||||||
|
pub async fn snapshot_history(
|
||||||
|
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||||
|
p: SnapshotParams<'_>,
|
||||||
|
) -> Result<()> {
|
||||||
|
let actor = std::env::var("USER").unwrap_or_default();
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO secrets_history \
|
||||||
|
(secret_id, namespace, kind, name, version, action, tags, metadata, encrypted, actor) \
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
|
||||||
|
)
|
||||||
|
.bind(p.secret_id)
|
||||||
|
.bind(p.namespace)
|
||||||
|
.bind(p.kind)
|
||||||
|
.bind(p.name)
|
||||||
|
.bind(p.version)
|
||||||
|
.bind(p.action)
|
||||||
|
.bind(p.tags)
|
||||||
|
.bind(p.metadata)
|
||||||
|
.bind(p.encrypted)
|
||||||
|
.bind(&actor)
|
||||||
|
.execute(&mut **tx)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Load the Argon2id salt from the database.
|
/// Load the Argon2id salt from the database.
|
||||||
/// Returns None if not yet initialized.
|
/// Returns None if not yet initialized.
|
||||||
pub async fn load_argon2_salt(pool: &PgPool) -> Result<Option<Vec<u8>>> {
|
pub async fn load_argon2_salt(pool: &PgPool) -> Result<Option<Vec<u8>>> {
|
||||||
|
|||||||
342
src/main.rs
342
src/main.rs
@@ -18,20 +18,26 @@ use output::resolve_output_mode;
|
|||||||
version,
|
version,
|
||||||
about = "Secrets & config manager backed by PostgreSQL — optimised for AI agents",
|
about = "Secrets & config manager backed by PostgreSQL — optimised for AI agents",
|
||||||
after_help = "QUICK START:
|
after_help = "QUICK START:
|
||||||
# First time setup (run once per device)
|
# 1. Configure database (once per device)
|
||||||
|
secrets config set-db \"postgres://postgres:<password>@<host>:<port>/secrets\"
|
||||||
|
|
||||||
|
# 2. Initialize master key (once per device)
|
||||||
secrets init
|
secrets init
|
||||||
|
|
||||||
# Discover what namespaces / kinds exist
|
# Discover what namespaces / kinds exist
|
||||||
secrets search --summary --limit 20
|
secrets search --summary --limit 20
|
||||||
|
|
||||||
# Precise lookup (JSON output for easy parsing)
|
# Precise lookup (JSON output for easy parsing)
|
||||||
secrets search -n refining --kind service --name gitea -o json --show-secrets
|
secrets search -n refining --kind service --name gitea -o json
|
||||||
|
|
||||||
# Extract a single field value directly
|
# Extract a single metadata field directly
|
||||||
secrets search -n refining --kind service --name gitea -f secret.token
|
secrets search -n refining --kind service --name gitea -f metadata.url
|
||||||
|
|
||||||
# Pipe-friendly (non-TTY defaults to json-compact automatically)
|
# Pipe-friendly (non-TTY defaults to json-compact automatically)
|
||||||
secrets search -n refining --kind service | jq '.[].name'"
|
secrets search -n refining --kind service | jq '.[].name'
|
||||||
|
|
||||||
|
# Inject secrets into environment variables when you really need them
|
||||||
|
secrets inject -n refining --kind service --name gitea"
|
||||||
)]
|
)]
|
||||||
struct Cli {
|
struct Cli {
|
||||||
/// Database URL, overrides saved config (one-time override)
|
/// Database URL, overrides saved config (one-time override)
|
||||||
@@ -52,7 +58,12 @@ enum Commands {
|
|||||||
///
|
///
|
||||||
/// Prompts for a master password, derives a key with Argon2id, and stores
|
/// Prompts for a master password, derives a key with Argon2id, and stores
|
||||||
/// it in the OS Keychain. Use the same password on every device.
|
/// it in the OS Keychain. Use the same password on every device.
|
||||||
#[command(after_help = "EXAMPLES:
|
///
|
||||||
|
/// NOTE: Run `secrets config set-db <URL>` first if database is not configured.
|
||||||
|
#[command(after_help = "PREREQUISITE:
|
||||||
|
Database must be configured first. Run: secrets config set-db <DATABASE_URL>
|
||||||
|
|
||||||
|
EXAMPLES:
|
||||||
# First device: generates a new Argon2id salt and stores master key
|
# First device: generates a new Argon2id salt and stores master key
|
||||||
secrets init
|
secrets init
|
||||||
|
|
||||||
@@ -60,12 +71,6 @@ enum Commands {
|
|||||||
secrets init")]
|
secrets init")]
|
||||||
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.
|
/// Add or update a record (upsert). Use -m for plaintext metadata, -s for secrets.
|
||||||
#[command(after_help = "EXAMPLES:
|
#[command(after_help = "EXAMPLES:
|
||||||
# Add a server
|
# Add a server
|
||||||
@@ -127,19 +132,19 @@ enum Commands {
|
|||||||
# Fuzzy keyword search (matches name, namespace, kind, tags, metadata)
|
# Fuzzy keyword search (matches name, namespace, kind, tags, metadata)
|
||||||
secrets search -q mqtt
|
secrets search -q mqtt
|
||||||
|
|
||||||
# Extract a single field value (implies --show-secrets for secret.*)
|
# Extract a single metadata field value
|
||||||
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
|
||||||
|
|
||||||
# Multiple fields at once
|
# Multiple fields at once
|
||||||
secrets search -n refining --kind service --name gitea \\
|
secrets search -n refining --kind service --name gitea \\
|
||||||
-f metadata.url -f metadata.default_org -f secret.token
|
-f metadata.url -f metadata.default_org
|
||||||
|
|
||||||
# Full JSON output with secrets revealed (ideal for AI parsing)
|
# Export metadata as env vars (single record only)
|
||||||
secrets search -n refining --kind service --name gitea -o json --show-secrets
|
secrets search -n refining --kind service --name gitea -o env
|
||||||
|
|
||||||
# Export as env vars (source-able; single record only)
|
# Inject decrypted secrets only when needed
|
||||||
secrets search -n refining --kind service --name gitea -o env --show-secrets
|
secrets inject -n refining --kind service --name gitea
|
||||||
|
secrets run -n refining --kind service --name gitea -- printenv
|
||||||
|
|
||||||
# Paginate large result sets
|
# Paginate large result sets
|
||||||
secrets search -n refining --summary --limit 10 --offset 0
|
secrets search -n refining --summary --limit 10 --offset 0
|
||||||
@@ -149,8 +154,7 @@ enum Commands {
|
|||||||
secrets search --sort updated --limit 5 --summary
|
secrets search --sort updated --limit 5 --summary
|
||||||
|
|
||||||
# Non-TTY / pipe: output is json-compact by default
|
# Non-TTY / pipe: output is json-compact by default
|
||||||
secrets search -n refining --kind service | jq '.[].name'
|
secrets search -n refining --kind service | jq '.[].name'")]
|
||||||
secrets search -n refining --kind service --name gitea --show-secrets | jq '.secrets.token'")]
|
|
||||||
Search {
|
Search {
|
||||||
/// Filter by namespace, e.g. refining, ricnsmart
|
/// Filter by namespace, e.g. refining, ricnsmart
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
@@ -161,16 +165,16 @@ enum Commands {
|
|||||||
/// Exact name filter, e.g. gitea, i-uf63f2uookgs5uxmrdyc
|
/// Exact name filter, e.g. gitea, i-uf63f2uookgs5uxmrdyc
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
name: Option<String>,
|
name: Option<String>,
|
||||||
/// Filter by tag, e.g. --tag aliyun
|
/// Filter by tag, e.g. --tag aliyun (repeatable for AND intersection)
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
tag: Option<String>,
|
tag: Vec<String>,
|
||||||
/// Fuzzy keyword (matches name, namespace, kind, tags, metadata text)
|
/// Fuzzy keyword (matches name, namespace, kind, tags, metadata text)
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
query: Option<String>,
|
query: Option<String>,
|
||||||
/// Reveal encrypted secret values in output
|
/// Deprecated: search never reveals secrets; use inject/run instead
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
show_secrets: bool,
|
show_secrets: bool,
|
||||||
/// Extract field value(s) directly: metadata.<key> or secret.<key> (repeatable)
|
/// Extract metadata field value(s) directly: metadata.<key> (repeatable)
|
||||||
#[arg(short = 'f', long = "field")]
|
#[arg(short = 'f', long = "field")]
|
||||||
fields: Vec<String>,
|
fields: Vec<String>,
|
||||||
/// Return lightweight summary only (namespace, kind, name, tags, desc, updated_at)
|
/// Return lightweight summary only (namespace, kind, name, tags, desc, updated_at)
|
||||||
@@ -207,6 +211,9 @@ enum Commands {
|
|||||||
/// Exact name of the record to delete
|
/// Exact name of the record to delete
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
name: String,
|
name: String,
|
||||||
|
/// Output format: text (default on TTY), json, json-compact
|
||||||
|
#[arg(short, long = "output")]
|
||||||
|
output: Option<String>,
|
||||||
},
|
},
|
||||||
|
|
||||||
/// Incrementally update an existing record (merge semantics; record must exist).
|
/// Incrementally update an existing record (merge semantics; record must exist).
|
||||||
@@ -258,6 +265,9 @@ enum Commands {
|
|||||||
/// Delete a secret field by key (repeatable)
|
/// Delete a secret field by key (repeatable)
|
||||||
#[arg(long = "remove-secret")]
|
#[arg(long = "remove-secret")]
|
||||||
remove_secrets: Vec<String>,
|
remove_secrets: Vec<String>,
|
||||||
|
/// Output format: text (default on TTY), json, json-compact
|
||||||
|
#[arg(short, long = "output")]
|
||||||
|
output: Option<String>,
|
||||||
},
|
},
|
||||||
|
|
||||||
/// Manage CLI configuration (database connection, etc.)
|
/// Manage CLI configuration (database connection, etc.)
|
||||||
@@ -274,6 +284,128 @@ enum Commands {
|
|||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
action: ConfigAction,
|
action: ConfigAction,
|
||||||
},
|
},
|
||||||
|
|
||||||
|
/// Show the change history for a record.
|
||||||
|
#[command(after_help = "EXAMPLES:
|
||||||
|
# Show last 20 versions for a service record
|
||||||
|
secrets history -n refining --kind service --name gitea
|
||||||
|
|
||||||
|
# Show last 5 versions
|
||||||
|
secrets history -n refining --kind service --name gitea --limit 5")]
|
||||||
|
History {
|
||||||
|
#[arg(short, long)]
|
||||||
|
namespace: String,
|
||||||
|
#[arg(long)]
|
||||||
|
kind: String,
|
||||||
|
#[arg(long)]
|
||||||
|
name: String,
|
||||||
|
/// Number of history entries to show [default: 20]
|
||||||
|
#[arg(long, default_value = "20")]
|
||||||
|
limit: u32,
|
||||||
|
/// Output format: text (default on TTY), json, json-compact
|
||||||
|
#[arg(short, long = "output")]
|
||||||
|
output: Option<String>,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// Roll back a record to a previous version.
|
||||||
|
#[command(after_help = "EXAMPLES:
|
||||||
|
# Roll back to the most recent snapshot (undo last change)
|
||||||
|
secrets rollback -n refining --kind service --name gitea
|
||||||
|
|
||||||
|
# Roll back to a specific version number
|
||||||
|
secrets rollback -n refining --kind service --name gitea --to-version 3")]
|
||||||
|
Rollback {
|
||||||
|
#[arg(short, long)]
|
||||||
|
namespace: String,
|
||||||
|
#[arg(long)]
|
||||||
|
kind: String,
|
||||||
|
#[arg(long)]
|
||||||
|
name: String,
|
||||||
|
/// Target version to restore. Omit to restore the most recent snapshot.
|
||||||
|
#[arg(long)]
|
||||||
|
to_version: Option<i64>,
|
||||||
|
/// Output format: text (default on TTY), json, json-compact
|
||||||
|
#[arg(short, long = "output")]
|
||||||
|
output: Option<String>,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// Print secrets as environment variables (stdout only, nothing persisted).
|
||||||
|
///
|
||||||
|
/// Outputs KEY=VALUE pairs for all matched records. Safe to pipe or eval.
|
||||||
|
#[command(after_help = "EXAMPLES:
|
||||||
|
# Print env vars for a single service
|
||||||
|
secrets inject -n refining --kind service --name gitea
|
||||||
|
|
||||||
|
# With a custom prefix
|
||||||
|
secrets inject -n refining --kind service --name gitea --prefix GITEA
|
||||||
|
|
||||||
|
# JSON output (all vars as a JSON object)
|
||||||
|
secrets inject -n refining --kind service --name gitea -o json
|
||||||
|
|
||||||
|
# Eval into current shell (use with caution)
|
||||||
|
eval $(secrets inject -n refining --kind service --name gitea)")]
|
||||||
|
Inject {
|
||||||
|
#[arg(short, long)]
|
||||||
|
namespace: Option<String>,
|
||||||
|
#[arg(long)]
|
||||||
|
kind: Option<String>,
|
||||||
|
#[arg(long)]
|
||||||
|
name: Option<String>,
|
||||||
|
#[arg(long)]
|
||||||
|
tag: Vec<String>,
|
||||||
|
/// Prefix to prepend to every variable name (uppercased automatically)
|
||||||
|
#[arg(long, default_value = "")]
|
||||||
|
prefix: String,
|
||||||
|
/// Output format: text/KEY=VALUE (default), json, json-compact
|
||||||
|
#[arg(short, long = "output")]
|
||||||
|
output: Option<String>,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// Run a command with secrets injected as environment variables.
|
||||||
|
///
|
||||||
|
/// Secrets are available only to the child process; the current shell
|
||||||
|
/// environment is not modified. The process exit code is propagated.
|
||||||
|
#[command(after_help = "EXAMPLES:
|
||||||
|
# Run a script with a single service's secrets injected
|
||||||
|
secrets run -n refining --kind service --name gitea -- ./deploy.sh
|
||||||
|
|
||||||
|
# Run with a tag filter (all matched records merged)
|
||||||
|
secrets run --tag production -- env | grep GITEA
|
||||||
|
|
||||||
|
# With prefix
|
||||||
|
secrets run -n refining --kind service --name gitea --prefix GITEA -- printenv")]
|
||||||
|
Run {
|
||||||
|
#[arg(short, long)]
|
||||||
|
namespace: Option<String>,
|
||||||
|
#[arg(long)]
|
||||||
|
kind: Option<String>,
|
||||||
|
#[arg(long)]
|
||||||
|
name: Option<String>,
|
||||||
|
#[arg(long)]
|
||||||
|
tag: Vec<String>,
|
||||||
|
/// Prefix to prepend to every variable name (uppercased automatically)
|
||||||
|
#[arg(long, default_value = "")]
|
||||||
|
prefix: String,
|
||||||
|
/// Command and arguments to execute with injected environment
|
||||||
|
#[arg(last = true, required = true)]
|
||||||
|
command: Vec<String>,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// Check for a newer version and update the binary in-place.
|
||||||
|
///
|
||||||
|
/// Downloads the latest release from Gitea and replaces the current binary.
|
||||||
|
/// No database connection or master key required.
|
||||||
|
#[command(after_help = "EXAMPLES:
|
||||||
|
# Check for updates only (no download)
|
||||||
|
secrets upgrade --check
|
||||||
|
|
||||||
|
# Download and install the latest version
|
||||||
|
secrets upgrade")]
|
||||||
|
Upgrade {
|
||||||
|
/// Only check if a newer version is available; do not download
|
||||||
|
#[arg(long)]
|
||||||
|
check: bool,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Subcommand)]
|
#[derive(Subcommand)]
|
||||||
@@ -304,15 +436,13 @@ async fn main() -> Result<()> {
|
|||||||
.init();
|
.init();
|
||||||
|
|
||||||
// config subcommand needs no database or master key
|
// config subcommand needs no database or master key
|
||||||
if let Commands::Config { action } = &cli.command {
|
if let Commands::Config { action } = cli.command {
|
||||||
let cmd_action = match action {
|
return commands::config::run(action).await;
|
||||||
ConfigAction::SetDb { url } => {
|
|
||||||
commands::config::ConfigAction::SetDb { url: url.clone() }
|
|
||||||
}
|
}
|
||||||
ConfigAction::Show => commands::config::ConfigAction::Show,
|
|
||||||
ConfigAction::Path => commands::config::ConfigAction::Path,
|
// upgrade needs no database or master key either
|
||||||
};
|
if let Commands::Upgrade { check } = cli.command {
|
||||||
return commands::config::run(cmd_action).await;
|
return commands::upgrade::run(check).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
let db_url = config::resolve_db_url(&cli.db_url)?;
|
let db_url = config::resolve_db_url(&cli.db_url)?;
|
||||||
@@ -320,19 +450,15 @@ async fn main() -> Result<()> {
|
|||||||
db::migrate(&pool).await?;
|
db::migrate(&pool).await?;
|
||||||
|
|
||||||
// init needs a pool but sets up the master key — handle before loading it
|
// init needs a pool but sets up the master key — handle before loading it
|
||||||
if let Commands::Init = &cli.command {
|
if let Commands::Init = cli.command {
|
||||||
return commands::init::run(&pool).await;
|
return commands::init::run(&pool).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
// All remaining commands require the master key from the OS Keychain
|
// All remaining commands require the master key from the OS Keychain,
|
||||||
let master_key = crypto::load_master_key()?;
|
// except delete which operates on plaintext metadata only.
|
||||||
|
|
||||||
match &cli.command {
|
match cli.command {
|
||||||
Commands::Init | Commands::Config { .. } => unreachable!(),
|
Commands::Init | Commands::Config { .. } | Commands::Upgrade { .. } => unreachable!(),
|
||||||
|
|
||||||
Commands::MigrateEncrypt => {
|
|
||||||
commands::migrate_encrypt::run(&pool, &master_key).await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Commands::Add {
|
Commands::Add {
|
||||||
namespace,
|
namespace,
|
||||||
@@ -343,18 +469,19 @@ async fn main() -> Result<()> {
|
|||||||
secrets,
|
secrets,
|
||||||
output,
|
output,
|
||||||
} => {
|
} => {
|
||||||
|
let master_key = crypto::load_master_key()?;
|
||||||
let _span =
|
let _span =
|
||||||
tracing::info_span!("cmd", command = "add", %namespace, %kind, %name).entered();
|
tracing::info_span!("cmd", command = "add", %namespace, %kind, %name).entered();
|
||||||
let out = resolve_output_mode(output.as_deref())?;
|
let out = resolve_output_mode(output.as_deref())?;
|
||||||
commands::add::run(
|
commands::add::run(
|
||||||
&pool,
|
&pool,
|
||||||
commands::add::AddArgs {
|
commands::add::AddArgs {
|
||||||
namespace,
|
namespace: &namespace,
|
||||||
kind,
|
kind: &kind,
|
||||||
name,
|
name: &name,
|
||||||
tags,
|
tags: &tags,
|
||||||
meta_entries: meta,
|
meta_entries: &meta,
|
||||||
secret_entries: secrets,
|
secret_entries: &secrets,
|
||||||
output: out,
|
output: out,
|
||||||
},
|
},
|
||||||
&master_key,
|
&master_key,
|
||||||
@@ -377,7 +504,6 @@ async fn main() -> Result<()> {
|
|||||||
output,
|
output,
|
||||||
} => {
|
} => {
|
||||||
let _span = tracing::info_span!("cmd", command = "search").entered();
|
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())?;
|
let out = resolve_output_mode(output.as_deref())?;
|
||||||
commands::search::run(
|
commands::search::run(
|
||||||
&pool,
|
&pool,
|
||||||
@@ -385,17 +511,16 @@ async fn main() -> Result<()> {
|
|||||||
namespace: namespace.as_deref(),
|
namespace: namespace.as_deref(),
|
||||||
kind: kind.as_deref(),
|
kind: kind.as_deref(),
|
||||||
name: name.as_deref(),
|
name: name.as_deref(),
|
||||||
tag: tag.as_deref(),
|
tags: &tag,
|
||||||
query: query.as_deref(),
|
query: query.as_deref(),
|
||||||
show_secrets: show,
|
show_secrets,
|
||||||
fields,
|
fields: &fields,
|
||||||
summary: *summary,
|
summary,
|
||||||
limit: *limit,
|
limit,
|
||||||
offset: *offset,
|
offset,
|
||||||
sort,
|
sort: &sort,
|
||||||
output: out,
|
output: out,
|
||||||
},
|
},
|
||||||
Some(&master_key),
|
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
@@ -404,10 +529,12 @@ async fn main() -> Result<()> {
|
|||||||
namespace,
|
namespace,
|
||||||
kind,
|
kind,
|
||||||
name,
|
name,
|
||||||
|
output,
|
||||||
} => {
|
} => {
|
||||||
let _span =
|
let _span =
|
||||||
tracing::info_span!("cmd", command = "delete", %namespace, %kind, %name).entered();
|
tracing::info_span!("cmd", command = "delete", %namespace, %kind, %name).entered();
|
||||||
commands::delete::run(&pool, namespace, kind, name).await?;
|
let out = resolve_output_mode(output.as_deref())?;
|
||||||
|
commands::delete::run(&pool, &namespace, &kind, &name, out).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Commands::Update {
|
Commands::Update {
|
||||||
@@ -420,21 +547,108 @@ async fn main() -> Result<()> {
|
|||||||
remove_meta,
|
remove_meta,
|
||||||
secrets,
|
secrets,
|
||||||
remove_secrets,
|
remove_secrets,
|
||||||
|
output,
|
||||||
} => {
|
} => {
|
||||||
|
let master_key = crypto::load_master_key()?;
|
||||||
let _span =
|
let _span =
|
||||||
tracing::info_span!("cmd", command = "update", %namespace, %kind, %name).entered();
|
tracing::info_span!("cmd", command = "update", %namespace, %kind, %name).entered();
|
||||||
|
let out = resolve_output_mode(output.as_deref())?;
|
||||||
commands::update::run(
|
commands::update::run(
|
||||||
&pool,
|
&pool,
|
||||||
commands::update::UpdateArgs {
|
commands::update::UpdateArgs {
|
||||||
|
namespace: &namespace,
|
||||||
|
kind: &kind,
|
||||||
|
name: &name,
|
||||||
|
add_tags: &add_tags,
|
||||||
|
remove_tags: &remove_tags,
|
||||||
|
meta_entries: &meta,
|
||||||
|
remove_meta: &remove_meta,
|
||||||
|
secret_entries: &secrets,
|
||||||
|
remove_secrets: &remove_secrets,
|
||||||
|
output: out,
|
||||||
|
},
|
||||||
|
&master_key,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Commands::History {
|
||||||
namespace,
|
namespace,
|
||||||
kind,
|
kind,
|
||||||
name,
|
name,
|
||||||
add_tags,
|
limit,
|
||||||
remove_tags,
|
output,
|
||||||
meta_entries: meta,
|
} => {
|
||||||
remove_meta,
|
let out = resolve_output_mode(output.as_deref())?;
|
||||||
secret_entries: secrets,
|
commands::rollback::list_history(&pool, &namespace, &kind, &name, limit, out).await?;
|
||||||
remove_secrets,
|
}
|
||||||
|
|
||||||
|
Commands::Rollback {
|
||||||
|
namespace,
|
||||||
|
kind,
|
||||||
|
name,
|
||||||
|
to_version,
|
||||||
|
output,
|
||||||
|
} => {
|
||||||
|
let master_key = crypto::load_master_key()?;
|
||||||
|
let out = resolve_output_mode(output.as_deref())?;
|
||||||
|
commands::rollback::run(
|
||||||
|
&pool,
|
||||||
|
commands::rollback::RollbackArgs {
|
||||||
|
namespace: &namespace,
|
||||||
|
kind: &kind,
|
||||||
|
name: &name,
|
||||||
|
to_version,
|
||||||
|
output: out,
|
||||||
|
},
|
||||||
|
&master_key,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Commands::Inject {
|
||||||
|
namespace,
|
||||||
|
kind,
|
||||||
|
name,
|
||||||
|
tag,
|
||||||
|
prefix,
|
||||||
|
output,
|
||||||
|
} => {
|
||||||
|
let master_key = crypto::load_master_key()?;
|
||||||
|
let out = resolve_output_mode(output.as_deref())?;
|
||||||
|
commands::run::run_inject(
|
||||||
|
&pool,
|
||||||
|
commands::run::InjectArgs {
|
||||||
|
namespace: namespace.as_deref(),
|
||||||
|
kind: kind.as_deref(),
|
||||||
|
name: name.as_deref(),
|
||||||
|
tags: &tag,
|
||||||
|
prefix: &prefix,
|
||||||
|
output: out,
|
||||||
|
},
|
||||||
|
&master_key,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Commands::Run {
|
||||||
|
namespace,
|
||||||
|
kind,
|
||||||
|
name,
|
||||||
|
tag,
|
||||||
|
prefix,
|
||||||
|
command,
|
||||||
|
} => {
|
||||||
|
let master_key = crypto::load_master_key()?;
|
||||||
|
commands::run::run_exec(
|
||||||
|
&pool,
|
||||||
|
commands::run::RunArgs {
|
||||||
|
namespace: namespace.as_deref(),
|
||||||
|
kind: kind.as_deref(),
|
||||||
|
name: name.as_deref(),
|
||||||
|
tags: &tag,
|
||||||
|
prefix: &prefix,
|
||||||
|
command: &command,
|
||||||
},
|
},
|
||||||
&master_key,
|
&master_key,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ pub struct Secret {
|
|||||||
/// AES-256-GCM ciphertext: nonce(12B) || ciphertext+tag
|
/// AES-256-GCM ciphertext: nonce(12B) || ciphertext+tag
|
||||||
/// Decrypt with crypto::decrypt_json() before use.
|
/// Decrypt with crypto::decrypt_json() before use.
|
||||||
pub encrypted: Vec<u8>,
|
pub encrypted: Vec<u8>,
|
||||||
|
pub version: i64,
|
||||||
pub created_at: DateTime<Utc>,
|
pub created_at: DateTime<Utc>,
|
||||||
pub updated_at: DateTime<Utc>,
|
pub updated_at: DateTime<Utc>,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use chrono::{DateTime, Local, Utc};
|
||||||
use std::io::IsTerminal;
|
use std::io::IsTerminal;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
|
||||||
@@ -45,3 +46,10 @@ pub fn resolve_output_mode(explicit: Option<&str>) -> anyhow::Result<OutputMode>
|
|||||||
Ok(OutputMode::JsonCompact)
|
Ok(OutputMode::JsonCompact)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Format a UTC timestamp for local human-readable output.
|
||||||
|
pub fn format_local_time(dt: DateTime<Utc>) -> String {
|
||||||
|
dt.with_timezone(&Local)
|
||||||
|
.format("%Y-%m-%d %H:%M:%S %:z")
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user