Compare commits
19 Commits
secrets-0.
...
secrets-0.
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1f7984d798 | ||
|
|
140162f39a | ||
|
|
535683b15c | ||
|
|
9620ff1923 | ||
|
|
e6db23bd6d | ||
|
|
c61c8292aa | ||
|
|
c1d86bc96d | ||
|
|
f87cf3fd20 | ||
|
|
1aef267bbd | ||
|
|
2ad1abe846 | ||
|
|
010001a4f4 | ||
|
|
0f7c151c89 | ||
|
|
a3a92e073f | ||
|
|
3d00b65f55 | ||
|
|
1acc2537b3 | ||
|
|
9a562be4e4 | ||
|
|
3203984fb4 | ||
|
|
52ee858fd7 | ||
|
|
3b338be2d2 |
@@ -24,120 +24,127 @@ env:
|
|||||||
RUST_BACKTRACE: short
|
RUST_BACKTRACE: short
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
# ========== 版本检查(只跑一次,供后续 job 共用)==========
|
|
||||||
version:
|
version:
|
||||||
name: 检查版本
|
name: 版本 & Release
|
||||||
runs-on: debian
|
runs-on: debian
|
||||||
outputs:
|
outputs:
|
||||||
version: ${{ steps.version.outputs.version }}
|
version: ${{ steps.ver.outputs.version }}
|
||||||
tag: ${{ steps.version.outputs.tag }}
|
tag: ${{ steps.ver.outputs.tag }}
|
||||||
tag_exists: ${{ steps.version.outputs.tag_exists }}
|
tag_exists: ${{ steps.ver.outputs.tag_exists }}
|
||||||
|
release_id: ${{ steps.release.outputs.release_id }}
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
- name: 检查版本
|
- name: 解析版本
|
||||||
id: version
|
id: ver
|
||||||
run: |
|
run: |
|
||||||
version=$(grep -m1 '^version' Cargo.toml | sed 's/.*"\(.*\)".*/\1/')
|
version=$(grep -m1 '^version' Cargo.toml | sed 's/.*"\(.*\)".*/\1/')
|
||||||
tag="secrets-${version}"
|
tag="secrets-${version}"
|
||||||
echo "version=${version}" >> $GITHUB_OUTPUT
|
previous_tag=$(git tag --list 'secrets-*' --sort=-v:refname | awk -v tag="$tag" '$0 != tag { print; exit }')
|
||||||
echo "tag=${tag}" >> $GITHUB_OUTPUT
|
|
||||||
|
echo "version=${version}" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "tag=${tag}" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "previous_tag=${previous_tag}" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
if git rev-parse "refs/tags/${tag}" >/dev/null 2>&1; then
|
if git rev-parse "refs/tags/${tag}" >/dev/null 2>&1; then
|
||||||
echo "tag_exists=true" >> $GITHUB_OUTPUT
|
echo "tag_exists=true" >> "$GITHUB_OUTPUT"
|
||||||
echo "版本 ${tag} 已存在"
|
echo "版本 ${tag} 已存在"
|
||||||
else
|
else
|
||||||
echo "tag_exists=false" >> $GITHUB_OUTPUT
|
echo "tag_exists=false" >> "$GITHUB_OUTPUT"
|
||||||
echo "将创建新版本 ${tag}"
|
echo "将创建新版本 ${tag}"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
- name: 创建 Tag
|
- name: 创建 Tag
|
||||||
if: steps.version.outputs.tag_exists == 'false'
|
if: steps.ver.outputs.tag_exists == 'false'
|
||||||
run: |
|
run: |
|
||||||
git config user.name "github-actions[bot]"
|
git config user.name "github-actions[bot]"
|
||||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||||
git tag -a "${{ steps.version.outputs.tag }}" -m "Release ${{ steps.version.outputs.tag }}"
|
git tag -a "${{ steps.ver.outputs.tag }}" -m "Release ${{ steps.ver.outputs.tag }}"
|
||||||
git push origin "${{ steps.version.outputs.tag }}"
|
git push origin "${{ steps.ver.outputs.tag }}"
|
||||||
|
|
||||||
# ========== 矩阵构建 ==========
|
- name: 解析或创建 Release
|
||||||
build:
|
id: release
|
||||||
name: Build (${{ matrix.target }})
|
env:
|
||||||
needs: version
|
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||||
continue-on-error: true # 某平台失败/超时不阻断其他平台和 notify
|
run: |
|
||||||
timeout-minutes: 30 # runner 不在线时 30 分钟后放弃
|
if [ -z "$RELEASE_TOKEN" ]; then
|
||||||
strategy:
|
echo "release_id=" >> "$GITHUB_OUTPUT"
|
||||||
fail-fast: false
|
exit 0
|
||||||
matrix:
|
fi
|
||||||
include:
|
|
||||||
- runner: debian
|
|
||||||
target: x86_64-unknown-linux-musl
|
|
||||||
archive_suffix: x86_64-linux-musl
|
|
||||||
os: linux
|
|
||||||
- runner: darwin-arm64
|
|
||||||
target: aarch64-apple-darwin
|
|
||||||
archive_suffix: aarch64-macos
|
|
||||||
os: macos
|
|
||||||
- runner: windows
|
|
||||||
target: x86_64-pc-windows-msvc
|
|
||||||
archive_suffix: x86_64-windows
|
|
||||||
os: windows
|
|
||||||
|
|
||||||
runs-on: ${{ matrix.runner }}
|
command -v jq >/dev/null 2>&1 || (sudo apt-get update -qq && sudo apt-get install -y -qq jq)
|
||||||
|
|
||||||
|
tag="${{ steps.ver.outputs.tag }}"
|
||||||
|
version="${{ steps.ver.outputs.version }}"
|
||||||
|
release_api="${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases"
|
||||||
|
|
||||||
|
http_code=$(curl -sS -o /tmp/release.json -w '%{http_code}' \
|
||||||
|
-H "Authorization: token $RELEASE_TOKEN" \
|
||||||
|
"${release_api}/tags/${tag}")
|
||||||
|
|
||||||
|
if [ "$http_code" = "200" ]; then
|
||||||
|
release_id=$(jq -r '.id // empty' /tmp/release.json)
|
||||||
|
if [ -n "$release_id" ]; then
|
||||||
|
echo "已找到现有 Release: ${release_id}"
|
||||||
|
echo "release_id=${release_id}" >> "$GITHUB_OUTPUT"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
previous_tag="${{ steps.ver.outputs.previous_tag }}"
|
||||||
|
if [ -n "$previous_tag" ]; then
|
||||||
|
changes=$(git log --pretty=format:'- %s (%h)' "${previous_tag}..HEAD")
|
||||||
|
else
|
||||||
|
changes=$(git log --pretty=format:'- %s (%h)')
|
||||||
|
fi
|
||||||
|
[ -z "$changes" ] && changes="- 首次发布"
|
||||||
|
|
||||||
|
body=$(printf '## 变更日志\n\n%s' "$changes")
|
||||||
|
|
||||||
|
payload=$(jq -n \
|
||||||
|
--arg tag "$tag" \
|
||||||
|
--arg name "${{ env.BINARY_NAME }} ${version}" \
|
||||||
|
--arg body "$body" \
|
||||||
|
'{tag_name: $tag, name: $name, body: $body, draft: true}')
|
||||||
|
|
||||||
|
http_code=$(curl -sS -o /tmp/create-release.json -w '%{http_code}' \
|
||||||
|
-H "Authorization: token $RELEASE_TOKEN" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-X POST "$release_api" \
|
||||||
|
-d "$payload")
|
||||||
|
|
||||||
|
if [ "$http_code" = "201" ] || [ "$http_code" = "200" ]; then
|
||||||
|
release_id=$(jq -r '.id // empty' /tmp/create-release.json)
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -n "$release_id" ]; then
|
||||||
|
echo "已创建草稿 Release: ${release_id}"
|
||||||
|
echo "release_id=${release_id}" >> "$GITHUB_OUTPUT"
|
||||||
|
else
|
||||||
|
echo "⚠ 创建 Release 失败 (HTTP ${http_code}),跳过产物上传"
|
||||||
|
cat /tmp/create-release.json 2>/dev/null || true
|
||||||
|
echo "release_id=" >> "$GITHUB_OUTPUT"
|
||||||
|
fi
|
||||||
|
|
||||||
|
check:
|
||||||
|
name: 质量检查 (fmt / clippy / test)
|
||||||
|
runs-on: debian
|
||||||
|
timeout-minutes: 10
|
||||||
steps:
|
steps:
|
||||||
# ========== 环境准备 ==========
|
- name: 安装 Rust
|
||||||
- name: 安装依赖 (Linux)
|
|
||||||
if: matrix.os == 'linux'
|
|
||||||
run: |
|
run: |
|
||||||
sudo apt-get update
|
if ! command -v cargo >/dev/null 2>&1; then
|
||||||
sudo apt-get install -y jq curl git pkg-config musl-tools binutils
|
|
||||||
|
|
||||||
if ! command -v cargo &>/dev/null; then
|
|
||||||
echo "安装 Rust 工具链..."
|
|
||||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
|
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
|
||||||
source "$HOME/.cargo/env"
|
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||||
rustup component add rustfmt clippy
|
|
||||||
fi
|
fi
|
||||||
|
source "$HOME/.cargo/env" 2>/dev/null || true
|
||||||
rustup target add ${{ matrix.target }}
|
|
||||||
echo "$HOME/.cargo/bin" >> $GITHUB_PATH
|
|
||||||
|
|
||||||
- name: 安装依赖 (macOS)
|
|
||||||
if: matrix.os == 'macos'
|
|
||||||
run: |
|
|
||||||
brew install jq
|
|
||||||
|
|
||||||
if ! command -v cargo &>/dev/null; then
|
|
||||||
echo "安装 Rust 工具链..."
|
|
||||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
|
|
||||||
source "$HOME/.cargo/env"
|
|
||||||
rustup component add rustfmt clippy
|
rustup component add rustfmt clippy
|
||||||
fi
|
|
||||||
|
|
||||||
rustup target add ${{ matrix.target }}
|
|
||||||
echo "$HOME/.cargo/bin" >> $GITHUB_PATH
|
|
||||||
|
|
||||||
- name: 安装依赖 (Windows)
|
|
||||||
if: matrix.os == 'windows'
|
|
||||||
shell: pwsh
|
|
||||||
run: |
|
|
||||||
# 检查 Rust 是否已安装
|
|
||||||
if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) {
|
|
||||||
Write-Host "安装 Rust 工具链..."
|
|
||||||
Invoke-WebRequest -Uri "https://win.rustup.rs/x86_64" -OutFile rustup-init.exe
|
|
||||||
.\rustup-init.exe -y --default-toolchain stable
|
|
||||||
Remove-Item rustup-init.exe
|
|
||||||
}
|
|
||||||
rustup component add rustfmt clippy
|
|
||||||
rustup target add ${{ matrix.target }}
|
|
||||||
|
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
# ========== Cargo 缓存 ==========
|
- name: 缓存 Cargo
|
||||||
- name: 缓存 Cargo 依赖
|
|
||||||
uses: actions/cache@v4
|
uses: actions/cache@v4
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
@@ -145,169 +152,288 @@ jobs:
|
|||||||
~/.cargo/registry/cache
|
~/.cargo/registry/cache
|
||||||
~/.cargo/git/db
|
~/.cargo/git/db
|
||||||
target
|
target
|
||||||
key: cargo-secrets-${{ matrix.target }}-${{ hashFiles('Cargo.lock') }}
|
key: cargo-check-${{ hashFiles('Cargo.lock') }}
|
||||||
restore-keys: |
|
restore-keys: |
|
||||||
cargo-secrets-${{ matrix.target }}-
|
cargo-check-
|
||||||
|
|
||||||
- name: 检查代码格式
|
- run: cargo fmt -- --check
|
||||||
if: matrix.os != 'windows'
|
- run: cargo clippy --locked -- -D warnings
|
||||||
run: cargo fmt -- --check
|
- run: cargo test --locked
|
||||||
|
|
||||||
- name: 检查代码格式 (Windows)
|
build-linux:
|
||||||
if: matrix.os == 'windows'
|
name: Build (x86_64-unknown-linux-musl)
|
||||||
shell: pwsh
|
needs: [version, check]
|
||||||
run: cargo fmt -- --check
|
|
||||||
|
|
||||||
- name: 运行 Clippy 检查
|
|
||||||
if: matrix.os != 'windows'
|
|
||||||
run: cargo clippy --release --target ${{ matrix.target }} -- -D warnings
|
|
||||||
|
|
||||||
- name: 运行 Clippy 检查 (Windows)
|
|
||||||
if: matrix.os == 'windows'
|
|
||||||
shell: pwsh
|
|
||||||
run: cargo clippy --release --target ${{ matrix.target }} -- -D warnings
|
|
||||||
|
|
||||||
- name: 构建
|
|
||||||
if: matrix.os != 'windows'
|
|
||||||
env:
|
|
||||||
GIT_TAG: ${{ needs.version.outputs.version }}
|
|
||||||
run: cargo build --release --target ${{ matrix.target }} --verbose
|
|
||||||
|
|
||||||
- name: 构建 (Windows)
|
|
||||||
if: matrix.os == 'windows'
|
|
||||||
shell: pwsh
|
|
||||||
env:
|
|
||||||
GIT_TAG: ${{ needs.version.outputs.version }}
|
|
||||||
run: cargo build --release --target ${{ matrix.target }} --verbose
|
|
||||||
|
|
||||||
- name: Strip 二进制 (Linux)
|
|
||||||
if: matrix.os == 'linux'
|
|
||||||
run: strip target/${{ matrix.target }}/release/${{ env.BINARY_NAME }}
|
|
||||||
|
|
||||||
- name: Strip 二进制 (macOS)
|
|
||||||
if: matrix.os == 'macos'
|
|
||||||
run: strip -x target/${{ matrix.target }}/release/${{ env.BINARY_NAME }}
|
|
||||||
|
|
||||||
# ========== 上传 Release 产物 ==========
|
|
||||||
- name: 上传 Release 产物 (Linux/macOS)
|
|
||||||
if: needs.version.outputs.tag_exists == 'false' && matrix.os != 'windows'
|
|
||||||
env:
|
|
||||||
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
|
||||||
run: |
|
|
||||||
[ -z "$RELEASE_TOKEN" ] && echo "跳过:未配置 RELEASE_TOKEN" && exit 0
|
|
||||||
|
|
||||||
tag="${{ needs.version.outputs.tag }}"
|
|
||||||
binary="target/${{ matrix.target }}/release/${{ env.BINARY_NAME }}"
|
|
||||||
archive="${{ env.BINARY_NAME }}-${tag}-${{ matrix.archive_suffix }}.tar.gz"
|
|
||||||
|
|
||||||
tar -czf "$archive" -C "$(dirname $binary)" "$(basename $binary)"
|
|
||||||
|
|
||||||
# 查找已有 Release(由首个完成的 job 创建,后续 job 直接上传)
|
|
||||||
release_url="${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases"
|
|
||||||
release_id=$(curl -sS -H "Authorization: token $RELEASE_TOKEN" \
|
|
||||||
"${release_url}/tags/${tag}" | jq -r '.id // empty')
|
|
||||||
|
|
||||||
if [ -z "$release_id" ]; then
|
|
||||||
release_id=$(curl -sS -H "Authorization: token $RELEASE_TOKEN" \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-X POST "$release_url" \
|
|
||||||
-d "{\"tag_name\": \"${tag}\", \"name\": \"${tag}\", \"body\": \"Release ${tag}\"}" \
|
|
||||||
| jq -r '.id')
|
|
||||||
fi
|
|
||||||
|
|
||||||
upload_url="${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${release_id}/assets"
|
|
||||||
curl -sS -H "Authorization: token $RELEASE_TOKEN" \
|
|
||||||
-F "attachment=@${archive}" \
|
|
||||||
"$upload_url"
|
|
||||||
|
|
||||||
echo "已上传: ${archive} → Release ${tag}"
|
|
||||||
|
|
||||||
- name: 上传 Release 产物 (Windows)
|
|
||||||
if: needs.version.outputs.tag_exists == 'false' && matrix.os == 'windows'
|
|
||||||
shell: pwsh
|
|
||||||
env:
|
|
||||||
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
|
||||||
run: |
|
|
||||||
if (-not $env:RELEASE_TOKEN) { Write-Host "跳过:未配置 RELEASE_TOKEN"; exit 0 }
|
|
||||||
|
|
||||||
$tag = "${{ needs.version.outputs.tag }}"
|
|
||||||
$binary = "target\${{ matrix.target }}\release\${{ env.BINARY_NAME }}.exe"
|
|
||||||
$archive = "${{ env.BINARY_NAME }}-${tag}-${{ matrix.archive_suffix }}.zip"
|
|
||||||
|
|
||||||
Compress-Archive -Path $binary -DestinationPath $archive
|
|
||||||
|
|
||||||
$headers = @{ "Authorization" = "token $env:RELEASE_TOKEN"; "Content-Type" = "application/json" }
|
|
||||||
$release_url = "${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases"
|
|
||||||
|
|
||||||
# 查找已有 Release
|
|
||||||
$existing = Invoke-RestMethod -Uri "${release_url}/tags/${tag}" -Headers $headers -ErrorAction SilentlyContinue
|
|
||||||
if ($existing.id) {
|
|
||||||
$release_id = $existing.id
|
|
||||||
} else {
|
|
||||||
$body = @{ tag_name = $tag; name = $tag; body = "Release ${tag}" } | ConvertTo-Json
|
|
||||||
$release_id = (Invoke-RestMethod -Uri $release_url -Method Post -Headers $headers -Body $body).id
|
|
||||||
}
|
|
||||||
|
|
||||||
$upload_url = "${release_url}/${release_id}/assets"
|
|
||||||
$upload_headers = @{ "Authorization" = "token $env:RELEASE_TOKEN" }
|
|
||||||
$form = @{ attachment = Get-Item $archive }
|
|
||||||
Invoke-RestMethod -Uri $upload_url -Method Post -Headers $upload_headers -Form $form
|
|
||||||
|
|
||||||
Write-Host "已上传: ${archive} → Release ${tag}"
|
|
||||||
|
|
||||||
# ========== 汇总通知 ==========
|
|
||||||
notify:
|
|
||||||
name: 发送通知
|
|
||||||
needs: [version, build]
|
|
||||||
if: always() && github.event_name == 'push'
|
|
||||||
runs-on: debian
|
runs-on: debian
|
||||||
|
timeout-minutes: 15
|
||||||
steps:
|
steps:
|
||||||
|
- name: 安装依赖
|
||||||
|
run: |
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y pkg-config musl-tools binutils curl
|
||||||
|
if ! command -v cargo >/dev/null 2>&1; then
|
||||||
|
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
|
||||||
|
fi
|
||||||
|
source "$HOME/.cargo/env" 2>/dev/null || true
|
||||||
|
rustup target add x86_64-unknown-linux-musl
|
||||||
|
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||||
|
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: 发送通知
|
- name: 缓存 Cargo
|
||||||
continue-on-error: true
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.cargo/registry/index
|
||||||
|
~/.cargo/registry/cache
|
||||||
|
~/.cargo/git/db
|
||||||
|
target
|
||||||
|
key: cargo-x86_64-unknown-linux-musl-${{ hashFiles('Cargo.lock') }}
|
||||||
|
restore-keys: |
|
||||||
|
cargo-x86_64-unknown-linux-musl-
|
||||||
|
|
||||||
|
- run: cargo build --release --locked --target x86_64-unknown-linux-musl
|
||||||
|
- run: strip target/x86_64-unknown-linux-musl/release/${{ env.BINARY_NAME }}
|
||||||
|
|
||||||
|
- name: 上传 Release 产物
|
||||||
|
if: needs.version.outputs.release_id != ''
|
||||||
|
env:
|
||||||
|
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||||
|
run: |
|
||||||
|
[ -z "$RELEASE_TOKEN" ] && exit 0
|
||||||
|
tag="${{ needs.version.outputs.tag }}"
|
||||||
|
bin="target/x86_64-unknown-linux-musl/release/${{ env.BINARY_NAME }}"
|
||||||
|
archive="${{ env.BINARY_NAME }}-${tag}-x86_64-linux-musl.tar.gz"
|
||||||
|
tar -czf "$archive" -C "$(dirname "$bin")" "$(basename "$bin")"
|
||||||
|
curl -fsS -H "Authorization: token $RELEASE_TOKEN" \
|
||||||
|
-F "attachment=@${archive}" \
|
||||||
|
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${{ needs.version.outputs.release_id }}/assets"
|
||||||
|
|
||||||
|
- name: 飞书通知
|
||||||
|
if: always()
|
||||||
env:
|
env:
|
||||||
WEBHOOK_URL: ${{ vars.WEBHOOK_URL }}
|
WEBHOOK_URL: ${{ vars.WEBHOOK_URL }}
|
||||||
run: |
|
run: |
|
||||||
[ -z "$WEBHOOK_URL" ] && exit 0
|
[ -z "$WEBHOOK_URL" ] && exit 0
|
||||||
|
command -v jq >/dev/null 2>&1 || (sudo apt-get update -qq && sudo apt-get install -y -qq jq)
|
||||||
|
tag="${{ needs.version.outputs.tag }}"
|
||||||
|
commit=$(git log -1 --pretty=format:"%s" 2>/dev/null || echo "N/A")
|
||||||
|
url="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}"
|
||||||
|
result="${{ job.status }}"
|
||||||
|
if [ "$result" = "success" ]; then icon="✅"; else icon="❌"; fi
|
||||||
|
msg="secrets linux 构建${icon}
|
||||||
|
版本:${tag}
|
||||||
|
提交:${commit}
|
||||||
|
作者:${{ github.actor }}
|
||||||
|
详情:${url}"
|
||||||
|
payload=$(jq -n --arg text "$msg" '{msg_type: "text", content: {text: $text}}')
|
||||||
|
curl -sS -H "Content-Type: application/json" -X POST -d "$payload" "$WEBHOOK_URL"
|
||||||
|
|
||||||
|
build-macos:
|
||||||
|
name: Build (aarch64-apple-darwin)
|
||||||
|
needs: [version, check]
|
||||||
|
runs-on: darwin-arm64
|
||||||
|
timeout-minutes: 15
|
||||||
|
steps:
|
||||||
|
- name: 安装依赖
|
||||||
|
run: |
|
||||||
|
if ! command -v cargo >/dev/null 2>&1; then
|
||||||
|
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
|
||||||
|
fi
|
||||||
|
source "$HOME/.cargo/env" 2>/dev/null || true
|
||||||
|
rustup target add aarch64-apple-darwin
|
||||||
|
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||||
|
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: 缓存 Cargo
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.cargo/registry/index
|
||||||
|
~/.cargo/registry/cache
|
||||||
|
~/.cargo/git/db
|
||||||
|
target
|
||||||
|
key: cargo-aarch64-apple-darwin-${{ hashFiles('Cargo.lock') }}
|
||||||
|
restore-keys: |
|
||||||
|
cargo-aarch64-apple-darwin-
|
||||||
|
|
||||||
|
- run: cargo build --release --locked --target aarch64-apple-darwin
|
||||||
|
- run: strip -x target/aarch64-apple-darwin/release/${{ env.BINARY_NAME }}
|
||||||
|
|
||||||
|
- name: 上传 Release 产物
|
||||||
|
if: needs.version.outputs.release_id != ''
|
||||||
|
env:
|
||||||
|
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||||
|
run: |
|
||||||
|
[ -z "$RELEASE_TOKEN" ] && exit 0
|
||||||
|
tag="${{ needs.version.outputs.tag }}"
|
||||||
|
bin="target/aarch64-apple-darwin/release/${{ env.BINARY_NAME }}"
|
||||||
|
archive="${{ env.BINARY_NAME }}-${tag}-aarch64-macos.tar.gz"
|
||||||
|
tar -czf "$archive" -C "$(dirname "$bin")" "$(basename "$bin")"
|
||||||
|
curl -fsS -H "Authorization: token $RELEASE_TOKEN" \
|
||||||
|
-F "attachment=@${archive}" \
|
||||||
|
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${{ needs.version.outputs.release_id }}/assets"
|
||||||
|
|
||||||
|
- name: 飞书通知
|
||||||
|
if: always()
|
||||||
|
env:
|
||||||
|
WEBHOOK_URL: ${{ vars.WEBHOOK_URL }}
|
||||||
|
run: |
|
||||||
|
[ -z "$WEBHOOK_URL" ] && exit 0
|
||||||
|
tag="${{ needs.version.outputs.tag }}"
|
||||||
|
commit=$(git log -1 --pretty=format:"%s" 2>/dev/null || echo "N/A")
|
||||||
|
url="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}"
|
||||||
|
result="${{ job.status }}"
|
||||||
|
if [ "$result" = "success" ]; then icon="✅"; else icon="❌"; fi
|
||||||
|
msg="secrets macOS 构建${icon}
|
||||||
|
版本:${tag}
|
||||||
|
提交:${commit}
|
||||||
|
作者:${{ github.actor }}
|
||||||
|
详情:${url}"
|
||||||
|
payload=$(python3 -c "import json,sys; print(json.dumps({'msg_type':'text','content':{'text':sys.argv[1]}}))" "$msg")
|
||||||
|
curl -sS -H "Content-Type: application/json" -X POST -d "$payload" "$WEBHOOK_URL"
|
||||||
|
|
||||||
|
build-windows:
|
||||||
|
name: Build (x86_64-pc-windows-msvc)
|
||||||
|
needs: [version, check]
|
||||||
|
runs-on: windows
|
||||||
|
timeout-minutes: 15
|
||||||
|
steps:
|
||||||
|
- name: 安装依赖
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) {
|
||||||
|
Invoke-WebRequest -Uri "https://win.rustup.rs/x86_64" -OutFile rustup-init.exe
|
||||||
|
.\rustup-init.exe -y --default-toolchain stable
|
||||||
|
Remove-Item rustup-init.exe
|
||||||
|
}
|
||||||
|
rustup target add x86_64-pc-windows-msvc
|
||||||
|
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: 缓存 Cargo
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.cargo/registry/index
|
||||||
|
~/.cargo/registry/cache
|
||||||
|
~/.cargo/git/db
|
||||||
|
target
|
||||||
|
key: cargo-x86_64-pc-windows-msvc-${{ hashFiles('Cargo.lock') }}
|
||||||
|
restore-keys: |
|
||||||
|
cargo-x86_64-pc-windows-msvc-
|
||||||
|
|
||||||
|
- name: 构建
|
||||||
|
shell: pwsh
|
||||||
|
run: cargo build --release --locked --target x86_64-pc-windows-msvc
|
||||||
|
|
||||||
|
- name: 上传 Release 产物
|
||||||
|
if: needs.version.outputs.release_id != ''
|
||||||
|
shell: pwsh
|
||||||
|
env:
|
||||||
|
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||||
|
run: |
|
||||||
|
if (-not $env:RELEASE_TOKEN) { exit 0 }
|
||||||
|
$tag = "${{ needs.version.outputs.tag }}"
|
||||||
|
$bin = "target\x86_64-pc-windows-msvc\release\${{ env.BINARY_NAME }}.exe"
|
||||||
|
$archive = "${{ env.BINARY_NAME }}-${tag}-x86_64-windows.zip"
|
||||||
|
Compress-Archive -Path $bin -DestinationPath $archive -Force
|
||||||
|
$url = "${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${{ needs.version.outputs.release_id }}/assets"
|
||||||
|
Invoke-RestMethod -Uri $url -Method Post `
|
||||||
|
-Headers @{ "Authorization" = "token $env:RELEASE_TOKEN" } `
|
||||||
|
-Form @{ attachment = Get-Item $archive }
|
||||||
|
|
||||||
|
- name: 飞书通知
|
||||||
|
if: always()
|
||||||
|
shell: pwsh
|
||||||
|
env:
|
||||||
|
WEBHOOK_URL: ${{ vars.WEBHOOK_URL }}
|
||||||
|
run: |
|
||||||
|
if (-not $env:WEBHOOK_URL) { exit 0 }
|
||||||
|
$tag = "${{ needs.version.outputs.tag }}"
|
||||||
|
$commit = (git log -1 --pretty=format:"%s" 2>$null) ?? "N/A"
|
||||||
|
$url = "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}"
|
||||||
|
$result = "${{ job.status }}"
|
||||||
|
$icon = if ($result -eq "success") { "✅" } else { "❌" }
|
||||||
|
$msg = "secrets windows 构建${icon}`n版本:${tag}`n提交:${commit}`n作者:${{ github.actor }}`n详情:${url}"
|
||||||
|
$payload = @{ msg_type = "text"; content = @{ text = $msg } } | ConvertTo-Json
|
||||||
|
Invoke-RestMethod -Uri $env:WEBHOOK_URL -Method Post `
|
||||||
|
-ContentType "application/json" -Body $payload
|
||||||
|
|
||||||
|
publish-release:
|
||||||
|
name: 发布草稿 Release
|
||||||
|
needs: [version, build-linux]
|
||||||
|
if: always() && needs.version.outputs.release_id != ''
|
||||||
|
runs-on: debian
|
||||||
|
timeout-minutes: 5
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: 发布草稿
|
||||||
|
env:
|
||||||
|
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||||
|
run: |
|
||||||
|
[ -z "$RELEASE_TOKEN" ] && exit 0
|
||||||
|
|
||||||
|
linux_r="${{ needs.build-linux.result }}"
|
||||||
|
if [ "$linux_r" != "success" ]; then
|
||||||
|
echo "Linux 构建未成功 (${linux_r}),保留草稿 Release"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
release_api="${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${{ needs.version.outputs.release_id }}"
|
||||||
|
http_code=$(curl -sS -o /tmp/publish-release.json -w '%{http_code}' \
|
||||||
|
-H "Authorization: token $RELEASE_TOKEN" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-X PATCH "$release_api" \
|
||||||
|
-d '{"draft":false}')
|
||||||
|
|
||||||
|
if [ "$http_code" != "200" ]; then
|
||||||
|
echo "发布草稿 Release 失败 (HTTP ${http_code})"
|
||||||
|
cat /tmp/publish-release.json 2>/dev/null || true
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "Release 已发布"
|
||||||
|
|
||||||
|
- name: 飞书汇总通知
|
||||||
|
if: always()
|
||||||
|
env:
|
||||||
|
WEBHOOK_URL: ${{ vars.WEBHOOK_URL }}
|
||||||
|
run: |
|
||||||
|
[ -z "$WEBHOOK_URL" ] && exit 0
|
||||||
|
command -v jq >/dev/null 2>&1 || (sudo apt-get update -qq && sudo apt-get install -y -qq jq)
|
||||||
|
|
||||||
tag="${{ needs.version.outputs.tag }}"
|
tag="${{ needs.version.outputs.tag }}"
|
||||||
tag_exists="${{ needs.version.outputs.tag_exists }}"
|
tag_exists="${{ needs.version.outputs.tag_exists }}"
|
||||||
build_result="${{ needs.build.result }}"
|
commit=$(git log -1 --pretty=format:"%s" 2>/dev/null || echo "N/A")
|
||||||
|
url="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}"
|
||||||
|
|
||||||
if [ "$build_result" = "success" ]; then
|
check_r="${{ needs.version.result }}"
|
||||||
status_text="构建成功 ✅"
|
linux_r="${{ needs.build-linux.result }}"
|
||||||
|
publish_r="${{ job.status }}"
|
||||||
|
|
||||||
|
icon() { case "$1" in success) echo "✅";; skipped) echo "⏭";; *) echo "❌";; esac; }
|
||||||
|
|
||||||
|
if [ "$linux_r" = "success" ] && [ "$publish_r" = "success" ]; then
|
||||||
|
status="发布成功 ✅"
|
||||||
|
elif [ "$linux_r" != "success" ]; then
|
||||||
|
status="构建失败 ❌"
|
||||||
else
|
else
|
||||||
status_text="构建失败 ❌"
|
status="发布失败 ❌"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
commit_title=$(git log -1 --pretty=format:"%s" 2>/dev/null || echo "N/A")
|
if [ "$tag_exists" = "false" ]; then
|
||||||
workflow_url="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}"
|
version_line="🆕 新版本 ${tag}"
|
||||||
|
|
||||||
if [ "$build_result" != "success" ]; then
|
|
||||||
payload=$(jq -n \
|
|
||||||
--arg title "${{ env.BINARY_NAME }} ${status_text}" \
|
|
||||||
--arg commit "$commit_title" \
|
|
||||||
--arg version "$tag" \
|
|
||||||
--arg author "${{ github.actor }}" \
|
|
||||||
--arg url "$workflow_url" \
|
|
||||||
'{msg_type: "text", content: {text: "\($title)\n提交:\($commit)\n版本:\($version)\n作者:\($author)\n详情:\($url)"}}')
|
|
||||||
elif [ "$tag_exists" = "false" ]; then
|
|
||||||
payload=$(jq -n \
|
|
||||||
--arg title "${{ env.BINARY_NAME }} ${status_text}" \
|
|
||||||
--arg commit "$commit_title" \
|
|
||||||
--arg version "$tag" \
|
|
||||||
--arg author "${{ github.actor }}" \
|
|
||||||
--arg url "$workflow_url" \
|
|
||||||
'{msg_type: "text", content: {text: "\($title)\n🆕 新版本已发布 (linux / macOS / windows)\n提交:\($commit)\n版本:\($version)\n作者:\($author)\n详情:\($url)"}}')
|
|
||||||
else
|
else
|
||||||
payload=$(jq -n \
|
version_line="🔄 重复构建 ${tag}"
|
||||||
--arg title "${{ env.BINARY_NAME }} ${status_text}" \
|
|
||||||
--arg commit "$commit_title" \
|
|
||||||
--arg version "$tag" \
|
|
||||||
--arg author "${{ github.actor }}" \
|
|
||||||
--arg url "$workflow_url" \
|
|
||||||
'{msg_type: "text", content: {text: "\($title)\n🔄 重复构建\n提交:\($commit)\n版本:\($version)\n作者:\($author)\n详情:\($url)"}}')
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
msg="secrets ${status}
|
||||||
|
${version_line}
|
||||||
|
linux $(icon "$linux_r") | Release $(icon "$publish_r")
|
||||||
|
提交:${commit}
|
||||||
|
作者:${{ github.actor }}
|
||||||
|
详情:${url}"
|
||||||
|
|
||||||
|
payload=$(jq -n --arg text "$msg" '{msg_type: "text", content: {text: $text}}')
|
||||||
curl -sS -H "Content-Type: application/json" -X POST -d "$payload" "$WEBHOOK_URL"
|
curl -sS -H "Content-Type: application/json" -X POST -d "$payload" "$WEBHOOK_URL"
|
||||||
|
|||||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -1,2 +1,4 @@
|
|||||||
/target
|
/target
|
||||||
.env
|
.env
|
||||||
|
.DS_Store
|
||||||
|
.cursor/
|
||||||
44
.vscode/tasks.json
vendored
44
.vscode/tasks.json
vendored
@@ -25,12 +25,36 @@
|
|||||||
"command": "./target/debug/secrets help add",
|
"command": "./target/debug/secrets help add",
|
||||||
"dependsOn": "build"
|
"dependsOn": "build"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"label": "cli: help config",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "./target/debug/secrets help config",
|
||||||
|
"dependsOn": "build"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "cli: config path",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "./target/debug/secrets config path",
|
||||||
|
"dependsOn": "build"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "cli: config show",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "./target/debug/secrets config show",
|
||||||
|
"dependsOn": "build"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"label": "test: search all",
|
"label": "test: search all",
|
||||||
"type": "shell",
|
"type": "shell",
|
||||||
"command": "./target/debug/secrets search",
|
"command": "./target/debug/secrets search",
|
||||||
"dependsOn": "build"
|
"dependsOn": "build"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"label": "test: search all (verbose)",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "./target/debug/secrets --verbose search",
|
||||||
|
"dependsOn": "build"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"label": "test: search by namespace (refining)",
|
"label": "test: search by namespace (refining)",
|
||||||
"type": "shell",
|
"type": "shell",
|
||||||
@@ -82,7 +106,7 @@
|
|||||||
{
|
{
|
||||||
"label": "test: search with secrets revealed",
|
"label": "test: search with secrets revealed",
|
||||||
"type": "shell",
|
"type": "shell",
|
||||||
"command": "./target/debug/secrets search -n refining --kind service --name gitea --show-secrets",
|
"command": "./target/debug/secrets search -n refining --kind service --show-secrets",
|
||||||
"dependsOn": "build"
|
"dependsOn": "build"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -97,6 +121,24 @@
|
|||||||
"command": "echo '--- add ---' && ./target/debug/secrets add -n test --kind demo --name roundtrip-test --tag test -m foo=bar -s password=secret123 && echo '--- search ---' && ./target/debug/secrets search -n test --show-secrets && echo '--- delete ---' && ./target/debug/secrets delete -n test --kind demo --name roundtrip-test && echo '--- verify deleted ---' && ./target/debug/secrets search -n test",
|
"command": "echo '--- add ---' && ./target/debug/secrets add -n test --kind demo --name roundtrip-test --tag test -m foo=bar -s password=secret123 && echo '--- search ---' && ./target/debug/secrets search -n test --show-secrets && echo '--- delete ---' && ./target/debug/secrets delete -n test --kind demo --name roundtrip-test && echo '--- verify deleted ---' && ./target/debug/secrets search -n test",
|
||||||
"dependsOn": "build"
|
"dependsOn": "build"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"label": "test: add + delete roundtrip (verbose)",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "echo '--- add (verbose) ---' && ./target/debug/secrets --verbose add -n test --kind demo --name roundtrip-verbose --tag test -m foo=bar -s password=secret123 && echo '--- delete (verbose) ---' && ./target/debug/secrets --verbose delete -n test --kind demo --name roundtrip-verbose",
|
||||||
|
"dependsOn": "build"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "test: update roundtrip",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "echo '--- add ---' && ./target/debug/secrets add -n test --kind demo --name update-test --tag v1 -m env=staging && echo '--- update ---' && ./target/debug/secrets update -n test --kind demo --name update-test --add-tag v2 --remove-tag v1 -m env=production && echo '--- verify ---' && ./target/debug/secrets search -n test --kind demo && echo '--- cleanup ---' && ./target/debug/secrets delete -n test --kind demo --name update-test",
|
||||||
|
"dependsOn": "build"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "test: audit log",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "echo '--- add ---' && ./target/debug/secrets add -n test --kind demo --name audit-test -m foo=bar -s key=val && echo '--- update ---' && ./target/debug/secrets update -n test --kind demo --name audit-test -m foo=baz && echo '--- delete ---' && ./target/debug/secrets delete -n test --kind demo --name audit-test && echo '--- audit log (last 5) ---' && psql $DATABASE_URL -c \"SELECT action, namespace, kind, name, actor, detail, created_at FROM audit_log ORDER BY created_at DESC LIMIT 5;\"",
|
||||||
|
"dependsOn": "build"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"label": "test: add with file secret",
|
"label": "test: add with file secret",
|
||||||
"type": "shell",
|
"type": "shell",
|
||||||
|
|||||||
292
AGENTS.md
292
AGENTS.md
@@ -7,27 +7,31 @@
|
|||||||
```
|
```
|
||||||
secrets/
|
secrets/
|
||||||
src/
|
src/
|
||||||
main.rs # CLI 入口,clap 命令定义,auto-migrate
|
main.rs # CLI 入口,clap 命令定义,auto-migrate,--verbose 全局参数
|
||||||
db.rs # PgPool 创建 + 建表/索引(幂等)
|
output.rs # OutputMode 枚举 + TTY 检测(TTY→text,非 TTY→json-compact)
|
||||||
|
config.rs # 配置读写:~/.config/secrets/config.toml(database_url)
|
||||||
|
db.rs # PgPool 创建 + 建表/索引(幂等,含 audit_log)
|
||||||
models.rs # Secret 结构体(sqlx::FromRow + serde)
|
models.rs # Secret 结构体(sqlx::FromRow + serde)
|
||||||
|
audit.rs # 审计写入:向 audit_log 表记录所有写操作
|
||||||
commands/
|
commands/
|
||||||
add.rs # add 命令:upsert,支持 --meta key=value / --secret key=@file
|
add.rs # add 命令:upsert,支持 --meta key=value / --secret key=@file / -o json
|
||||||
search.rs # search 命令:多条件动态查询
|
config.rs # config 命令:set-db / show / path(持久化 database_url)
|
||||||
|
search.rs # search 命令:多条件查询,-f/-o/--summary/--limit/--offset/--sort
|
||||||
delete.rs # delete 命令
|
delete.rs # delete 命令
|
||||||
|
update.rs # update 命令:增量更新(合并 tags/metadata/encrypted)
|
||||||
scripts/
|
scripts/
|
||||||
seed-data.sh # 从 refining/ricnsmart config.toml 导入全量数据
|
seed-data.sh # 从 refining/ricnsmart config.toml 导入全量数据
|
||||||
.gitea/workflows/
|
.gitea/workflows/
|
||||||
secrets.yml # CI:fmt + clippy + musl 构建 + Release 上传 + 飞书通知
|
secrets.yml # CI:fmt + clippy + musl 构建 + Release 上传 + 飞书通知
|
||||||
.vscode/tasks.json # 本地测试任务(build / search / add+delete roundtrip 等)
|
.vscode/tasks.json # 本地测试任务(build / config / search / add+delete / update / audit 等)
|
||||||
.env # DATABASE_URL(gitignore,不提交)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## 数据库
|
## 数据库
|
||||||
|
|
||||||
- **Host**: `47.117.131.22:5432`(阿里云上海 ECS,PostgreSQL 18 with io_uring)
|
- **Host**: `<host>:<port>`
|
||||||
- **Database**: `secrets`
|
- **Database**: `secrets`
|
||||||
- **连接串**: `postgres://postgres:<password>@47.117.131.22:5432/secrets`
|
- **连接串**: `postgres://postgres:<password>@<host>:<port>/secrets`
|
||||||
- **表**: 单张 `secrets` 表,首次连接自动建表(auto-migrate)
|
- **表**: `secrets`(主表)+ `audit_log`(审计表),首次连接自动建表(auto-migrate)
|
||||||
|
|
||||||
### 表结构
|
### 表结构
|
||||||
|
|
||||||
@@ -46,6 +50,21 @@ secrets (
|
|||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### audit_log 表结构
|
||||||
|
|
||||||
|
```sql
|
||||||
|
audit_log (
|
||||||
|
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
|
action VARCHAR(32) NOT NULL, -- 'add' | 'update' | 'delete'
|
||||||
|
namespace VARCHAR(64) NOT NULL,
|
||||||
|
kind VARCHAR(64) NOT NULL,
|
||||||
|
name VARCHAR(256) NOT NULL,
|
||||||
|
detail JSONB NOT NULL DEFAULT '{}', -- 变更摘要(tags/meta keys/secret keys,不含 value)
|
||||||
|
actor VARCHAR(128) NOT NULL DEFAULT '', -- 操作者($USER 环境变量)
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
### 字段职责划分
|
### 字段职责划分
|
||||||
|
|
||||||
| 字段 | 存什么 | 示例 |
|
| 字段 | 存什么 | 示例 |
|
||||||
@@ -57,33 +76,104 @@ secrets (
|
|||||||
| `metadata` | 明文非敏感信息 | `{"ip":"47.243.154.187","desc":"Grafana","domains":["..."]}` |
|
| `metadata` | 明文非敏感信息 | `{"ip":"47.243.154.187","desc":"Grafana","domains":["..."]}` |
|
||||||
| `encrypted` | 敏感凭据(MVP 阶段明文存储,后续对 value 加密) | `{"ssh_key":"-----BEGIN...","password":"..."}` |
|
| `encrypted` | 敏感凭据(MVP 阶段明文存储,后续对 value 加密) | `{"ssh_key":"-----BEGIN...","password":"..."}` |
|
||||||
|
|
||||||
## CLI 命令
|
## 数据库配置
|
||||||
|
|
||||||
|
首次使用需显式配置数据库连接,设置一次后在该设备上持久生效:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 查看版本
|
secrets config set-db "postgres://postgres:<password>@<host>:<port>/secrets"
|
||||||
secrets -V / --version
|
secrets config show # 查看当前配置(密码脱敏)
|
||||||
|
secrets config path # 打印配置文件路径
|
||||||
# 查看帮助
|
|
||||||
secrets -h / --help
|
|
||||||
secrets help <subcommand> # 子命令详细帮助,如 secrets help add
|
|
||||||
|
|
||||||
# 添加或更新记录(upsert)
|
|
||||||
secrets add -n <namespace> --kind <kind> --name <name> \
|
|
||||||
[--tag <tag>]... # 可重复
|
|
||||||
[-m key=value]... # --meta 明文字段,-m 是短标志
|
|
||||||
[-s key=value]... # --secret 敏感字段,value 以 @ 开头表示从文件读取
|
|
||||||
|
|
||||||
# 搜索(默认隐藏 encrypted 内容)
|
|
||||||
secrets search [-n <namespace>] [--kind <kind>] [--tag <tag>] [-q <keyword>] [--show-secrets]
|
|
||||||
# -q 匹配范围:name、namespace、kind、metadata 全文内容、tags
|
|
||||||
|
|
||||||
# 删除
|
|
||||||
secrets delete -n <namespace> --kind <kind> --name <name>
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 示例
|
配置文件:`~/.config/secrets/config.toml`,权限 0600。`--db-url` 参数可一次性覆盖。
|
||||||
|
|
||||||
|
## CLI 命令
|
||||||
|
|
||||||
|
### AI 使用主路径
|
||||||
|
|
||||||
|
**读取一律用 `search`,写入用 `add` / `update`,避免反复查帮助。**
|
||||||
|
|
||||||
|
输出格式规则:
|
||||||
|
- TTY(终端直接运行)→ 默认 `text`
|
||||||
|
- 非 TTY(管道/重定向/AI 调用)→ 自动 `json-compact`
|
||||||
|
- 显式 `-o json` → 美化 JSON
|
||||||
|
- 显式 `-o env` → KEY=VALUE(可 source)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### search — 发现与读取
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
# 参数说明(带典型值)
|
||||||
|
# -n / --namespace refining | ricnsmart
|
||||||
|
# --kind server | service
|
||||||
|
# --name gitea | i-uf63f2uookgs5uxmrdyc | mqtt
|
||||||
|
# --tag aliyun | hongkong | production
|
||||||
|
# -q / --query mqtt | grafana | gitea (模糊匹配 name/namespace/kind/tags/metadata)
|
||||||
|
# --show-secrets 不带值的 flag,显示 encrypted 字段内容
|
||||||
|
# -f / --field metadata.ip | metadata.url | secret.token | secret.ssh_key
|
||||||
|
# --summary 不带值的 flag,仅返回摘要(name/tags/desc/updated_at)
|
||||||
|
# --limit 20 | 50(默认 50)
|
||||||
|
# --offset 0 | 10 | 20(分页偏移)
|
||||||
|
# --sort name(默认)| updated | created
|
||||||
|
# -o / --output text | json | json-compact | env
|
||||||
|
|
||||||
|
# 发现概览(起步推荐)
|
||||||
|
secrets search --summary --limit 20
|
||||||
|
secrets search -n refining --summary --limit 20
|
||||||
|
secrets search --sort updated --limit 10 --summary
|
||||||
|
|
||||||
|
# 精确定位单条记录
|
||||||
|
secrets search -n refining --kind service --name gitea
|
||||||
|
secrets search -n refining --kind server --name i-uf63f2uookgs5uxmrdyc
|
||||||
|
|
||||||
|
# 精确定位并获取完整内容(含 secrets)
|
||||||
|
secrets search -n refining --kind service --name gitea -o json --show-secrets
|
||||||
|
|
||||||
|
# 直接提取字段值(最短路径,-f secret.* 自动解锁 secrets)
|
||||||
|
secrets search -n refining --kind service --name gitea -f secret.token
|
||||||
|
secrets search -n refining --kind service --name gitea -f metadata.url
|
||||||
|
secrets search -n refining --kind service --name gitea \
|
||||||
|
-f metadata.url -f metadata.default_org -f secret.token
|
||||||
|
|
||||||
|
# 模糊关键词搜索
|
||||||
|
secrets search -q mqtt
|
||||||
|
secrets search -q grafana
|
||||||
|
secrets search -q 47.117
|
||||||
|
|
||||||
|
# 按条件过滤
|
||||||
|
secrets search -n refining --kind service
|
||||||
|
secrets search -n ricnsmart --kind server
|
||||||
|
secrets search --tag hongkong
|
||||||
|
secrets search --tag aliyun --summary
|
||||||
|
|
||||||
|
# 分页
|
||||||
|
secrets search -n refining --summary --limit 10 --offset 0
|
||||||
|
secrets search -n refining --summary --limit 10 --offset 10
|
||||||
|
|
||||||
|
# 管道 / AI 调用(非 TTY 自动 json-compact)
|
||||||
|
secrets search -n refining --kind service | jq '.[].name'
|
||||||
|
secrets search -n refining --kind service --name gitea --show-secrets | jq '.secrets.token'
|
||||||
|
|
||||||
|
# 导出为 env 文件(单条记录)
|
||||||
|
secrets search -n refining --kind service --name gitea -o env --show-secrets \
|
||||||
|
> ~/.config/gitea/config.env
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### add — 新增或全量覆盖(upsert)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 参数说明(带典型值)
|
||||||
|
# -n / --namespace refining | ricnsmart
|
||||||
|
# --kind server | service
|
||||||
|
# --name gitea | i-uf63f2uookgs5uxmrdyc
|
||||||
|
# --tag aliyun | hongkong(可重复)
|
||||||
|
# -m / --meta ip=47.117.131.22 | desc="Aliyun ECS" | url=https://...(可重复)
|
||||||
|
# -s / --secret token=<value> | ssh_key=@./key.pem | password=secret123(可重复)
|
||||||
|
|
||||||
# 添加服务器
|
# 添加服务器
|
||||||
secrets add -n refining --kind server --name i-uf63f2uookgs5uxmrdyc \
|
secrets add -n refining --kind server --name i-uf63f2uookgs5uxmrdyc \
|
||||||
--tag aliyun --tag shanghai \
|
--tag aliyun --tag shanghai \
|
||||||
@@ -93,17 +183,101 @@ secrets add -n refining --kind server --name i-uf63f2uookgs5uxmrdyc \
|
|||||||
# 添加服务凭据
|
# 添加服务凭据
|
||||||
secrets add -n refining --kind service --name gitea \
|
secrets add -n refining --kind service --name gitea \
|
||||||
--tag gitea \
|
--tag gitea \
|
||||||
-m url=https://gitea.refining.dev \
|
-m url=https://gitea.refining.dev -m default_org=refining -m username=voson \
|
||||||
-s token=<token>
|
-s token=<token> -s runner_token=<runner_token>
|
||||||
|
|
||||||
# 搜索含 mqtt 的所有记录
|
# 从文件读取 token
|
||||||
secrets search -q mqtt
|
secrets add -n ricnsmart --kind service --name mqtt \
|
||||||
|
-m host=mqtt.ricnsmart.com -m port=1883 \
|
||||||
|
-s password=@./mqtt_password.txt
|
||||||
|
```
|
||||||
|
|
||||||
# 查看 refining 的全部服务配置(显示 secrets)
|
---
|
||||||
secrets search -n refining --kind service --show-secrets
|
|
||||||
|
|
||||||
# 按 tag 筛选
|
### update — 增量更新(记录必须已存在)
|
||||||
secrets search --tag hongkong
|
|
||||||
|
只有传入的字段才会变动,其余全部保留。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 参数说明(带典型值)
|
||||||
|
# -n / --namespace refining | ricnsmart
|
||||||
|
# --kind server | service
|
||||||
|
# --name gitea | i-uf63f2uookgs5uxmrdyc
|
||||||
|
# --add-tag production | backup(不影响已有 tag,可重复)
|
||||||
|
# --remove-tag staging | deprecated(可重复)
|
||||||
|
# -m / --meta ip=10.0.0.1 | desc="新描述"(新增或覆盖,可重复)
|
||||||
|
# --remove-meta old_port | legacy_key(删除 metadata 字段,可重复)
|
||||||
|
# -s / --secret token=<new> | ssh_key=@./new.pem(新增或覆盖,可重复)
|
||||||
|
# --remove-secret old_password | deprecated_key(删除 secret 字段,可重复)
|
||||||
|
|
||||||
|
# 更新单个 metadata 字段
|
||||||
|
secrets update -n refining --kind server --name i-uf63f2uookgs5uxmrdyc \
|
||||||
|
-m ip=10.0.0.1
|
||||||
|
|
||||||
|
# 轮换 token
|
||||||
|
secrets update -n refining --kind service --name gitea \
|
||||||
|
-s token=<new-token>
|
||||||
|
|
||||||
|
# 新增 tag 并轮换 token
|
||||||
|
secrets update -n refining --kind service --name gitea \
|
||||||
|
--add-tag production \
|
||||||
|
-s token=<new-token>
|
||||||
|
|
||||||
|
# 移除废弃字段
|
||||||
|
secrets update -n refining --kind service --name mqtt \
|
||||||
|
--remove-meta old_port --remove-secret old_password
|
||||||
|
|
||||||
|
# 移除 tag
|
||||||
|
secrets update -n refining --kind service --name gitea --remove-tag staging
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### delete — 删除记录
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 参数说明(带典型值)
|
||||||
|
# -n / --namespace refining | ricnsmart
|
||||||
|
# --kind server | service
|
||||||
|
# --name gitea | i-uf63f2uookgs5uxmrdyc(必须精确匹配)
|
||||||
|
|
||||||
|
# 删除服务凭据
|
||||||
|
secrets delete -n refining --kind service --name legacy-mqtt
|
||||||
|
|
||||||
|
# 删除服务器记录
|
||||||
|
secrets delete -n ricnsmart --kind server --name i-old-server-id
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### config — 配置管理
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 设置数据库连接(每台设备执行一次,之后永久生效)
|
||||||
|
secrets config set-db "postgres://postgres:<password>@<host>:<port>/secrets"
|
||||||
|
|
||||||
|
# 查看当前配置(密码脱敏)
|
||||||
|
secrets config show
|
||||||
|
|
||||||
|
# 打印配置文件路径
|
||||||
|
secrets config path
|
||||||
|
# 输出: /Users/<user>/.config/secrets/config.toml
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 全局参数
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# debug 日志(位于子命令之前)
|
||||||
|
secrets --verbose search -q mqtt
|
||||||
|
secrets -v add -n refining --kind service --name gitea -m url=xxx -s token=yyy
|
||||||
|
|
||||||
|
# 或通过环境变量精细控制
|
||||||
|
RUST_LOG=secrets=trace secrets search
|
||||||
|
|
||||||
|
# 一次性覆盖数据库连接
|
||||||
|
secrets --db-url "postgres://..." search -n refining
|
||||||
```
|
```
|
||||||
|
|
||||||
## 代码规范
|
## 代码规范
|
||||||
@@ -112,7 +286,42 @@ secrets search --tag hongkong
|
|||||||
- 异步:全程 `tokio`,数据库操作 `sqlx` async
|
- 异步:全程 `tokio`,数据库操作 `sqlx` async
|
||||||
- SQL:使用 `sqlx::query` / `sqlx::query_as` 绑定参数,禁止字符串拼接(搜索的动态 WHERE 子句除外,需使用参数绑定 `$1/$2`)
|
- SQL:使用 `sqlx::query` / `sqlx::query_as` 绑定参数,禁止字符串拼接(搜索的动态 WHERE 子句除外,需使用参数绑定 `$1/$2`)
|
||||||
- 新增 `kind` 类型时:只需在 `add` 调用时传入,无需改代码
|
- 新增 `kind` 类型时:只需在 `add` 调用时传入,无需改代码
|
||||||
- 字段命名:CLI 短标志 `-n`=namespace,`-m`=meta,`-s`=secret,`-q`=query
|
- 字段命名:CLI 短标志 `-n`=namespace,`-m`=meta,`-s`=secret,`-q`=query,`-v`=verbose,`-f`=field,`-o`=output
|
||||||
|
- 日志:用户可见输出用 `println!`;调试/运维信息用 `tracing::debug!`/`info!`/`warn!`/`error!`
|
||||||
|
- 审计:`add`/`update`/`delete` 成功后调用 `audit::log()`,写入 `audit_log` 表;失败只 warn 不中断
|
||||||
|
- 输出:读命令通过 `OutputMode` 支持 text/json/json-compact/env;写命令 `add` 同样支持 `-o json`
|
||||||
|
|
||||||
|
## 提交前检查(必须全部通过)
|
||||||
|
|
||||||
|
每次提交代码前,请在本地依次执行以下检查,**全部通过后再 push**:
|
||||||
|
|
||||||
|
### 1. 版本号(按需)
|
||||||
|
|
||||||
|
若本次改动需要发版,请先确认 `Cargo.toml` 中的 `version` 已提升,避免 CI 打出的 Tag 与已有版本重复。可通过 git tag 判断:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 查看当前 Cargo.toml 版本
|
||||||
|
grep '^version' Cargo.toml
|
||||||
|
|
||||||
|
# 查看是否已存在该版本对应的 tag(CI 使用格式 secrets-<version>)
|
||||||
|
git tag -l 'secrets-*'
|
||||||
|
```
|
||||||
|
|
||||||
|
若当前版本已被 tag(例如已有 `secrets-0.3.0` 且 `Cargo.toml` 仍为 `0.3.0`),则应在 `Cargo.toml` 中 bump 版本号后再提交,以便 CI 自动打新 Tag 并发布 Release。
|
||||||
|
|
||||||
|
### 2. 格式、Lint、测试
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo fmt -- --check # 格式检查(不通过则运行 cargo fmt 修复)
|
||||||
|
cargo clippy -- -D warnings # Lint 检查(消除所有 warning)
|
||||||
|
cargo test # 单元/集成测试
|
||||||
|
```
|
||||||
|
|
||||||
|
或一次性执行:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo fmt -- --check && cargo clippy -- -D warnings && cargo test
|
||||||
|
```
|
||||||
|
|
||||||
## CI/CD
|
## CI/CD
|
||||||
|
|
||||||
@@ -127,4 +336,7 @@ secrets search --tag hongkong
|
|||||||
|
|
||||||
| 变量 | 说明 |
|
| 变量 | 说明 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| `DATABASE_URL` | PostgreSQL 连接串,优先级高于 `--db-url` 参数 |
|
| `RUST_LOG` | 日志级别,如 `secrets=debug`、`secrets=trace`(默认 warn) |
|
||||||
|
| `USER` | 审计日志 actor 字段来源,Shell 自动设置,通常无需手动配置 |
|
||||||
|
|
||||||
|
数据库连接通过 `secrets config set-db` 持久化到 `~/.config/secrets/config.toml`,不支持环境变量。
|
||||||
|
|||||||
436
Cargo.lock
generated
436
Cargo.lock
generated
@@ -2,6 +2,15 @@
|
|||||||
# It is not intended for manual editing.
|
# It is not intended for manual editing.
|
||||||
version = 4
|
version = 4
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "aho-corasick"
|
||||||
|
version = "1.1.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
|
||||||
|
dependencies = [
|
||||||
|
"memchr",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "allocator-api2"
|
name = "allocator-api2"
|
||||||
version = "0.2.21"
|
version = "0.2.21"
|
||||||
@@ -227,16 +236,6 @@ version = "0.9.6"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
|
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "core-foundation"
|
|
||||||
version = "0.10.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
|
|
||||||
dependencies = [
|
|
||||||
"core-foundation-sys",
|
|
||||||
"libc",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "core-foundation-sys"
|
name = "core-foundation-sys"
|
||||||
version = "0.8.7"
|
version = "0.8.7"
|
||||||
@@ -315,6 +314,27 @@ dependencies = [
|
|||||||
"subtle",
|
"subtle",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "dirs"
|
||||||
|
version = "6.0.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"
|
||||||
|
dependencies = [
|
||||||
|
"dirs-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "dirs-sys"
|
||||||
|
version = "0.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"option-ext",
|
||||||
|
"redox_users",
|
||||||
|
"windows-sys 0.61.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "displaydoc"
|
name = "displaydoc"
|
||||||
version = "0.2.5"
|
version = "0.2.5"
|
||||||
@@ -379,12 +399,6 @@ 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]]
|
[[package]]
|
||||||
name = "find-msvc-tools"
|
name = "find-msvc-tools"
|
||||||
version = "0.1.9"
|
version = "0.1.9"
|
||||||
@@ -408,21 +422,6 @@ version = "0.1.5"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
|
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "foreign-types"
|
|
||||||
version = "0.3.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
|
|
||||||
dependencies = [
|
|
||||||
"foreign-types-shared",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "foreign-types-shared"
|
|
||||||
version = "0.1.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "form_urlencoded"
|
name = "form_urlencoded"
|
||||||
version = "1.2.2"
|
version = "1.2.2"
|
||||||
@@ -817,12 +816,6 @@ dependencies = [
|
|||||||
"vcpkg",
|
"vcpkg",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[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"
|
||||||
@@ -844,6 +837,15 @@ 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 = "matchers"
|
||||||
|
version = "0.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
|
||||||
|
dependencies = [
|
||||||
|
"regex-automata",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "md-5"
|
name = "md-5"
|
||||||
version = "0.10.6"
|
version = "0.10.6"
|
||||||
@@ -872,20 +874,12 @@ dependencies = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "native-tls"
|
name = "nu-ansi-term"
|
||||||
version = "0.2.18"
|
version = "0.50.3"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2"
|
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"libc",
|
"windows-sys 0.61.2",
|
||||||
"log",
|
|
||||||
"openssl",
|
|
||||||
"openssl-probe",
|
|
||||||
"openssl-sys",
|
|
||||||
"schannel",
|
|
||||||
"security-framework",
|
|
||||||
"security-framework-sys",
|
|
||||||
"tempfile",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -947,48 +941,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "openssl"
|
name = "option-ext"
|
||||||
version = "0.10.76"
|
version = "0.2.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "951c002c75e16ea2c65b8c7e4d3d51d5530d8dfa7d060b4776828c88cfb18ecf"
|
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
|
||||||
dependencies = [
|
|
||||||
"bitflags",
|
|
||||||
"cfg-if",
|
|
||||||
"foreign-types",
|
|
||||||
"libc",
|
|
||||||
"once_cell",
|
|
||||||
"openssl-macros",
|
|
||||||
"openssl-sys",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "openssl-macros"
|
|
||||||
version = "0.1.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "openssl-probe"
|
|
||||||
version = "0.2.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "openssl-sys"
|
|
||||||
version = "0.9.112"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "57d55af3b3e226502be1526dfdba67ab0e9c96fc293004e79576b2b9edb0dbdb"
|
|
||||||
dependencies = [
|
|
||||||
"cc",
|
|
||||||
"libc",
|
|
||||||
"pkg-config",
|
|
||||||
"vcpkg",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "parking"
|
name = "parking"
|
||||||
@@ -1173,6 +1129,48 @@ dependencies = [
|
|||||||
"bitflags",
|
"bitflags",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "redox_users"
|
||||||
|
version = "0.5.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac"
|
||||||
|
dependencies = [
|
||||||
|
"getrandom 0.2.17",
|
||||||
|
"libredox",
|
||||||
|
"thiserror",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "regex-automata"
|
||||||
|
version = "0.4.14"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
|
||||||
|
dependencies = [
|
||||||
|
"aho-corasick",
|
||||||
|
"memchr",
|
||||||
|
"regex-syntax",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "regex-syntax"
|
||||||
|
version = "0.8.10"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ring"
|
||||||
|
version = "0.17.14"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
"cfg-if",
|
||||||
|
"getrandom 0.2.17",
|
||||||
|
"libc",
|
||||||
|
"untrusted",
|
||||||
|
"windows-sys 0.52.0",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rsa"
|
name = "rsa"
|
||||||
version = "0.9.10"
|
version = "0.9.10"
|
||||||
@@ -1194,16 +1192,37 @@ dependencies = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustix"
|
name = "rustls"
|
||||||
version = "1.1.4"
|
version = "0.23.36"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
|
checksum = "c665f33d38cea657d9614f766881e4d510e0eda4239891eea56b4cadcf01801b"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bitflags",
|
"once_cell",
|
||||||
"errno",
|
"ring",
|
||||||
"libc",
|
"rustls-pki-types",
|
||||||
"linux-raw-sys",
|
"rustls-webpki",
|
||||||
"windows-sys 0.61.2",
|
"subtle",
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustls-pki-types"
|
||||||
|
version = "1.14.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"
|
||||||
|
dependencies = [
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustls-webpki"
|
||||||
|
version = "0.103.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53"
|
||||||
|
dependencies = [
|
||||||
|
"ring",
|
||||||
|
"rustls-pki-types",
|
||||||
|
"untrusted",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1218,15 +1237,6 @@ version = "1.0.23"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "schannel"
|
|
||||||
version = "0.1.29"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
|
|
||||||
dependencies = [
|
|
||||||
"windows-sys 0.61.2",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "scopeguard"
|
name = "scopeguard"
|
||||||
version = "1.2.0"
|
version = "1.2.0"
|
||||||
@@ -1235,43 +1245,22 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "secrets"
|
name = "secrets"
|
||||||
version = "0.1.0"
|
version = "0.4.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"chrono",
|
"chrono",
|
||||||
"clap",
|
"clap",
|
||||||
"dotenvy",
|
"dirs",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sqlx",
|
"sqlx",
|
||||||
"tokio",
|
"tokio",
|
||||||
"toml",
|
"toml",
|
||||||
|
"tracing",
|
||||||
|
"tracing-subscriber",
|
||||||
"uuid",
|
"uuid",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "security-framework"
|
|
||||||
version = "3.7.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
|
|
||||||
dependencies = [
|
|
||||||
"bitflags",
|
|
||||||
"core-foundation",
|
|
||||||
"core-foundation-sys",
|
|
||||||
"libc",
|
|
||||||
"security-framework-sys",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "security-framework-sys"
|
|
||||||
version = "2.17.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
|
|
||||||
dependencies = [
|
|
||||||
"core-foundation-sys",
|
|
||||||
"libc",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "semver"
|
name = "semver"
|
||||||
version = "1.0.27"
|
version = "1.0.27"
|
||||||
@@ -1364,6 +1353,15 @@ dependencies = [
|
|||||||
"digest",
|
"digest",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "sharded-slab"
|
||||||
|
version = "0.1.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
|
||||||
|
dependencies = [
|
||||||
|
"lazy_static",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "shlex"
|
name = "shlex"
|
||||||
version = "1.3.0"
|
version = "1.3.0"
|
||||||
@@ -1469,9 +1467,9 @@ dependencies = [
|
|||||||
"indexmap",
|
"indexmap",
|
||||||
"log",
|
"log",
|
||||||
"memchr",
|
"memchr",
|
||||||
"native-tls",
|
|
||||||
"once_cell",
|
"once_cell",
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
|
"rustls",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sha2",
|
"sha2",
|
||||||
@@ -1482,6 +1480,7 @@ dependencies = [
|
|||||||
"tracing",
|
"tracing",
|
||||||
"url",
|
"url",
|
||||||
"uuid",
|
"uuid",
|
||||||
|
"webpki-roots 0.26.11",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1682,19 +1681,6 @@ dependencies = [
|
|||||||
"syn",
|
"syn",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[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"
|
||||||
@@ -1715,6 +1701,15 @@ dependencies = [
|
|||||||
"syn",
|
"syn",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "thread_local"
|
||||||
|
version = "1.1.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tinystr"
|
name = "tinystr"
|
||||||
version = "0.8.2"
|
version = "0.8.2"
|
||||||
@@ -1848,6 +1843,36 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
|
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"once_cell",
|
"once_cell",
|
||||||
|
"valuable",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tracing-log"
|
||||||
|
version = "0.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
|
||||||
|
dependencies = [
|
||||||
|
"log",
|
||||||
|
"once_cell",
|
||||||
|
"tracing-core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tracing-subscriber"
|
||||||
|
version = "0.3.23"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
|
||||||
|
dependencies = [
|
||||||
|
"matchers",
|
||||||
|
"nu-ansi-term",
|
||||||
|
"once_cell",
|
||||||
|
"regex-automata",
|
||||||
|
"sharded-slab",
|
||||||
|
"smallvec",
|
||||||
|
"thread_local",
|
||||||
|
"tracing",
|
||||||
|
"tracing-core",
|
||||||
|
"tracing-log",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1889,6 +1914,12 @@ version = "0.2.6"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
|
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "untrusted"
|
||||||
|
version = "0.9.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "url"
|
name = "url"
|
||||||
version = "2.5.8"
|
version = "2.5.8"
|
||||||
@@ -1925,6 +1956,12 @@ dependencies = [
|
|||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "valuable"
|
||||||
|
version = "0.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "vcpkg"
|
name = "vcpkg"
|
||||||
version = "0.2.15"
|
version = "0.2.15"
|
||||||
@@ -2046,6 +2083,24 @@ dependencies = [
|
|||||||
"semver",
|
"semver",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "webpki-roots"
|
||||||
|
version = "0.26.11"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
|
||||||
|
dependencies = [
|
||||||
|
"webpki-roots 1.0.6",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "webpki-roots"
|
||||||
|
version = "1.0.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "22cfaf3c063993ff62e73cb4311efde4db1efb31ab78a3e5c457939ad5cc0bed"
|
||||||
|
dependencies = [
|
||||||
|
"rustls-pki-types",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "whoami"
|
name = "whoami"
|
||||||
version = "1.6.1"
|
version = "1.6.1"
|
||||||
@@ -2121,7 +2176,16 @@ version = "0.48.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
|
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"windows-targets",
|
"windows-targets 0.48.5",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-sys"
|
||||||
|
version = "0.52.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
|
||||||
|
dependencies = [
|
||||||
|
"windows-targets 0.52.6",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2139,13 +2203,29 @@ version = "0.48.5"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
|
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"windows_aarch64_gnullvm",
|
"windows_aarch64_gnullvm 0.48.5",
|
||||||
"windows_aarch64_msvc",
|
"windows_aarch64_msvc 0.48.5",
|
||||||
"windows_i686_gnu",
|
"windows_i686_gnu 0.48.5",
|
||||||
"windows_i686_msvc",
|
"windows_i686_msvc 0.48.5",
|
||||||
"windows_x86_64_gnu",
|
"windows_x86_64_gnu 0.48.5",
|
||||||
"windows_x86_64_gnullvm",
|
"windows_x86_64_gnullvm 0.48.5",
|
||||||
"windows_x86_64_msvc",
|
"windows_x86_64_msvc 0.48.5",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-targets"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
|
||||||
|
dependencies = [
|
||||||
|
"windows_aarch64_gnullvm 0.52.6",
|
||||||
|
"windows_aarch64_msvc 0.52.6",
|
||||||
|
"windows_i686_gnu 0.52.6",
|
||||||
|
"windows_i686_gnullvm",
|
||||||
|
"windows_i686_msvc 0.52.6",
|
||||||
|
"windows_x86_64_gnu 0.52.6",
|
||||||
|
"windows_x86_64_gnullvm 0.52.6",
|
||||||
|
"windows_x86_64_msvc 0.52.6",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2154,42 +2234,90 @@ version = "0.48.5"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
|
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_aarch64_gnullvm"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_aarch64_msvc"
|
name = "windows_aarch64_msvc"
|
||||||
version = "0.48.5"
|
version = "0.48.5"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
|
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_aarch64_msvc"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_i686_gnu"
|
name = "windows_i686_gnu"
|
||||||
version = "0.48.5"
|
version = "0.48.5"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
|
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_i686_gnu"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_i686_gnullvm"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_i686_msvc"
|
name = "windows_i686_msvc"
|
||||||
version = "0.48.5"
|
version = "0.48.5"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
|
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_i686_msvc"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_x86_64_gnu"
|
name = "windows_x86_64_gnu"
|
||||||
version = "0.48.5"
|
version = "0.48.5"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
|
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_x86_64_gnu"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_x86_64_gnullvm"
|
name = "windows_x86_64_gnullvm"
|
||||||
version = "0.48.5"
|
version = "0.48.5"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
|
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_x86_64_gnullvm"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_x86_64_msvc"
|
name = "windows_x86_64_msvc"
|
||||||
version = "0.48.5"
|
version = "0.48.5"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
|
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_x86_64_msvc"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "winnow"
|
name = "winnow"
|
||||||
version = "1.0.0"
|
version = "1.0.0"
|
||||||
|
|||||||
@@ -1,16 +1,18 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "secrets"
|
name = "secrets"
|
||||||
version = "0.1.0"
|
version = "0.4.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "1.0.102"
|
anyhow = "1.0.102"
|
||||||
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", "env"] }
|
||||||
dotenvy = "0.15.7"
|
dirs = "6.0.0"
|
||||||
serde = { version = "1.0.228", features = ["derive"] }
|
serde = { version = "1.0.228", features = ["derive"] }
|
||||||
serde_json = "1.0.149"
|
serde_json = "1.0.149"
|
||||||
sqlx = { version = "0.8.6", features = ["runtime-tokio", "tls-native-tls", "postgres", "uuid", "json", "chrono"] }
|
sqlx = { version = "0.8.6", features = ["runtime-tokio", "tls-rustls", "postgres", "uuid", "json", "chrono"] }
|
||||||
tokio = { version = "1.50.0", features = ["full"] }
|
tokio = { version = "1.50.0", features = ["full"] }
|
||||||
toml = "1.0.7"
|
toml = "1.0.7"
|
||||||
|
tracing = "0.1"
|
||||||
|
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||||
uuid = { version = "1.22.0", features = ["serde", "v4"] }
|
uuid = { version = "1.22.0", features = ["serde", "v4"] }
|
||||||
|
|||||||
150
README.md
150
README.md
@@ -11,55 +11,124 @@ cargo build --release
|
|||||||
# 或从 Release 页面下载预编译二进制
|
# 或从 Release 页面下载预编译二进制
|
||||||
```
|
```
|
||||||
|
|
||||||
配置数据库连接:
|
配置数据库连接(首次使用需执行一次,之后在该设备上持久生效):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
export DATABASE_URL=postgres://postgres:<password>@<host>:5432/secrets
|
secrets config set-db "postgres://postgres:<password>@<host>:<port>/secrets"
|
||||||
# 或在项目根目录创建 .env 文件写入上述变量
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## 使用
|
## AI Agent 快速指南
|
||||||
|
|
||||||
|
这个 CLI 以 AI 使用优先设计。核心路径只有一条:**读取用 `search`,写入用 `add` / `update`**。
|
||||||
|
|
||||||
|
### 第一步:发现有哪些数据
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 查看版本
|
# 列出所有记录摘要(默认最多 50 条,安全起步)
|
||||||
secrets -V
|
secrets search --summary --limit 20
|
||||||
secrets --version
|
|
||||||
|
|
||||||
# 查看帮助
|
# 按 namespace 过滤
|
||||||
|
secrets search -n refining --summary --limit 20
|
||||||
|
|
||||||
|
# 按最近更新排序
|
||||||
|
secrets search --sort updated --limit 10 --summary
|
||||||
|
```
|
||||||
|
|
||||||
|
`--summary` 只返回轻量字段(namespace、kind、name、tags、desc、updated_at),不含完整 metadata 和 secrets。
|
||||||
|
|
||||||
|
### 第二步:精确读取单条记录
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 精确定位(namespace + kind + name 三元组)
|
||||||
|
secrets search -n refining --kind service --name gitea
|
||||||
|
|
||||||
|
# 获取完整记录含 secrets(JSON 格式,AI 最易解析)
|
||||||
|
secrets search -n refining --kind service --name gitea -o json --show-secrets
|
||||||
|
|
||||||
|
# 直接提取单个字段值(最短路径)
|
||||||
|
secrets search -n refining --kind service --name gitea -f secret.token
|
||||||
|
secrets search -n refining --kind service --name gitea -f metadata.url
|
||||||
|
|
||||||
|
# 同时提取多个字段
|
||||||
|
secrets search -n refining --kind service --name gitea \
|
||||||
|
-f metadata.url -f metadata.default_org -f secret.token
|
||||||
|
```
|
||||||
|
|
||||||
|
`-f secret.*` 会自动解锁 secrets,无需额外加 `--show-secrets`。
|
||||||
|
|
||||||
|
### 输出格式
|
||||||
|
|
||||||
|
| 场景 | 推荐命令 |
|
||||||
|
|------|----------|
|
||||||
|
| AI 解析 / 管道处理 | `-o json` 或 `-o json-compact` |
|
||||||
|
| 写入 `.env` 文件 | `-o env --show-secrets` |
|
||||||
|
| 人类查看 | 默认 `text`(TTY 下自动启用) |
|
||||||
|
| 非 TTY(管道/重定向) | 自动 `json-compact` |
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 管道直接 jq 解析(非 TTY 自动 json-compact)
|
||||||
|
secrets search -n refining --kind service | jq '.[].name'
|
||||||
|
secrets search -n refining --kind service --name gitea --show-secrets | jq '.secrets.token'
|
||||||
|
|
||||||
|
# 导出为可 source 的 env 文件(单条记录)
|
||||||
|
secrets search -n refining --kind service --name gitea -o env --show-secrets \
|
||||||
|
> ~/.config/gitea/config.env
|
||||||
|
```
|
||||||
|
|
||||||
|
## 完整命令参考
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 查看帮助(包含各子命令 EXAMPLES)
|
||||||
secrets --help
|
secrets --help
|
||||||
secrets -h
|
secrets search --help
|
||||||
|
secrets add --help
|
||||||
|
secrets update --help
|
||||||
|
secrets delete --help
|
||||||
|
secrets config --help
|
||||||
|
|
||||||
# 查看子命令帮助
|
# ── search ──────────────────────────────────────────────────────────────────
|
||||||
secrets help add
|
secrets search --summary --limit 20 # 发现概览
|
||||||
secrets help search
|
secrets search -n refining --kind service # 按 namespace + kind
|
||||||
secrets help delete
|
secrets search -n refining --kind service --name gitea # 精确查找
|
||||||
|
secrets search -q mqtt # 关键词模糊搜索
|
||||||
|
secrets search --tag hongkong # 按 tag 过滤
|
||||||
|
secrets search -n refining --kind service --name gitea -f secret.token # 提取字段
|
||||||
|
secrets search -n refining --kind service --name gitea -o json --show-secrets # 完整 JSON
|
||||||
|
secrets search --sort updated --limit 10 --summary # 最近改动
|
||||||
|
secrets search -n refining --summary --limit 10 --offset 10 # 翻页
|
||||||
|
|
||||||
# 添加服务器
|
# ── add ──────────────────────────────────────────────────────────────────────
|
||||||
secrets add -n refining --kind server --name my-server \
|
secrets add -n refining --kind server --name my-server \
|
||||||
--tag aliyun --tag shanghai \
|
--tag aliyun --tag shanghai \
|
||||||
-m ip=1.2.3.4 -m desc="My Server" \
|
-m ip=47.117.131.22 -m desc="Aliyun Shanghai ECS" \
|
||||||
-s username=root \
|
-s username=root -s ssh_key=@./keys/server.pem
|
||||||
-s ssh_key=@./keys/my.pem
|
|
||||||
|
|
||||||
# 添加服务凭据
|
|
||||||
secrets add -n refining --kind service --name gitea \
|
secrets add -n refining --kind service --name gitea \
|
||||||
-m url=https://gitea.example.com \
|
--tag gitea \
|
||||||
|
-m url=https://gitea.refining.dev -m default_org=refining \
|
||||||
-s token=<token>
|
-s token=<token>
|
||||||
|
|
||||||
# 搜索(默认隐藏敏感字段)
|
# ── update ───────────────────────────────────────────────────────────────────
|
||||||
secrets search
|
secrets update -n refining --kind server --name my-server -m ip=10.0.0.1
|
||||||
secrets search -n refining --kind server
|
secrets update -n refining --kind service --name gitea --add-tag production -s token=<new>
|
||||||
secrets search --tag hongkong
|
secrets update -n refining --kind service --name mqtt --remove-meta old_port --remove-secret old_key
|
||||||
secrets search -q mqtt # 关键词匹配 name / metadata / tags
|
|
||||||
secrets search -n refining --kind service --name gitea --show-secrets
|
|
||||||
|
|
||||||
# 删除
|
# ── delete ───────────────────────────────────────────────────────────────────
|
||||||
secrets delete -n refining --kind server --name my-server
|
secrets delete -n refining --kind service --name legacy-mqtt
|
||||||
|
|
||||||
|
# ── config ───────────────────────────────────────────────────────────────────
|
||||||
|
secrets config set-db "postgres://postgres:<password>@<host>:<port>/secrets"
|
||||||
|
secrets config show # 密码脱敏展示
|
||||||
|
secrets config path # 打印配置文件路径
|
||||||
|
|
||||||
|
# ── 调试 ──────────────────────────────────────────────────────────────────────
|
||||||
|
secrets --verbose search -q mqtt
|
||||||
|
RUST_LOG=secrets=trace secrets search
|
||||||
```
|
```
|
||||||
|
|
||||||
## 数据模型
|
## 数据模型
|
||||||
|
|
||||||
单张 `secrets` 表,首次连接自动建表。
|
单张 `secrets` 表,首次连接自动建表;同时自动创建 `audit_log` 表,记录所有写操作。
|
||||||
|
|
||||||
| 字段 | 说明 |
|
| 字段 | 说明 |
|
||||||
|------|------|
|
|------|------|
|
||||||
@@ -72,17 +141,34 @@ secrets delete -n refining --kind server --name my-server
|
|||||||
|
|
||||||
`-m` / `--meta` 写入 `metadata`,`-s` / `--secret` 写入 `encrypted`,`value=@file` 从文件读取内容。
|
`-m` / `--meta` 写入 `metadata`,`-s` / `--secret` 写入 `encrypted`,`value=@file` 从文件读取内容。
|
||||||
|
|
||||||
|
## 审计日志
|
||||||
|
|
||||||
|
`add`、`update`、`delete` 操作成功后自动向 `audit_log` 表写入一条记录,包含操作类型、操作对象和变更摘要(不含 secret 值)。操作者取自 `$USER` 环境变量。
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- 查看最近 20 条审计记录
|
||||||
|
SELECT action, namespace, kind, name, actor, detail, created_at
|
||||||
|
FROM audit_log
|
||||||
|
ORDER BY created_at DESC
|
||||||
|
LIMIT 20;
|
||||||
|
```
|
||||||
|
|
||||||
## 项目结构
|
## 项目结构
|
||||||
|
|
||||||
```
|
```
|
||||||
src/
|
src/
|
||||||
main.rs # CLI 入口(clap)
|
main.rs # CLI 入口(clap),含各子命令 after_help 示例
|
||||||
db.rs # 连接池 + auto-migrate
|
output.rs # OutputMode 枚举 + TTY 检测
|
||||||
|
config.rs # 配置读写(~/.config/secrets/config.toml)
|
||||||
|
db.rs # 连接池 + auto-migrate(secrets + audit_log)
|
||||||
models.rs # Secret 结构体
|
models.rs # Secret 结构体
|
||||||
|
audit.rs # 审计日志写入(audit_log 表)
|
||||||
commands/
|
commands/
|
||||||
add.rs # upsert
|
add.rs # upsert,支持 -o json
|
||||||
search.rs # 多条件查询
|
config.rs # config set-db/show/path
|
||||||
|
search.rs # 多条件查询,支持 -f/-o/--summary/--limit/--offset/--sort
|
||||||
delete.rs # 删除
|
delete.rs # 删除
|
||||||
|
update.rs # 增量更新(合并 tags/metadata/encrypted)
|
||||||
scripts/
|
scripts/
|
||||||
seed-data.sh # 导入 refining / ricnsmart 全量数据
|
seed-data.sh # 导入 refining / ricnsmart 全量数据
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -109,11 +109,10 @@ echo ""
|
|||||||
|
|
||||||
# 1. 创建 Secret: RELEASE_TOKEN
|
# 1. 创建 Secret: RELEASE_TOKEN
|
||||||
echo "1. 创建 Secret: RELEASE_TOKEN"
|
echo "1. 创建 Secret: RELEASE_TOKEN"
|
||||||
encoded=$(echo -n "$GITEA_TOKEN" | base64)
|
|
||||||
resp=$(curl -s -w "\n%{http_code}" -X PUT \
|
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\":\"${encoded}\"}" \
|
-d "{\"data\":\"${GITEA_TOKEN}\"}" \
|
||||||
"${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')
|
||||||
|
|||||||
34
src/audit.rs
Normal file
34
src/audit.rs
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
use serde_json::Value;
|
||||||
|
use sqlx::PgPool;
|
||||||
|
|
||||||
|
/// Write an audit entry for a write operation. Failures are logged as warnings
|
||||||
|
/// and do not interrupt the main flow.
|
||||||
|
pub async fn log(
|
||||||
|
pool: &PgPool,
|
||||||
|
action: &str,
|
||||||
|
namespace: &str,
|
||||||
|
kind: &str,
|
||||||
|
name: &str,
|
||||||
|
detail: Value,
|
||||||
|
) {
|
||||||
|
let actor = std::env::var("USER").unwrap_or_default();
|
||||||
|
let result: Result<_, sqlx::Error> = sqlx::query(
|
||||||
|
"INSERT INTO audit_log (action, namespace, kind, name, detail, actor) \
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6)",
|
||||||
|
)
|
||||||
|
.bind(action)
|
||||||
|
.bind(namespace)
|
||||||
|
.bind(kind)
|
||||||
|
.bind(name)
|
||||||
|
.bind(&detail)
|
||||||
|
.bind(&actor)
|
||||||
|
.execute(pool)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
if let Err(e) = result {
|
||||||
|
tracing::warn!(error = %e, "failed to write audit log");
|
||||||
|
} else {
|
||||||
|
tracing::debug!(action, namespace, kind, name, actor, "audit logged");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use serde_json::{Map, Value};
|
use serde_json::{Map, Value, json};
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
|
|
||||||
|
use crate::output::OutputMode;
|
||||||
|
|
||||||
/// Parse "key=value" entries. Value starting with '@' reads from file.
|
/// Parse "key=value" entries. Value starting with '@' reads from file.
|
||||||
fn parse_kv(entry: &str) -> Result<(String, String)> {
|
pub(crate) fn parse_kv(entry: &str) -> Result<(String, String)> {
|
||||||
let (key, raw_val) = entry.split_once('=').ok_or_else(|| {
|
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 or key=@file",
|
||||||
@@ -31,17 +33,21 @@ fn build_json(entries: &[String]) -> Result<Value> {
|
|||||||
Ok(Value::Object(map))
|
Ok(Value::Object(map))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn run(
|
pub struct AddArgs<'a> {
|
||||||
pool: &PgPool,
|
pub namespace: &'a str,
|
||||||
namespace: &str,
|
pub kind: &'a str,
|
||||||
kind: &str,
|
pub name: &'a str,
|
||||||
name: &str,
|
pub tags: &'a [String],
|
||||||
tags: &[String],
|
pub meta_entries: &'a [String],
|
||||||
meta_entries: &[String],
|
pub secret_entries: &'a [String],
|
||||||
secret_entries: &[String],
|
pub output: OutputMode,
|
||||||
) -> Result<()> {
|
}
|
||||||
let metadata = build_json(meta_entries)?;
|
|
||||||
let encrypted = build_json(secret_entries)?;
|
pub async fn run(pool: &PgPool, args: AddArgs<'_>) -> Result<()> {
|
||||||
|
let metadata = build_json(args.meta_entries)?;
|
||||||
|
let encrypted = build_json(args.secret_entries)?;
|
||||||
|
|
||||||
|
tracing::debug!(args.namespace, args.kind, args.name, "upserting record");
|
||||||
|
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
r#"
|
r#"
|
||||||
@@ -55,32 +61,69 @@ pub async fn run(
|
|||||||
updated_at = NOW()
|
updated_at = NOW()
|
||||||
"#,
|
"#,
|
||||||
)
|
)
|
||||||
.bind(namespace)
|
.bind(args.namespace)
|
||||||
.bind(kind)
|
.bind(args.kind)
|
||||||
.bind(name)
|
.bind(args.name)
|
||||||
.bind(tags)
|
.bind(args.tags)
|
||||||
.bind(&metadata)
|
.bind(&metadata)
|
||||||
.bind(&encrypted)
|
.bind(&encrypted)
|
||||||
.execute(pool)
|
.execute(pool)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
println!("Added: [{}/{}] {}", namespace, kind, name);
|
let meta_keys: Vec<&str> = args
|
||||||
if !tags.is_empty() {
|
.meta_entries
|
||||||
println!(" tags: {}", tags.join(", "));
|
|
||||||
}
|
|
||||||
if !meta_entries.is_empty() {
|
|
||||||
let keys: Vec<&str> = meta_entries
|
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
|
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
|
||||||
.collect();
|
.collect();
|
||||||
println!(" metadata: {}", keys.join(", "));
|
let secret_keys: Vec<&str> = args
|
||||||
}
|
.secret_entries
|
||||||
if !secret_entries.is_empty() {
|
|
||||||
let keys: Vec<&str> = secret_entries
|
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
|
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
|
||||||
.collect();
|
.collect();
|
||||||
println!(" secrets: {}", keys.join(", "));
|
|
||||||
|
crate::audit::log(
|
||||||
|
pool,
|
||||||
|
"add",
|
||||||
|
args.namespace,
|
||||||
|
args.kind,
|
||||||
|
args.name,
|
||||||
|
json!({
|
||||||
|
"tags": args.tags,
|
||||||
|
"meta_keys": meta_keys,
|
||||||
|
"secret_keys": secret_keys,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let result_json = json!({
|
||||||
|
"action": "added",
|
||||||
|
"namespace": args.namespace,
|
||||||
|
"kind": args.kind,
|
||||||
|
"name": args.name,
|
||||||
|
"tags": args.tags,
|
||||||
|
"meta_keys": meta_keys,
|
||||||
|
"secret_keys": secret_keys,
|
||||||
|
});
|
||||||
|
|
||||||
|
match args.output {
|
||||||
|
OutputMode::Json => {
|
||||||
|
println!("{}", serde_json::to_string_pretty(&result_json)?);
|
||||||
|
}
|
||||||
|
OutputMode::JsonCompact => {
|
||||||
|
println!("{}", serde_json::to_string(&result_json)?);
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
println!("Added: [{}/{}] {}", args.namespace, args.kind, args.name);
|
||||||
|
if !args.tags.is_empty() {
|
||||||
|
println!(" tags: {}", args.tags.join(", "));
|
||||||
|
}
|
||||||
|
if !args.meta_entries.is_empty() {
|
||||||
|
println!(" metadata: {}", meta_keys.join(", "));
|
||||||
|
}
|
||||||
|
if !args.secret_entries.is_empty() {
|
||||||
|
println!(" secrets: {}", secret_keys.join(", "));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
54
src/commands/config.rs
Normal file
54
src/commands/config.rs
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
use crate::config::{self, Config, config_path};
|
||||||
|
use anyhow::Result;
|
||||||
|
|
||||||
|
pub enum ConfigAction {
|
||||||
|
SetDb { url: String },
|
||||||
|
Show,
|
||||||
|
Path,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn run(action: ConfigAction) -> Result<()> {
|
||||||
|
match action {
|
||||||
|
ConfigAction::SetDb { url } => {
|
||||||
|
let cfg = Config {
|
||||||
|
database_url: Some(url.clone()),
|
||||||
|
};
|
||||||
|
config::save_config(&cfg)?;
|
||||||
|
println!("✓ 数据库连接串已保存到: {}", config_path().display());
|
||||||
|
println!(" {}", mask_password(&url));
|
||||||
|
}
|
||||||
|
ConfigAction::Show => {
|
||||||
|
let cfg = config::load_config()?;
|
||||||
|
match cfg.database_url {
|
||||||
|
Some(url) => {
|
||||||
|
println!("database_url = {}", mask_password(&url));
|
||||||
|
println!("配置文件: {}", config_path().display());
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
println!("未配置数据库连接串。");
|
||||||
|
println!("请运行:secrets config set-db <DATABASE_URL>");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ConfigAction::Path => {
|
||||||
|
println!("{}", config_path().display());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 将 postgres://user:password@host/db 中的密码替换为 ***
|
||||||
|
fn mask_password(url: &str) -> String {
|
||||||
|
if let Some(at_pos) = url.rfind('@')
|
||||||
|
&& let Some(scheme_end) = url.find("://")
|
||||||
|
{
|
||||||
|
let prefix = &url[..scheme_end + 3];
|
||||||
|
let credentials = &url[scheme_end + 3..at_pos];
|
||||||
|
let rest = &url[at_pos..];
|
||||||
|
if let Some(colon_pos) = credentials.find(':') {
|
||||||
|
let user = &credentials[..colon_pos];
|
||||||
|
return format!("{}{}:***{}", prefix, user, rest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
url.to_string()
|
||||||
|
}
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
use serde_json::json;
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
|
|
||||||
pub async fn run(pool: &PgPool, namespace: &str, kind: &str, name: &str) -> Result<()> {
|
pub async fn run(pool: &PgPool, namespace: &str, kind: &str, name: &str) -> Result<()> {
|
||||||
let result = sqlx::query(
|
tracing::debug!(namespace, kind, name, "deleting record");
|
||||||
"DELETE FROM secrets WHERE namespace = $1 AND kind = $2 AND name = $3",
|
|
||||||
)
|
let result =
|
||||||
|
sqlx::query("DELETE FROM secrets WHERE namespace = $1 AND kind = $2 AND name = $3")
|
||||||
.bind(namespace)
|
.bind(namespace)
|
||||||
.bind(kind)
|
.bind(kind)
|
||||||
.bind(name)
|
.bind(name)
|
||||||
@@ -12,8 +14,10 @@ pub async fn run(pool: &PgPool, namespace: &str, kind: &str, name: &str) -> Resu
|
|||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if result.rows_affected() == 0 {
|
if result.rows_affected() == 0 {
|
||||||
|
tracing::warn!(namespace, kind, name, "record not found for deletion");
|
||||||
println!("Not found: [{}/{}] {}", namespace, kind, name);
|
println!("Not found: [{}/{}] {}", namespace, kind, name);
|
||||||
} else {
|
} else {
|
||||||
|
crate::audit::log(pool, "delete", namespace, kind, name, json!({})).await;
|
||||||
println!("Deleted: [{}/{}] {}", namespace, kind, name);
|
println!("Deleted: [{}/{}] {}", namespace, kind, name);
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
pub mod add;
|
pub mod add;
|
||||||
|
pub mod config;
|
||||||
pub mod delete;
|
pub mod delete;
|
||||||
pub mod search;
|
pub mod search;
|
||||||
|
pub mod update;
|
||||||
|
|||||||
@@ -1,36 +1,51 @@
|
|||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
use serde_json::{Value, json};
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
|
|
||||||
use crate::models::Secret;
|
use crate::models::Secret;
|
||||||
|
use crate::output::OutputMode;
|
||||||
|
|
||||||
pub async fn run(
|
pub struct SearchArgs<'a> {
|
||||||
pool: &PgPool,
|
pub namespace: Option<&'a str>,
|
||||||
namespace: Option<&str>,
|
pub kind: Option<&'a str>,
|
||||||
kind: Option<&str>,
|
pub name: Option<&'a str>,
|
||||||
tag: Option<&str>,
|
pub tag: Option<&'a str>,
|
||||||
query: Option<&str>,
|
pub query: Option<&'a str>,
|
||||||
show_secrets: bool,
|
pub show_secrets: bool,
|
||||||
) -> Result<()> {
|
pub fields: &'a [String],
|
||||||
|
pub summary: bool,
|
||||||
|
pub limit: u32,
|
||||||
|
pub offset: u32,
|
||||||
|
pub sort: &'a str,
|
||||||
|
pub output: OutputMode,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn run(pool: &PgPool, args: SearchArgs<'_>) -> Result<()> {
|
||||||
let mut conditions: Vec<String> = Vec::new();
|
let mut conditions: Vec<String> = Vec::new();
|
||||||
let mut idx: i32 = 1;
|
let mut idx: i32 = 1;
|
||||||
|
|
||||||
if namespace.is_some() {
|
if args.namespace.is_some() {
|
||||||
conditions.push(format!("namespace = ${}", idx));
|
conditions.push(format!("namespace = ${}", idx));
|
||||||
idx += 1;
|
idx += 1;
|
||||||
}
|
}
|
||||||
if kind.is_some() {
|
if args.kind.is_some() {
|
||||||
conditions.push(format!("kind = ${}", idx));
|
conditions.push(format!("kind = ${}", idx));
|
||||||
idx += 1;
|
idx += 1;
|
||||||
}
|
}
|
||||||
if tag.is_some() {
|
if args.name.is_some() {
|
||||||
|
conditions.push(format!("name = ${}", idx));
|
||||||
|
idx += 1;
|
||||||
|
}
|
||||||
|
if args.tag.is_some() {
|
||||||
conditions.push(format!("tags @> ARRAY[${}]", idx));
|
conditions.push(format!("tags @> ARRAY[${}]", idx));
|
||||||
idx += 1;
|
idx += 1;
|
||||||
}
|
}
|
||||||
if query.is_some() {
|
if args.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} OR namespace ILIKE ${i} OR kind ILIKE ${i} OR metadata::text ILIKE ${i} OR EXISTS (SELECT 1 FROM unnest(tags) t WHERE t ILIKE ${i}))",
|
||||||
i = idx
|
i = idx
|
||||||
));
|
));
|
||||||
|
idx += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
let where_clause = if conditions.is_empty() {
|
let where_clause = if conditions.is_empty() {
|
||||||
@@ -39,52 +54,171 @@ pub async fn run(
|
|||||||
format!("WHERE {}", conditions.join(" AND "))
|
format!("WHERE {}", conditions.join(" AND "))
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let order = match args.sort {
|
||||||
|
"updated" => "updated_at DESC",
|
||||||
|
"created" => "created_at DESC",
|
||||||
|
_ => "namespace, kind, name",
|
||||||
|
};
|
||||||
|
|
||||||
let sql = format!(
|
let sql = format!(
|
||||||
"SELECT * FROM secrets {} ORDER BY namespace, kind, name",
|
"SELECT * FROM secrets {} ORDER BY {} LIMIT ${} OFFSET ${}",
|
||||||
where_clause
|
where_clause,
|
||||||
|
order,
|
||||||
|
idx,
|
||||||
|
idx + 1
|
||||||
);
|
);
|
||||||
|
|
||||||
|
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) = namespace {
|
if let Some(v) = args.namespace {
|
||||||
q = q.bind(v);
|
q = q.bind(v);
|
||||||
}
|
}
|
||||||
if let Some(v) = kind {
|
if let Some(v) = args.kind {
|
||||||
q = q.bind(v);
|
q = q.bind(v);
|
||||||
}
|
}
|
||||||
if let Some(v) = tag {
|
if let Some(v) = args.name {
|
||||||
q = q.bind(v);
|
q = q.bind(v);
|
||||||
}
|
}
|
||||||
if let Some(v) = query {
|
if let Some(v) = args.tag {
|
||||||
|
q = q.bind(v);
|
||||||
|
}
|
||||||
|
if let Some(v) = args.query {
|
||||||
q = q.bind(format!("%{}%", v));
|
q = q.bind(format!("%{}%", v));
|
||||||
}
|
}
|
||||||
|
q = q.bind(args.limit as i64).bind(args.offset as i64);
|
||||||
|
|
||||||
let rows = q.fetch_all(pool).await?;
|
let rows = q.fetch_all(pool).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.show_secrets, args.summary))
|
||||||
|
.collect();
|
||||||
|
let out = if args.output == OutputMode::Json {
|
||||||
|
serde_json::to_string_pretty(&arr)?
|
||||||
|
} else {
|
||||||
|
serde_json::to_string(&arr)?
|
||||||
|
};
|
||||||
|
println!("{}", out);
|
||||||
|
}
|
||||||
|
OutputMode::Env => {
|
||||||
|
if rows.len() > 1 {
|
||||||
|
anyhow::bail!(
|
||||||
|
"env output requires exactly one record; got {}. Add more filters.",
|
||||||
|
rows.len()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if let Some(row) = rows.first() {
|
||||||
|
print_env(row, args.show_secrets)?;
|
||||||
|
} else {
|
||||||
|
eprintln!("No records found.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
OutputMode::Text => {
|
||||||
if rows.is_empty() {
|
if rows.is_empty() {
|
||||||
println!("No records found.");
|
println!("No records found.");
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
for row in &rows {
|
for row in &rows {
|
||||||
|
print_text(row, args.show_secrets, args.summary)?;
|
||||||
|
}
|
||||||
|
println!("{} record(s) found.", rows.len());
|
||||||
|
if rows.len() == args.limit as usize {
|
||||||
println!(
|
println!(
|
||||||
"[{}/{}] {}",
|
" (showing up to {}; use --offset {} to see more)",
|
||||||
row.namespace, row.kind, row.name,
|
args.limit,
|
||||||
|
args.offset + args.limit
|
||||||
);
|
);
|
||||||
println!(" id: {}", row.id);
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn to_json(row: &Secret, show_secrets: bool, summary: bool) -> Value {
|
||||||
|
if summary {
|
||||||
|
let desc = row
|
||||||
|
.metadata
|
||||||
|
.get("desc")
|
||||||
|
.or_else(|| row.metadata.get("url"))
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_string();
|
||||||
|
return json!({
|
||||||
|
"namespace": row.namespace,
|
||||||
|
"kind": row.kind,
|
||||||
|
"name": row.name,
|
||||||
|
"tags": row.tags,
|
||||||
|
"desc": desc,
|
||||||
|
"updated_at": row.updated_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let secrets_val = if show_secrets {
|
||||||
|
row.encrypted.clone()
|
||||||
|
} else {
|
||||||
|
let keys: Vec<&str> = row
|
||||||
|
.encrypted
|
||||||
|
.as_object()
|
||||||
|
.map(|m| m.keys().map(|k| k.as_str()).collect())
|
||||||
|
.unwrap_or_default();
|
||||||
|
json!({"_hidden_keys": keys})
|
||||||
|
};
|
||||||
|
|
||||||
|
json!({
|
||||||
|
"id": row.id,
|
||||||
|
"namespace": row.namespace,
|
||||||
|
"kind": row.kind,
|
||||||
|
"name": row.name,
|
||||||
|
"tags": row.tags,
|
||||||
|
"metadata": row.metadata,
|
||||||
|
"secrets": secrets_val,
|
||||||
|
"created_at": row.created_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
|
||||||
|
"updated_at": row.updated_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn print_text(row: &Secret, show_secrets: bool, summary: bool) -> Result<()> {
|
||||||
|
println!("[{}/{}] {}", row.namespace, row.kind, row.name);
|
||||||
|
if summary {
|
||||||
|
let desc = row
|
||||||
|
.metadata
|
||||||
|
.get("desc")
|
||||||
|
.or_else(|| row.metadata.get("url"))
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.unwrap_or("-");
|
||||||
if !row.tags.is_empty() {
|
if !row.tags.is_empty() {
|
||||||
println!(" tags: [{}]", row.tags.join(", "));
|
println!(" tags: [{}]", row.tags.join(", "));
|
||||||
}
|
}
|
||||||
|
println!(" desc: {}", desc);
|
||||||
let meta_obj = row.metadata.as_object();
|
println!(
|
||||||
if let Some(m) = meta_obj {
|
" updated: {}",
|
||||||
if !m.is_empty() {
|
row.updated_at.format("%Y-%m-%d %H:%M:%S UTC")
|
||||||
println!(" metadata: {}", serde_json::to_string_pretty(&row.metadata)?);
|
);
|
||||||
|
} else {
|
||||||
|
println!(" id: {}", row.id);
|
||||||
|
if !row.tags.is_empty() {
|
||||||
|
println!(" tags: [{}]", row.tags.join(", "));
|
||||||
}
|
}
|
||||||
|
if row.metadata.as_object().is_some_and(|m| !m.is_empty()) {
|
||||||
|
println!(
|
||||||
|
" metadata: {}",
|
||||||
|
serde_json::to_string_pretty(&row.metadata)?
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if show_secrets {
|
if show_secrets {
|
||||||
println!(" secrets: {}", serde_json::to_string_pretty(&row.encrypted)?);
|
println!(
|
||||||
|
" secrets: {}",
|
||||||
|
serde_json::to_string_pretty(&row.encrypted)?
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
let keys: Vec<String> = row
|
let keys: Vec<String> = row
|
||||||
.encrypted
|
.encrypted
|
||||||
@@ -92,13 +226,79 @@ pub async fn run(
|
|||||||
.map(|m| m.keys().cloned().collect())
|
.map(|m| m.keys().cloned().collect())
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
if !keys.is_empty() {
|
if !keys.is_empty() {
|
||||||
println!(" secrets: [{}] (--show-secrets to reveal)", keys.join(", "));
|
println!(
|
||||||
|
" secrets: [{}] (--show-secrets to reveal)",
|
||||||
|
keys.join(", ")
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
println!(
|
||||||
println!(" created: {}", row.created_at.format("%Y-%m-%d %H:%M:%S UTC"));
|
" created: {}",
|
||||||
|
row.created_at.format("%Y-%m-%d %H:%M:%S UTC")
|
||||||
|
);
|
||||||
|
}
|
||||||
println!();
|
println!();
|
||||||
}
|
|
||||||
println!("{} record(s) found.", rows.len());
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn print_env(row: &Secret, show_secrets: bool) -> Result<()> {
|
||||||
|
let prefix = row.name.to_uppercase().replace(['-', '.'], "_");
|
||||||
|
if let Some(meta) = row.metadata.as_object() {
|
||||||
|
for (k, v) in meta {
|
||||||
|
let key = format!("{}_{}", prefix, k.to_uppercase().replace('-', "_"));
|
||||||
|
println!("{}={}", key, v.as_str().unwrap_or(&v.to_string()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if show_secrets && let Some(enc) = row.encrypted.as_object() {
|
||||||
|
for (k, v) in enc {
|
||||||
|
let key = format!("{}_{}", prefix, k.to_uppercase().replace('-', "_"));
|
||||||
|
println!("{}={}", key, v.as_str().unwrap_or(&v.to_string()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extract one or more field paths like `metadata.url` or `secret.token`.
|
||||||
|
fn print_fields(rows: &[Secret], fields: &[String]) -> Result<()> {
|
||||||
|
for row in rows {
|
||||||
|
for field in fields {
|
||||||
|
let val = extract_field(row, field)?;
|
||||||
|
println!("{}", val);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extract_field(row: &Secret, field: &str) -> Result<String> {
|
||||||
|
let (section, key) = field.split_once('.').ok_or_else(|| {
|
||||||
|
anyhow::anyhow!(
|
||||||
|
"Invalid field path '{}'. Use metadata.<key> or secret.<key>",
|
||||||
|
field
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let obj = match section {
|
||||||
|
"metadata" | "meta" => &row.metadata,
|
||||||
|
"secret" | "secrets" | "encrypted" => &row.encrypted,
|
||||||
|
other => anyhow::bail!(
|
||||||
|
"Unknown field section '{}'. Use 'metadata' or 'secret'",
|
||||||
|
other
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
obj.get(key)
|
||||||
|
.and_then(|v| {
|
||||||
|
v.as_str()
|
||||||
|
.map(|s| s.to_string())
|
||||||
|
.or_else(|| Some(v.to_string()))
|
||||||
|
})
|
||||||
|
.ok_or_else(|| {
|
||||||
|
anyhow::anyhow!(
|
||||||
|
"Field '{}' not found in record [{}/{}/{}]",
|
||||||
|
field,
|
||||||
|
row.namespace,
|
||||||
|
row.kind,
|
||||||
|
row.name
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
169
src/commands/update.rs
Normal file
169
src/commands/update.rs
Normal file
@@ -0,0 +1,169 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
use serde_json::{Map, Value, json};
|
||||||
|
use sqlx::{FromRow, PgPool};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use super::add::parse_kv;
|
||||||
|
|
||||||
|
#[derive(FromRow)]
|
||||||
|
struct UpdateRow {
|
||||||
|
id: Uuid,
|
||||||
|
tags: Vec<String>,
|
||||||
|
metadata: Value,
|
||||||
|
encrypted: Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct UpdateArgs<'a> {
|
||||||
|
pub namespace: &'a str,
|
||||||
|
pub kind: &'a str,
|
||||||
|
pub name: &'a str,
|
||||||
|
pub add_tags: &'a [String],
|
||||||
|
pub remove_tags: &'a [String],
|
||||||
|
pub meta_entries: &'a [String],
|
||||||
|
pub remove_meta: &'a [String],
|
||||||
|
pub secret_entries: &'a [String],
|
||||||
|
pub remove_secrets: &'a [String],
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn run(pool: &PgPool, args: UpdateArgs<'_>) -> Result<()> {
|
||||||
|
let row: Option<UpdateRow> = sqlx::query_as(
|
||||||
|
r#"
|
||||||
|
SELECT id, tags, metadata, encrypted
|
||||||
|
FROM secrets
|
||||||
|
WHERE namespace = $1 AND kind = $2 AND name = $3
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.bind(args.namespace)
|
||||||
|
.bind(args.kind)
|
||||||
|
.bind(args.name)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let row = row.ok_or_else(|| {
|
||||||
|
anyhow::anyhow!(
|
||||||
|
"Not found: [{}/{}] {}. Use `add` to create it first.",
|
||||||
|
args.namespace,
|
||||||
|
args.kind,
|
||||||
|
args.name
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
// Merge tags
|
||||||
|
let mut tags: Vec<String> = row.tags;
|
||||||
|
for t in args.add_tags {
|
||||||
|
if !tags.contains(t) {
|
||||||
|
tags.push(t.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tags.retain(|t| !args.remove_tags.contains(t));
|
||||||
|
|
||||||
|
// Merge metadata
|
||||||
|
let mut meta_map: Map<String, Value> = match row.metadata {
|
||||||
|
Value::Object(m) => m,
|
||||||
|
_ => Map::new(),
|
||||||
|
};
|
||||||
|
for entry in args.meta_entries {
|
||||||
|
let (key, value) = parse_kv(entry)?;
|
||||||
|
meta_map.insert(key, Value::String(value));
|
||||||
|
}
|
||||||
|
for key in args.remove_meta {
|
||||||
|
meta_map.remove(key);
|
||||||
|
}
|
||||||
|
let metadata = Value::Object(meta_map);
|
||||||
|
|
||||||
|
// Merge encrypted
|
||||||
|
let mut enc_map: Map<String, Value> = match row.encrypted {
|
||||||
|
Value::Object(m) => m,
|
||||||
|
_ => Map::new(),
|
||||||
|
};
|
||||||
|
for entry in args.secret_entries {
|
||||||
|
let (key, value) = parse_kv(entry)?;
|
||||||
|
enc_map.insert(key, Value::String(value));
|
||||||
|
}
|
||||||
|
for key in args.remove_secrets {
|
||||||
|
enc_map.remove(key);
|
||||||
|
}
|
||||||
|
let encrypted = Value::Object(enc_map);
|
||||||
|
|
||||||
|
tracing::debug!(
|
||||||
|
namespace = args.namespace,
|
||||||
|
kind = args.kind,
|
||||||
|
name = args.name,
|
||||||
|
"updating record"
|
||||||
|
);
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
r#"
|
||||||
|
UPDATE secrets
|
||||||
|
SET tags = $1, metadata = $2, encrypted = $3, updated_at = NOW()
|
||||||
|
WHERE id = $4
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.bind(&tags)
|
||||||
|
.bind(metadata)
|
||||||
|
.bind(encrypted)
|
||||||
|
.bind(row.id)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let meta_keys: Vec<&str> = args
|
||||||
|
.meta_entries
|
||||||
|
.iter()
|
||||||
|
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
|
||||||
|
.collect();
|
||||||
|
let secret_keys: Vec<&str> = args
|
||||||
|
.secret_entries
|
||||||
|
.iter()
|
||||||
|
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
crate::audit::log(
|
||||||
|
pool,
|
||||||
|
"update",
|
||||||
|
args.namespace,
|
||||||
|
args.kind,
|
||||||
|
args.name,
|
||||||
|
json!({
|
||||||
|
"add_tags": args.add_tags,
|
||||||
|
"remove_tags": args.remove_tags,
|
||||||
|
"meta_keys": meta_keys,
|
||||||
|
"remove_meta": args.remove_meta,
|
||||||
|
"secret_keys": secret_keys,
|
||||||
|
"remove_secrets": args.remove_secrets,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
println!("Updated: [{}/{}] {}", args.namespace, args.kind, args.name);
|
||||||
|
|
||||||
|
if !args.add_tags.is_empty() {
|
||||||
|
println!(" +tags: {}", args.add_tags.join(", "));
|
||||||
|
}
|
||||||
|
if !args.remove_tags.is_empty() {
|
||||||
|
println!(" -tags: {}", args.remove_tags.join(", "));
|
||||||
|
}
|
||||||
|
if !args.meta_entries.is_empty() {
|
||||||
|
let keys: Vec<&str> = args
|
||||||
|
.meta_entries
|
||||||
|
.iter()
|
||||||
|
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
|
||||||
|
.collect();
|
||||||
|
println!(" +metadata: {}", keys.join(", "));
|
||||||
|
}
|
||||||
|
if !args.remove_meta.is_empty() {
|
||||||
|
println!(" -metadata: {}", args.remove_meta.join(", "));
|
||||||
|
}
|
||||||
|
if !args.secret_entries.is_empty() {
|
||||||
|
let keys: Vec<&str> = args
|
||||||
|
.secret_entries
|
||||||
|
.iter()
|
||||||
|
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
|
||||||
|
.collect();
|
||||||
|
println!(" +secrets: {}", keys.join(", "));
|
||||||
|
}
|
||||||
|
if !args.remove_secrets.is_empty() {
|
||||||
|
println!(" -secrets: {}", args.remove_secrets.join(", "));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
70
src/config.rs
Normal file
70
src/config.rs
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
use anyhow::{Context, Result};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::fs;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize, Default)]
|
||||||
|
pub struct Config {
|
||||||
|
pub database_url: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn config_dir() -> PathBuf {
|
||||||
|
dirs::config_dir()
|
||||||
|
.unwrap_or_else(|| PathBuf::from("~/.config"))
|
||||||
|
.join("secrets")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn config_path() -> PathBuf {
|
||||||
|
config_dir().join("config.toml")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load_config() -> Result<Config> {
|
||||||
|
let path = config_path();
|
||||||
|
if !path.exists() {
|
||||||
|
return Ok(Config::default());
|
||||||
|
}
|
||||||
|
let content = fs::read_to_string(&path)
|
||||||
|
.with_context(|| format!("读取配置文件失败: {}", path.display()))?;
|
||||||
|
let config: Config = toml::from_str(&content)
|
||||||
|
.with_context(|| format!("解析配置文件失败: {}", path.display()))?;
|
||||||
|
Ok(config)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save_config(config: &Config) -> Result<()> {
|
||||||
|
let dir = config_dir();
|
||||||
|
fs::create_dir_all(&dir).with_context(|| format!("创建配置目录失败: {}", dir.display()))?;
|
||||||
|
|
||||||
|
let path = config_path();
|
||||||
|
let content = toml::to_string_pretty(config).context("序列化配置失败")?;
|
||||||
|
fs::write(&path, &content).with_context(|| format!("写入配置文件失败: {}", path.display()))?;
|
||||||
|
|
||||||
|
// 设置文件权限为 0600(仅所有者读写)
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
let perms = fs::Permissions::from_mode(0o600);
|
||||||
|
fs::set_permissions(&path, perms)
|
||||||
|
.with_context(|| format!("设置文件权限失败: {}", path.display()))?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 按优先级解析数据库连接串:
|
||||||
|
/// 1. --db-url CLI 参数(非空时使用)
|
||||||
|
/// 2. ~/.config/secrets/config.toml 中的 database_url
|
||||||
|
/// 3. 报错并提示用户配置
|
||||||
|
pub fn resolve_db_url(cli_db_url: &str) -> Result<String> {
|
||||||
|
if !cli_db_url.is_empty() {
|
||||||
|
return Ok(cli_db_url.to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
let config = load_config()?;
|
||||||
|
if let Some(url) = config.database_url
|
||||||
|
&& !url.is_empty()
|
||||||
|
{
|
||||||
|
return Ok(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
anyhow::bail!("数据库未配置。请先运行:\n\n secrets config set-db <DATABASE_URL>\n")
|
||||||
|
}
|
||||||
20
src/db.rs
20
src/db.rs
@@ -1,16 +1,19 @@
|
|||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use sqlx::postgres::PgPoolOptions;
|
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
|
use sqlx::postgres::PgPoolOptions;
|
||||||
|
|
||||||
pub async fn create_pool(database_url: &str) -> Result<PgPool> {
|
pub async fn create_pool(database_url: &str) -> Result<PgPool> {
|
||||||
|
tracing::debug!("connecting to database");
|
||||||
let pool = PgPoolOptions::new()
|
let pool = PgPoolOptions::new()
|
||||||
.max_connections(5)
|
.max_connections(5)
|
||||||
.connect(database_url)
|
.connect(database_url)
|
||||||
.await?;
|
.await?;
|
||||||
|
tracing::debug!("database connection established");
|
||||||
Ok(pool)
|
Ok(pool)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn migrate(pool: &PgPool) -> Result<()> {
|
pub async fn migrate(pool: &PgPool) -> Result<()> {
|
||||||
|
tracing::debug!("running migrations");
|
||||||
sqlx::raw_sql(
|
sqlx::raw_sql(
|
||||||
r#"
|
r#"
|
||||||
CREATE TABLE IF NOT EXISTS secrets (
|
CREATE TABLE IF NOT EXISTS secrets (
|
||||||
@@ -36,9 +39,24 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
|
|||||||
CREATE INDEX IF NOT EXISTS idx_secrets_kind ON secrets(kind);
|
CREATE INDEX IF NOT EXISTS idx_secrets_kind ON secrets(kind);
|
||||||
CREATE INDEX IF NOT EXISTS idx_secrets_tags ON secrets USING GIN(tags);
|
CREATE INDEX IF NOT EXISTS idx_secrets_tags ON secrets USING GIN(tags);
|
||||||
CREATE INDEX IF NOT EXISTS idx_secrets_metadata ON secrets USING GIN(metadata jsonb_path_ops);
|
CREATE INDEX IF NOT EXISTS idx_secrets_metadata ON secrets USING GIN(metadata jsonb_path_ops);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS audit_log (
|
||||||
|
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
|
action VARCHAR(32) NOT NULL,
|
||||||
|
namespace VARCHAR(64) NOT NULL,
|
||||||
|
kind VARCHAR(64) NOT NULL,
|
||||||
|
name VARCHAR(256) NOT NULL,
|
||||||
|
detail JSONB NOT NULL DEFAULT '{}',
|
||||||
|
actor VARCHAR(128) NOT NULL DEFAULT '',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_audit_log_created ON audit_log(created_at DESC);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_audit_log_ns_kind ON audit_log(namespace, kind);
|
||||||
"#,
|
"#,
|
||||||
)
|
)
|
||||||
.execute(pool)
|
.execute(pool)
|
||||||
.await?;
|
.await?;
|
||||||
|
tracing::debug!("migrations complete");
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
342
src/main.rs
342
src/main.rs
@@ -1,93 +1,299 @@
|
|||||||
|
mod audit;
|
||||||
mod commands;
|
mod commands;
|
||||||
|
mod config;
|
||||||
mod db;
|
mod db;
|
||||||
mod models;
|
mod models;
|
||||||
|
mod output;
|
||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use clap::{Parser, Subcommand};
|
use clap::{Parser, Subcommand};
|
||||||
use dotenvy::dotenv;
|
use tracing_subscriber::EnvFilter;
|
||||||
|
|
||||||
|
use output::resolve_output_mode;
|
||||||
|
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
#[command(name = "secrets", version, about = "Secrets & config manager backed by PostgreSQL")]
|
#[command(
|
||||||
|
name = "secrets",
|
||||||
|
version,
|
||||||
|
about = "Secrets & config manager backed by PostgreSQL — optimised for AI agents",
|
||||||
|
after_help = "QUICK START (AI agents):
|
||||||
|
# Discover what namespaces / kinds exist
|
||||||
|
secrets search --summary --limit 20
|
||||||
|
|
||||||
|
# Precise lookup (JSON output for easy parsing)
|
||||||
|
secrets search -n refining --kind service --name gitea -o json --show-secrets
|
||||||
|
|
||||||
|
# Extract a single field value directly
|
||||||
|
secrets search -n refining --kind service --name gitea -f secret.token
|
||||||
|
|
||||||
|
# Pipe-friendly (non-TTY defaults to json-compact automatically)
|
||||||
|
secrets search -n refining --kind service | jq '.[].name'"
|
||||||
|
)]
|
||||||
struct Cli {
|
struct Cli {
|
||||||
/// Database URL (or set DATABASE_URL env var)
|
/// Database URL, overrides saved config (one-time override)
|
||||||
#[arg(long, env = "DATABASE_URL", global = true, default_value = "")]
|
#[arg(long, global = true, default_value = "")]
|
||||||
db_url: String,
|
db_url: String,
|
||||||
|
|
||||||
|
/// Enable verbose debug output
|
||||||
|
#[arg(long, short, global = true)]
|
||||||
|
verbose: bool,
|
||||||
|
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
command: Commands,
|
command: Commands,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Subcommand)]
|
#[derive(Subcommand)]
|
||||||
enum Commands {
|
enum Commands {
|
||||||
/// Add or update a record (upsert)
|
/// Add or update a record (upsert). Use -m for plaintext metadata, -s for secrets.
|
||||||
|
#[command(after_help = "EXAMPLES:
|
||||||
|
# Add a server
|
||||||
|
secrets add -n refining --kind server --name my-server \\
|
||||||
|
--tag aliyun --tag shanghai \\
|
||||||
|
-m ip=47.117.131.22 -m desc=\"Aliyun Shanghai ECS\" \\
|
||||||
|
-s username=root -s ssh_key=@./keys/server.pem
|
||||||
|
|
||||||
|
# Add a service credential
|
||||||
|
secrets add -n refining --kind service --name gitea \\
|
||||||
|
--tag gitea \\
|
||||||
|
-m url=https://gitea.refining.dev -m default_org=refining \\
|
||||||
|
-s token=<token>
|
||||||
|
|
||||||
|
# Add with token read from a file
|
||||||
|
secrets add -n ricnsmart --kind service --name mqtt \\
|
||||||
|
-m host=mqtt.ricnsmart.com -m port=1883 \\
|
||||||
|
-s password=@./mqtt_password.txt")]
|
||||||
Add {
|
Add {
|
||||||
/// Namespace (e.g. refining, ricnsmart)
|
/// Namespace, e.g. refining, ricnsmart
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
namespace: String,
|
namespace: String,
|
||||||
/// Kind of record (server, service, key, ...)
|
/// Kind of record: server, service, key, ...
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
kind: String,
|
kind: String,
|
||||||
/// Human-readable name
|
/// Human-readable unique name, e.g. gitea, i-uf63f2uookgs5uxmrdyc
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
name: String,
|
name: String,
|
||||||
/// Tags for categorization (repeatable)
|
/// Tag for categorization (repeatable), e.g. --tag aliyun --tag hongkong
|
||||||
#[arg(long = "tag")]
|
#[arg(long = "tag")]
|
||||||
tags: Vec<String>,
|
tags: Vec<String>,
|
||||||
/// Plaintext metadata entry: key=value (repeatable, key=@file reads from file)
|
/// Plaintext metadata: key=value (repeatable; value=@file reads from file)
|
||||||
#[arg(long = "meta", short = 'm')]
|
#[arg(long = "meta", short = 'm')]
|
||||||
meta: Vec<String>,
|
meta: Vec<String>,
|
||||||
/// Secret entry: key=value (repeatable, key=@file reads from file)
|
/// Secret entry: key=value (repeatable; value=@file reads from file)
|
||||||
#[arg(long = "secret", short = 's')]
|
#[arg(long = "secret", short = 's')]
|
||||||
secrets: Vec<String>,
|
secrets: Vec<String>,
|
||||||
|
/// Output format: text (default on TTY), json, json-compact, env
|
||||||
|
#[arg(short, long = "output")]
|
||||||
|
output: Option<String>,
|
||||||
},
|
},
|
||||||
|
|
||||||
/// Search records
|
/// Search / read records. This is the primary read command for AI agents.
|
||||||
|
///
|
||||||
|
/// Supports fuzzy search (-q), exact lookup (--name), field extraction (-f),
|
||||||
|
/// summary view (--summary), pagination (--limit / --offset), and structured
|
||||||
|
/// output (-o json / json-compact / env). When stdout is not a TTY, output
|
||||||
|
/// defaults to json-compact automatically.
|
||||||
|
#[command(after_help = "EXAMPLES:
|
||||||
|
# Discover all records (summary, safe default limit)
|
||||||
|
secrets search --summary --limit 20
|
||||||
|
|
||||||
|
# Filter by namespace and kind
|
||||||
|
secrets search -n refining --kind service
|
||||||
|
|
||||||
|
# Exact lookup — returns 0 or 1 record
|
||||||
|
secrets search -n refining --kind service --name gitea
|
||||||
|
|
||||||
|
# Fuzzy keyword search (matches name, namespace, kind, tags, metadata)
|
||||||
|
secrets search -q mqtt
|
||||||
|
|
||||||
|
# Extract a single field value (implies --show-secrets for secret.*)
|
||||||
|
secrets search -n refining --kind service --name gitea -f secret.token
|
||||||
|
secrets search -n refining --kind service --name gitea -f metadata.url
|
||||||
|
|
||||||
|
# Multiple fields at once
|
||||||
|
secrets search -n refining --kind service --name gitea \\
|
||||||
|
-f metadata.url -f metadata.default_org -f secret.token
|
||||||
|
|
||||||
|
# Full JSON output with secrets revealed (ideal for AI parsing)
|
||||||
|
secrets search -n refining --kind service --name gitea -o json --show-secrets
|
||||||
|
|
||||||
|
# Export as env vars (source-able; single record only)
|
||||||
|
secrets search -n refining --kind service --name gitea -o env --show-secrets
|
||||||
|
|
||||||
|
# Paginate large result sets
|
||||||
|
secrets search -n refining --summary --limit 10 --offset 0
|
||||||
|
secrets search -n refining --summary --limit 10 --offset 10
|
||||||
|
|
||||||
|
# Sort by most recently updated
|
||||||
|
secrets search --sort updated --limit 5 --summary
|
||||||
|
|
||||||
|
# Non-TTY / pipe: output is json-compact by default
|
||||||
|
secrets search -n refining --kind service | jq '.[].name'
|
||||||
|
secrets search -n refining --kind service --name gitea --show-secrets | jq '.secrets.token'")]
|
||||||
Search {
|
Search {
|
||||||
/// Filter by namespace
|
/// Filter by namespace, e.g. refining, ricnsmart
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
namespace: Option<String>,
|
namespace: Option<String>,
|
||||||
/// Filter by kind
|
/// Filter by kind, e.g. server, service
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
kind: Option<String>,
|
kind: Option<String>,
|
||||||
/// Filter by tag
|
/// Exact name filter, e.g. gitea, i-uf63f2uookgs5uxmrdyc
|
||||||
|
#[arg(long)]
|
||||||
|
name: Option<String>,
|
||||||
|
/// Filter by tag, e.g. --tag aliyun
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
tag: Option<String>,
|
tag: Option<String>,
|
||||||
/// Search by keyword (matches name, namespace, kind)
|
/// 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
|
/// Reveal encrypted secret values in output
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
show_secrets: bool,
|
show_secrets: bool,
|
||||||
|
/// Extract field value(s) directly: metadata.<key> or secret.<key> (repeatable)
|
||||||
|
#[arg(short = 'f', long = "field")]
|
||||||
|
fields: Vec<String>,
|
||||||
|
/// Return lightweight summary only (namespace, kind, name, tags, desc, updated_at)
|
||||||
|
#[arg(long)]
|
||||||
|
summary: bool,
|
||||||
|
/// Maximum number of records to return [default: 50]
|
||||||
|
#[arg(long, default_value = "50")]
|
||||||
|
limit: u32,
|
||||||
|
/// Skip this many records (for pagination)
|
||||||
|
#[arg(long, default_value = "0")]
|
||||||
|
offset: u32,
|
||||||
|
/// Sort order: name (default), updated, created
|
||||||
|
#[arg(long, default_value = "name")]
|
||||||
|
sort: String,
|
||||||
|
/// Output format: text (default on TTY), json, json-compact, env
|
||||||
|
#[arg(short, long = "output")]
|
||||||
|
output: Option<String>,
|
||||||
},
|
},
|
||||||
|
|
||||||
/// Delete a record
|
/// Delete a record permanently. Requires exact namespace + kind + name.
|
||||||
|
#[command(after_help = "EXAMPLES:
|
||||||
|
# Delete a service credential
|
||||||
|
secrets delete -n refining --kind service --name legacy-mqtt
|
||||||
|
|
||||||
|
# Delete a server record
|
||||||
|
secrets delete -n ricnsmart --kind server --name i-old-server-id")]
|
||||||
Delete {
|
Delete {
|
||||||
/// Namespace
|
/// Namespace, e.g. refining
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
namespace: String,
|
namespace: String,
|
||||||
/// Kind
|
/// Kind, e.g. server, service
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
kind: String,
|
kind: String,
|
||||||
/// Name
|
/// Exact name of the record to delete
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
name: String,
|
name: String,
|
||||||
},
|
},
|
||||||
|
|
||||||
|
/// Incrementally update an existing record (merge semantics; record must exist).
|
||||||
|
///
|
||||||
|
/// Only the fields you pass are changed — everything else is preserved.
|
||||||
|
/// Use --add-tag / --remove-tag to modify tags without touching other fields.
|
||||||
|
#[command(after_help = "EXAMPLES:
|
||||||
|
# Update a single metadata field (all other fields unchanged)
|
||||||
|
secrets update -n refining --kind server --name my-server -m ip=10.0.0.1
|
||||||
|
|
||||||
|
# Rotate a secret token
|
||||||
|
secrets update -n refining --kind service --name gitea -s token=<new-token>
|
||||||
|
|
||||||
|
# Add a tag and rotate password at the same time
|
||||||
|
secrets update -n refining --kind service --name gitea \\
|
||||||
|
--add-tag production -s token=<new-token>
|
||||||
|
|
||||||
|
# Remove a deprecated metadata field and a stale secret key
|
||||||
|
secrets update -n refining --kind service --name mqtt \\
|
||||||
|
--remove-meta old_port --remove-secret old_password
|
||||||
|
|
||||||
|
# Remove a tag
|
||||||
|
secrets update -n refining --kind service --name gitea --remove-tag staging")]
|
||||||
|
Update {
|
||||||
|
/// Namespace, e.g. refining, ricnsmart
|
||||||
|
#[arg(short, long)]
|
||||||
|
namespace: String,
|
||||||
|
/// Kind of record: server, service, key, ...
|
||||||
|
#[arg(long)]
|
||||||
|
kind: String,
|
||||||
|
/// Human-readable unique name
|
||||||
|
#[arg(long)]
|
||||||
|
name: String,
|
||||||
|
/// Add a tag (repeatable; does not affect existing tags)
|
||||||
|
#[arg(long = "add-tag")]
|
||||||
|
add_tags: Vec<String>,
|
||||||
|
/// Remove a tag (repeatable)
|
||||||
|
#[arg(long = "remove-tag")]
|
||||||
|
remove_tags: Vec<String>,
|
||||||
|
/// Set or overwrite a metadata field: key=value (repeatable, @file supported)
|
||||||
|
#[arg(long = "meta", short = 'm')]
|
||||||
|
meta: Vec<String>,
|
||||||
|
/// Delete a metadata field by key (repeatable)
|
||||||
|
#[arg(long = "remove-meta")]
|
||||||
|
remove_meta: Vec<String>,
|
||||||
|
/// Set or overwrite a secret field: key=value (repeatable, @file supported)
|
||||||
|
#[arg(long = "secret", short = 's')]
|
||||||
|
secrets: Vec<String>,
|
||||||
|
/// Delete a secret field by key (repeatable)
|
||||||
|
#[arg(long = "remove-secret")]
|
||||||
|
remove_secrets: Vec<String>,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// Manage CLI configuration (database connection, etc.)
|
||||||
|
#[command(after_help = "EXAMPLES:
|
||||||
|
# Configure the database URL (run once per device; persisted to config file)
|
||||||
|
secrets config set-db \"postgres://postgres:<password>@<host>:<port>/secrets\"
|
||||||
|
|
||||||
|
# Show current config (password is masked)
|
||||||
|
secrets config show
|
||||||
|
|
||||||
|
# Print path to the config file
|
||||||
|
secrets config path")]
|
||||||
|
Config {
|
||||||
|
#[command(subcommand)]
|
||||||
|
action: ConfigAction,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Subcommand)]
|
||||||
|
enum ConfigAction {
|
||||||
|
/// Save database URL to config file (~/.config/secrets/config.toml)
|
||||||
|
SetDb {
|
||||||
|
/// PostgreSQL connection string, e.g. postgres://user:pass@<host>:<port>/dbname
|
||||||
|
url: String,
|
||||||
|
},
|
||||||
|
/// Show current configuration (password masked)
|
||||||
|
Show,
|
||||||
|
/// Print path to the config file
|
||||||
|
Path,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<()> {
|
async fn main() -> Result<()> {
|
||||||
dotenv().ok();
|
|
||||||
|
|
||||||
let cli = Cli::parse();
|
let cli = Cli::parse();
|
||||||
|
|
||||||
let db_url = if cli.db_url.is_empty() {
|
let filter = if cli.verbose {
|
||||||
std::env::var("DATABASE_URL").map_err(|_| {
|
EnvFilter::new("secrets=debug")
|
||||||
anyhow::anyhow!("DATABASE_URL not set. Use --db-url or set DATABASE_URL env var.")
|
|
||||||
})?
|
|
||||||
} else {
|
} else {
|
||||||
cli.db_url.clone()
|
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("secrets=warn"))
|
||||||
};
|
};
|
||||||
|
tracing_subscriber::fmt()
|
||||||
|
.with_env_filter(filter)
|
||||||
|
.with_target(false)
|
||||||
|
.init();
|
||||||
|
|
||||||
|
// config 子命令不需要数据库连接,提前处理
|
||||||
|
if let Commands::Config { action } = &cli.command {
|
||||||
|
let cmd_action = match action {
|
||||||
|
ConfigAction::SetDb { url } => {
|
||||||
|
commands::config::ConfigAction::SetDb { url: url.clone() }
|
||||||
|
}
|
||||||
|
ConfigAction::Show => commands::config::ConfigAction::Show,
|
||||||
|
ConfigAction::Path => commands::config::ConfigAction::Path,
|
||||||
|
};
|
||||||
|
return commands::config::run(cmd_action).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
let db_url = config::resolve_db_url(&cli.db_url)?;
|
||||||
let pool = db::create_pool(&db_url).await?;
|
let pool = db::create_pool(&db_url).await?;
|
||||||
db::migrate(&pool).await?;
|
db::migrate(&pool).await?;
|
||||||
|
|
||||||
@@ -99,23 +305,59 @@ async fn main() -> Result<()> {
|
|||||||
tags,
|
tags,
|
||||||
meta,
|
meta,
|
||||||
secrets,
|
secrets,
|
||||||
|
output,
|
||||||
} => {
|
} => {
|
||||||
commands::add::run(&pool, namespace, kind, name, tags, meta, secrets).await?;
|
let _span =
|
||||||
|
tracing::info_span!("cmd", command = "add", %namespace, %kind, %name).entered();
|
||||||
|
let out = resolve_output_mode(output.as_deref())?;
|
||||||
|
commands::add::run(
|
||||||
|
&pool,
|
||||||
|
commands::add::AddArgs {
|
||||||
|
namespace,
|
||||||
|
kind,
|
||||||
|
name,
|
||||||
|
tags,
|
||||||
|
meta_entries: meta,
|
||||||
|
secret_entries: secrets,
|
||||||
|
output: out,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
}
|
}
|
||||||
Commands::Search {
|
Commands::Search {
|
||||||
namespace,
|
namespace,
|
||||||
kind,
|
kind,
|
||||||
|
name,
|
||||||
tag,
|
tag,
|
||||||
query,
|
query,
|
||||||
show_secrets,
|
show_secrets,
|
||||||
|
fields,
|
||||||
|
summary,
|
||||||
|
limit,
|
||||||
|
offset,
|
||||||
|
sort,
|
||||||
|
output,
|
||||||
} => {
|
} => {
|
||||||
|
let _span = tracing::info_span!("cmd", command = "search").entered();
|
||||||
|
// -f implies --show-secrets when any field path starts with "secret"
|
||||||
|
let show = *show_secrets || fields.iter().any(|f| f.starts_with("secret"));
|
||||||
|
let out = resolve_output_mode(output.as_deref())?;
|
||||||
commands::search::run(
|
commands::search::run(
|
||||||
&pool,
|
&pool,
|
||||||
namespace.as_deref(),
|
commands::search::SearchArgs {
|
||||||
kind.as_deref(),
|
namespace: namespace.as_deref(),
|
||||||
tag.as_deref(),
|
kind: kind.as_deref(),
|
||||||
query.as_deref(),
|
name: name.as_deref(),
|
||||||
*show_secrets,
|
tag: tag.as_deref(),
|
||||||
|
query: query.as_deref(),
|
||||||
|
show_secrets: show,
|
||||||
|
fields,
|
||||||
|
summary: *summary,
|
||||||
|
limit: *limit,
|
||||||
|
offset: *offset,
|
||||||
|
sort,
|
||||||
|
output: out,
|
||||||
|
},
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
@@ -124,8 +366,40 @@ async fn main() -> Result<()> {
|
|||||||
kind,
|
kind,
|
||||||
name,
|
name,
|
||||||
} => {
|
} => {
|
||||||
|
let _span =
|
||||||
|
tracing::info_span!("cmd", command = "delete", %namespace, %kind, %name).entered();
|
||||||
commands::delete::run(&pool, namespace, kind, name).await?;
|
commands::delete::run(&pool, namespace, kind, name).await?;
|
||||||
}
|
}
|
||||||
|
Commands::Update {
|
||||||
|
namespace,
|
||||||
|
kind,
|
||||||
|
name,
|
||||||
|
add_tags,
|
||||||
|
remove_tags,
|
||||||
|
meta,
|
||||||
|
remove_meta,
|
||||||
|
secrets,
|
||||||
|
remove_secrets,
|
||||||
|
} => {
|
||||||
|
let _span =
|
||||||
|
tracing::info_span!("cmd", command = "update", %namespace, %kind, %name).entered();
|
||||||
|
commands::update::run(
|
||||||
|
&pool,
|
||||||
|
commands::update::UpdateArgs {
|
||||||
|
namespace,
|
||||||
|
kind,
|
||||||
|
name,
|
||||||
|
add_tags,
|
||||||
|
remove_tags,
|
||||||
|
meta_entries: meta,
|
||||||
|
remove_meta,
|
||||||
|
secret_entries: secrets,
|
||||||
|
remove_secrets,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
Commands::Config { .. } => unreachable!(),
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
47
src/output.rs
Normal file
47
src/output.rs
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
use std::io::IsTerminal;
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
/// Output format for all commands.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq)]
|
||||||
|
pub enum OutputMode {
|
||||||
|
/// Human-readable text (default when stdout is a TTY)
|
||||||
|
#[default]
|
||||||
|
Text,
|
||||||
|
/// Pretty-printed JSON
|
||||||
|
Json,
|
||||||
|
/// Single-line JSON (default when stdout is NOT a TTY, e.g. piped to jq)
|
||||||
|
JsonCompact,
|
||||||
|
/// KEY=VALUE pairs suitable for `source` or `.env` files
|
||||||
|
Env,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromStr for OutputMode {
|
||||||
|
type Err = anyhow::Error;
|
||||||
|
|
||||||
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||||
|
match s {
|
||||||
|
"text" => Ok(Self::Text),
|
||||||
|
"json" => Ok(Self::Json),
|
||||||
|
"json-compact" => Ok(Self::JsonCompact),
|
||||||
|
"env" => Ok(Self::Env),
|
||||||
|
other => Err(anyhow::anyhow!(
|
||||||
|
"Unknown output format '{}'. Valid: text, json, json-compact, env",
|
||||||
|
other
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve the effective output mode.
|
||||||
|
/// - Explicit value from `--output` takes priority.
|
||||||
|
/// - TTY → text; non-TTY (piped/redirected) → json-compact.
|
||||||
|
pub fn resolve_output_mode(explicit: Option<&str>) -> anyhow::Result<OutputMode> {
|
||||||
|
if let Some(s) = explicit {
|
||||||
|
return s.parse();
|
||||||
|
}
|
||||||
|
if std::io::stdout().is_terminal() {
|
||||||
|
Ok(OutputMode::Text)
|
||||||
|
} else {
|
||||||
|
Ok(OutputMode::JsonCompact)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user