Compare commits
95 Commits
secrets-0.
...
secrets-mc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59084a409d | ||
|
|
b0fcb83592 | ||
|
|
8942718641 | ||
|
|
53d53ff96a | ||
|
|
cab234cfcb | ||
|
|
e0fee639c1 | ||
|
|
7c53bfb782 | ||
|
|
63cb3a8216 | ||
|
|
2b994141b8 | ||
|
|
9d6ac5c13a | ||
|
|
1860cce86c | ||
| dd24f7cc44 | |||
|
|
aefad33870 | ||
|
|
0ffb81e57f | ||
|
|
4a1654c820 | ||
|
|
a15e2eaf4a | ||
|
|
1518388374 | ||
| b99d821644 | |||
|
|
32f275f88a | ||
|
|
c6fb457734 | ||
| df701f21b9 | |||
| c3c536200e | |||
| 7909f7102d | |||
| 87a29af82d | |||
| 1b11f7e976 | |||
| 08e81363c9 | |||
|
|
beade4503d | ||
|
|
409fd78a35 | ||
|
|
f7afd7f819 | ||
|
|
719bdd7e08 | ||
|
|
1e597559a2 | ||
|
|
e3ca43ca3f | ||
|
|
0b57605103 | ||
|
|
8b191937cd | ||
|
|
11c936a5b8 | ||
|
|
b6349dd1c8 | ||
|
|
f720983328 | ||
|
|
7bd0603dc6 | ||
|
|
17a95bea5b | ||
|
|
a42db62702 | ||
|
|
2edb970cba | ||
|
|
17f8ac0dbc | ||
|
|
259fbe10a6 | ||
|
|
c815fb4cc8 | ||
|
|
90cd1eca15 | ||
|
|
da007348ea | ||
|
|
f2344b7543 | ||
|
|
ee028d45c3 | ||
|
|
a44c8ebf08 | ||
|
|
a595081c4c | ||
|
|
0a8b14211a | ||
|
|
9cebbd7587 | ||
|
|
4d136a5a20 | ||
|
|
7ce4aaf835 | ||
|
|
bce01a0f2b | ||
|
|
8cd4dbf592 | ||
|
|
ad3c8d1672 | ||
|
|
8d6b9f0368 | ||
|
|
ce9e089348 | ||
|
|
786675ce42 | ||
|
|
5df4141935 | ||
|
|
49fb7430a8 | ||
|
|
ff9767ff95 | ||
|
|
955acfe9ec | ||
|
|
3a5ec92bf0 | ||
|
|
854720f10c | ||
|
|
62a1df316b | ||
|
|
d0796e9c9a | ||
|
|
66b6417faa | ||
|
|
56a28e8cf7 | ||
|
|
12aec6675a | ||
|
|
e1cd6e736c | ||
|
|
0a5317e477 | ||
|
|
efa76cae55 | ||
|
|
5a5867adc1 | ||
|
|
4ddafbe4b6 | ||
|
|
6ea9f0861b | ||
|
|
3973295d6a | ||
|
|
c371da95c3 | ||
|
|
baad623efe | ||
|
|
2da7aab3e5 | ||
|
|
fcac14a8c4 | ||
|
|
ff79a3a9cc | ||
|
|
3c21b3dac1 | ||
|
|
3b36d5a3dd | ||
|
|
a765dcc428 | ||
|
|
31b0ea9bf1 | ||
|
|
dc0534cbc9 | ||
|
|
8fdb6db87b | ||
|
|
1f7984d798 | ||
|
|
140162f39a | ||
|
|
535683b15c | ||
|
|
9620ff1923 | ||
|
|
e6db23bd6d | ||
|
|
c61c8292aa |
@@ -1,13 +1,14 @@
|
||||
name: Secrets CLI - Build & Release
|
||||
# MCP 分支:仅构建/发布 secrets-mcp(CLI 在 main 分支维护)
|
||||
name: Secrets MCP — Build & Release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'src/**'
|
||||
- 'crates/**'
|
||||
- 'Cargo.toml'
|
||||
- 'Cargo.lock'
|
||||
- '.gitea/workflows/secrets.yml'
|
||||
- 'deploy/**'
|
||||
- '.gitea/workflows/**'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
@@ -17,465 +18,239 @@ permissions:
|
||||
contents: write
|
||||
|
||||
env:
|
||||
BINARY_NAME: secrets
|
||||
MCP_BINARY: secrets-mcp
|
||||
RUST_TOOLCHAIN: 1.94.0
|
||||
CARGO_INCREMENTAL: 0
|
||||
CARGO_NET_RETRY: 10
|
||||
CARGO_TERM_COLOR: always
|
||||
RUST_BACKTRACE: short
|
||||
MUSL_TARGET: x86_64-unknown-linux-musl
|
||||
|
||||
jobs:
|
||||
version:
|
||||
name: 版本 & Release
|
||||
ci:
|
||||
name: 检查 / 构建 / 发版
|
||||
runs-on: debian
|
||||
timeout-minutes: 40
|
||||
outputs:
|
||||
version: ${{ steps.ver.outputs.version }}
|
||||
tag: ${{ steps.ver.outputs.tag }}
|
||||
tag_exists: ${{ steps.ver.outputs.tag_exists }}
|
||||
release_id: ${{ steps.release.outputs.release_id }}
|
||||
version: ${{ steps.ver.outputs.version }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
# ── 版本解析 ────────────────────────────────────────────────────────
|
||||
- name: 解析版本
|
||||
id: ver
|
||||
run: |
|
||||
version=$(grep -m1 '^version' Cargo.toml | sed 's/.*"\(.*\)".*/\1/')
|
||||
tag="secrets-${version}"
|
||||
previous_tag=$(git tag --list 'secrets-*' --sort=-v:refname | awk -v tag="$tag" '$0 != tag { print; exit }')
|
||||
|
||||
version=$(grep -m1 '^version' crates/secrets-mcp/Cargo.toml | sed 's/.*"\(.*\)".*/\1/')
|
||||
tag="secrets-mcp-${version}"
|
||||
echo "version=${version}" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=${tag}" >> "$GITHUB_OUTPUT"
|
||||
echo "previous_tag=${previous_tag}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
if git rev-parse "refs/tags/${tag}" >/dev/null 2>&1; then
|
||||
echo "⚠ 版本 ${tag} 已存在,将覆盖重新发版。"
|
||||
echo "tag_exists=true" >> "$GITHUB_OUTPUT"
|
||||
echo "版本 ${tag} 已存在"
|
||||
else
|
||||
echo "tag_exists=false" >> "$GITHUB_OUTPUT"
|
||||
echo "将创建新版本 ${tag}"
|
||||
echo "tag_exists=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
# ── Rust 工具链 ──────────────────────────────────────────────────────
|
||||
- name: 安装 Rust 与 musl 工具链
|
||||
run: |
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq pkg-config musl-tools binutils jq
|
||||
if ! command -v rustup >/dev/null 2>&1; then
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain "${RUST_TOOLCHAIN}"
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
fi
|
||||
source "$HOME/.cargo/env" 2>/dev/null || true
|
||||
rustup toolchain install "${RUST_TOOLCHAIN}" --profile minimal \
|
||||
--component rustfmt --component clippy
|
||||
rustup default "${RUST_TOOLCHAIN}"
|
||||
rustup target add "${MUSL_TARGET}" --toolchain "${RUST_TOOLCHAIN}"
|
||||
rustc -V && cargo -V
|
||||
|
||||
- name: 缓存 Cargo
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry/index
|
||||
~/.cargo/registry/cache
|
||||
~/.cargo/git/db
|
||||
target
|
||||
key: cargo-${{ env.MUSL_TARGET }}-${{ env.RUST_TOOLCHAIN }}-${{ hashFiles('Cargo.lock') }}
|
||||
restore-keys: |
|
||||
cargo-${{ env.MUSL_TARGET }}-${{ env.RUST_TOOLCHAIN }}-
|
||||
cargo-${{ env.MUSL_TARGET }}-
|
||||
|
||||
# ── 质量检查(先于构建,失败即止)──────────────────────────────────
|
||||
- name: fmt
|
||||
run: cargo fmt -- --check
|
||||
|
||||
- name: clippy
|
||||
run: cargo clippy --locked -- -D warnings
|
||||
|
||||
- name: test
|
||||
run: cargo test --locked
|
||||
|
||||
# ── 构建(质量检查通过后才执行)────────────────────────────────────
|
||||
- name: 构建 secrets-mcp (musl)
|
||||
run: |
|
||||
cargo build --release --locked --target "${MUSL_TARGET}" -p secrets-mcp
|
||||
strip "target/${MUSL_TARGET}/release/${MCP_BINARY}"
|
||||
|
||||
- name: 上传构建产物
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: ${{ env.MCP_BINARY }}-linux-musl
|
||||
path: target/${{ env.MUSL_TARGET }}/release/${{ env.MCP_BINARY }}
|
||||
retention-days: 3
|
||||
|
||||
# ── 创建 / 覆盖 Tag(构建成功后才打)───────────────────────────────
|
||||
- name: 创建 Tag
|
||||
if: steps.ver.outputs.tag_exists == 'false'
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git tag -a "${{ steps.ver.outputs.tag }}" -m "Release ${{ steps.ver.outputs.tag }}"
|
||||
git push origin "${{ steps.ver.outputs.tag }}"
|
||||
tag="${{ steps.ver.outputs.tag }}"
|
||||
if [ "${{ steps.ver.outputs.tag_exists }}" = "true" ]; then
|
||||
git tag -d "$tag" 2>/dev/null || true
|
||||
git push origin ":refs/tags/$tag" 2>/dev/null || true
|
||||
fi
|
||||
git tag -a "$tag" -m "Release $tag"
|
||||
git push origin "$tag"
|
||||
|
||||
- name: 解析或创建 Release
|
||||
id: release
|
||||
# ── Release(可选,需配置 RELEASE_TOKEN)───────────────────────────
|
||||
- name: Upsert Release
|
||||
if: env.RELEASE_TOKEN != ''
|
||||
env:
|
||||
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
run: |
|
||||
if [ -z "$RELEASE_TOKEN" ]; then
|
||||
echo "release_id=" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
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"
|
||||
api="${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases"
|
||||
auth="Authorization: token $RELEASE_TOKEN"
|
||||
|
||||
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 }}"
|
||||
previous_tag=$(git tag --list 'secrets-mcp-*' --sort=-v:refname | awk -v t="$tag" '$0 != t { print; exit }')
|
||||
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
|
||||
|
||||
# Upsert: 存在 → PATCH + 清旧 assets;不存在 → POST
|
||||
release_id=$(curl -sS -H "$auth" "${api}/tags/${tag}" 2>/dev/null | jq -r '.id // empty')
|
||||
if [ -n "$release_id" ]; then
|
||||
echo "已创建草稿 Release: ${release_id}"
|
||||
echo "release_id=${release_id}" >> "$GITHUB_OUTPUT"
|
||||
curl -sS -o /dev/null -H "$auth" -H "Content-Type: application/json" \
|
||||
-X PATCH "${api}/${release_id}" \
|
||||
-d "$(jq -n --arg n "secrets-mcp ${version}" --arg b "$body" '{name:$n,body:$b,draft:false}')"
|
||||
curl -sS -H "$auth" "${api}/${release_id}/assets" | \
|
||||
jq -r '.[].id' | xargs -I{} curl -sS -o /dev/null -H "$auth" -X DELETE "${api}/${release_id}/assets/{}"
|
||||
echo "已更新 Release ${release_id}"
|
||||
else
|
||||
echo "⚠ 创建 Release 失败 (HTTP ${http_code}),跳过产物上传"
|
||||
cat /tmp/create-release.json 2>/dev/null || true
|
||||
echo "release_id=" >> "$GITHUB_OUTPUT"
|
||||
release_id=$(curl -fsS -H "$auth" -H "Content-Type: application/json" \
|
||||
-X POST "$api" \
|
||||
-d "$(jq -n --arg t "$tag" --arg n "secrets-mcp ${version}" --arg b "$body" \
|
||||
'{tag_name:$t,name:$n,body:$b,draft:false}')" | jq -r '.id')
|
||||
echo "已创建 Release ${release_id}"
|
||||
fi
|
||||
|
||||
probe-runners:
|
||||
name: 探测 Runner
|
||||
runs-on: debian
|
||||
outputs:
|
||||
has_linux: ${{ steps.probe.outputs.has_linux }}
|
||||
has_macos: ${{ steps.probe.outputs.has_macos }}
|
||||
has_windows: ${{ steps.probe.outputs.has_windows }}
|
||||
steps:
|
||||
- name: 查询可用 Runner
|
||||
id: probe
|
||||
env:
|
||||
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
run: |
|
||||
fallback_all() {
|
||||
echo "has_linux=true" >> "$GITHUB_OUTPUT"
|
||||
echo "has_macos=true" >> "$GITHUB_OUTPUT"
|
||||
echo "has_windows=true" >> "$GITHUB_OUTPUT"
|
||||
}
|
||||
|
||||
if [ -z "$RELEASE_TOKEN" ]; then
|
||||
echo "未配置 RELEASE_TOKEN,默认尝试所有平台"
|
||||
fallback_all; exit 0
|
||||
fi
|
||||
|
||||
command -v jq >/dev/null 2>&1 || (sudo apt-get update -qq && sudo apt-get install -y -qq jq)
|
||||
|
||||
http_code=$(curl -sS -o /tmp/runners.json -w '%{http_code}' \
|
||||
-H "Authorization: token $RELEASE_TOKEN" \
|
||||
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/actions/runners")
|
||||
|
||||
if [ "$http_code" != "200" ]; then
|
||||
echo "Runner API 返回 HTTP ${http_code},默认尝试所有平台"
|
||||
fallback_all; exit 0
|
||||
fi
|
||||
|
||||
has_runner() {
|
||||
local label="$1"
|
||||
jq -e --arg label "$label" '
|
||||
(.runners // .data // . // [])
|
||||
| any(
|
||||
(
|
||||
(.online == true)
|
||||
or (
|
||||
((.status // "") | ascii_downcase)
|
||||
| IN("online", "idle", "busy", "active")
|
||||
)
|
||||
)
|
||||
and (
|
||||
(.labels // [])
|
||||
| map(if type == "object" then (.name // .label // "") else tostring end | ascii_downcase)
|
||||
| index($label)
|
||||
) != null
|
||||
)
|
||||
' /tmp/runners.json >/dev/null
|
||||
}
|
||||
|
||||
for pair in "debian:has_linux" "darwin-arm64:has_macos" "windows:has_windows"; do
|
||||
label="$(printf '%s' "${pair%%:*}" | tr '[:upper:]' '[:lower:]')"; key="${pair##*:}"
|
||||
if has_runner "$label"; then
|
||||
echo "${key}=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "${key}=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
done
|
||||
|
||||
check:
|
||||
name: 质量检查 (fmt / clippy / test)
|
||||
runs-on: debian
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: 安装 Rust
|
||||
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
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
fi
|
||||
source "$HOME/.cargo/env" 2>/dev/null || true
|
||||
rustup component add rustfmt clippy
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: 缓存 Cargo
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry/index
|
||||
~/.cargo/registry/cache
|
||||
~/.cargo/git/db
|
||||
target
|
||||
key: cargo-check-${{ hashFiles('Cargo.lock') }}
|
||||
restore-keys: |
|
||||
cargo-check-
|
||||
|
||||
- run: cargo fmt -- --check
|
||||
- run: cargo clippy --locked -- -D warnings
|
||||
- run: cargo test --locked
|
||||
|
||||
build-linux:
|
||||
name: Build (x86_64-unknown-linux-musl)
|
||||
needs: [version, probe-runners, check]
|
||||
if: needs.probe-runners.outputs.has_linux == 'true'
|
||||
runs-on: debian
|
||||
timeout-minutes: 1
|
||||
steps:
|
||||
- name: 安装依赖
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y pkg-config musl-tools binutils curl
|
||||
if ! command -v cargo >/dev/null 2>&1; then
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
|
||||
fi
|
||||
source "$HOME/.cargo/env" 2>/dev/null || true
|
||||
rustup target add x86_64-unknown-linux-musl
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: 缓存 Cargo
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry/index
|
||||
~/.cargo/registry/cache
|
||||
~/.cargo/git/db
|
||||
target
|
||||
key: cargo-x86_64-unknown-linux-musl-${{ hashFiles('Cargo.lock') }}
|
||||
restore-keys: |
|
||||
cargo-x86_64-unknown-linux-musl-
|
||||
|
||||
- run: cargo build --release --locked --target x86_64-unknown-linux-musl
|
||||
- run: strip target/x86_64-unknown-linux-musl/release/${{ env.BINARY_NAME }}
|
||||
|
||||
- name: 上传 Release 产物
|
||||
if: needs.version.outputs.release_id != ''
|
||||
env:
|
||||
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
run: |
|
||||
[ -z "$RELEASE_TOKEN" ] && exit 0
|
||||
tag="${{ needs.version.outputs.tag }}"
|
||||
bin="target/x86_64-unknown-linux-musl/release/${{ env.BINARY_NAME }}"
|
||||
archive="${{ env.BINARY_NAME }}-${tag}-x86_64-linux-musl.tar.gz"
|
||||
bin="target/${MUSL_TARGET}/release/${MCP_BINARY}"
|
||||
archive="${MCP_BINARY}-${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"
|
||||
sha256sum "$archive" > "${archive}.sha256"
|
||||
curl -fsS -H "$auth" -F "attachment=@${archive}" "${api}/${release_id}/assets"
|
||||
curl -fsS -H "$auth" -F "attachment=@${archive}.sha256" "${api}/${release_id}/assets"
|
||||
echo "Release ${tag} 已发布"
|
||||
|
||||
build-macos:
|
||||
name: Build (aarch64-apple-darwin)
|
||||
needs: [version, probe-runners, check]
|
||||
if: needs.probe-runners.outputs.has_macos == 'true'
|
||||
runs-on: darwin-arm64
|
||||
timeout-minutes: 1
|
||||
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"
|
||||
|
||||
build-windows:
|
||||
name: Build (x86_64-pc-windows-msvc)
|
||||
needs: [version, probe-runners, check]
|
||||
if: needs.probe-runners.outputs.has_windows == 'true'
|
||||
runs-on: windows
|
||||
timeout-minutes: 1
|
||||
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 }
|
||||
|
||||
publish-release:
|
||||
name: 发布草稿 Release
|
||||
needs: [version, check, build-linux, build-macos, build-windows]
|
||||
if: always() && needs.version.outputs.release_id != ''
|
||||
runs-on: debian
|
||||
timeout-minutes: 2
|
||||
steps:
|
||||
- name: 发布草稿
|
||||
env:
|
||||
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
run: |
|
||||
[ -z "$RELEASE_TOKEN" ] && exit 0
|
||||
|
||||
version_r="${{ needs.version.result }}"
|
||||
check_r="${{ needs.check.result }}"
|
||||
linux_r="${{ needs.build-linux.result }}"
|
||||
macos_r="${{ needs.build-macos.result }}"
|
||||
windows_r="${{ needs.build-windows.result }}"
|
||||
|
||||
for result in "$version_r" "$check_r" "$linux_r" "$macos_r" "$windows_r"; do
|
||||
case "$result" in
|
||||
success|skipped) ;;
|
||||
*)
|
||||
echo "存在失败或取消的 job,保留草稿 Release"
|
||||
exit 0
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
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
|
||||
|
||||
notify:
|
||||
name: 通知
|
||||
needs: [version, probe-runners, check, build-linux, build-macos, build-windows, publish-release]
|
||||
if: always() && github.event_name == 'push'
|
||||
runs-on: debian
|
||||
timeout-minutes: 1
|
||||
continue-on-error: true
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: 发送飞书通知
|
||||
# ── 飞书汇总通知 ─────────────────────────────────────────────────────
|
||||
- name: 飞书通知
|
||||
if: always()
|
||||
env:
|
||||
WEBHOOK_URL: ${{ vars.WEBHOOK_URL }}
|
||||
run: |
|
||||
[ -z "$WEBHOOK_URL" ] && exit 0
|
||||
command -v jq >/dev/null 2>&1 || (sudo apt-get update -qq && sudo apt-get install -y -qq jq)
|
||||
|
||||
tag="${{ needs.version.outputs.tag }}"
|
||||
tag_exists="${{ needs.version.outputs.tag_exists }}"
|
||||
commit=$(git log -1 --pretty=format:"%s" 2>/dev/null || echo "N/A")
|
||||
tag="${{ steps.ver.outputs.tag }}"
|
||||
commit="${{ github.event.head_commit.message }}"
|
||||
[ -z "$commit" ] && commit="${{ github.sha }}"
|
||||
url="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}"
|
||||
|
||||
version_r="${{ needs.version.result }}"
|
||||
check_r="${{ needs.check.result }}"
|
||||
linux_r="${{ needs.build-linux.result }}"
|
||||
macos_r="${{ needs.build-macos.result }}"
|
||||
windows_r="${{ needs.build-windows.result }}"
|
||||
publish_r="${{ needs.publish-release.result }}"
|
||||
|
||||
if [ "$version_r" = "success" ] && [ "$check_r" = "success" ] \
|
||||
&& [ "$linux_r" != "failure" ] && [ "$linux_r" != "cancelled" ] \
|
||||
&& [ "$macos_r" != "failure" ] && [ "$macos_r" != "cancelled" ] \
|
||||
&& [ "$windows_r" != "failure" ] && [ "$windows_r" != "cancelled" ] \
|
||||
&& [ "$publish_r" != "failure" ] && [ "$publish_r" != "cancelled" ]; then
|
||||
status="构建成功 ✅"
|
||||
else
|
||||
status="构建失败 ❌"
|
||||
fi
|
||||
|
||||
icon() {
|
||||
case "$1" in
|
||||
success) echo "✅" ;;
|
||||
skipped) echo "⏭" ;;
|
||||
*) echo "❌" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
msg="${{ env.BINARY_NAME }} ${status}"
|
||||
if [ "$tag_exists" = "false" ]; then
|
||||
msg="${msg}
|
||||
🆕 新版本 ${tag}"
|
||||
else
|
||||
msg="${msg}
|
||||
🔄 重复构建 ${tag}"
|
||||
fi
|
||||
|
||||
msg="${msg}
|
||||
构建结果:linux$(icon "$linux_r") macOS$(icon "$macos_r") windows$(icon "$windows_r")
|
||||
Release:$(icon "$publish_r")
|
||||
result="${{ job.status }}"
|
||||
if [ "$result" = "success" ]; then icon="✅"; else icon="❌"; fi
|
||||
msg="secrets-mcp 构建&发版 ${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"
|
||||
|
||||
deploy:
|
||||
name: 部署 secrets-mcp
|
||||
needs: [ci]
|
||||
if: |
|
||||
github.ref == 'refs/heads/main' ||
|
||||
github.ref == 'refs/heads/feat/mcp' ||
|
||||
github.ref == 'refs/heads/mcp'
|
||||
runs-on: debian
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: 下载构建产物
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: ${{ env.MCP_BINARY }}-linux-musl
|
||||
path: /tmp/artifact
|
||||
|
||||
- name: 部署到阿里云 ECS
|
||||
env:
|
||||
DEPLOY_HOST: ${{ vars.DEPLOY_HOST }}
|
||||
DEPLOY_USER: ${{ vars.DEPLOY_USER }}
|
||||
DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
|
||||
DEPLOY_KNOWN_HOSTS: ${{ vars.DEPLOY_KNOWN_HOSTS }}
|
||||
run: |
|
||||
if [ -z "$DEPLOY_HOST" ] || [ -z "$DEPLOY_USER" ] || [ -z "$DEPLOY_SSH_KEY" ]; then
|
||||
echo "部署跳过:请配置 vars.DEPLOY_HOST、vars.DEPLOY_USER 与 secrets.DEPLOY_SSH_KEY"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
install -m 600 /dev/null /tmp/deploy_key
|
||||
echo "$DEPLOY_SSH_KEY" > /tmp/deploy_key
|
||||
trap 'rm -f /tmp/deploy_key' EXIT
|
||||
|
||||
if [ -n "$DEPLOY_KNOWN_HOSTS" ]; then
|
||||
echo "$DEPLOY_KNOWN_HOSTS" > /tmp/deploy_known_hosts
|
||||
ssh_opts="-o UserKnownHostsFile=/tmp/deploy_known_hosts -o StrictHostKeyChecking=yes"
|
||||
else
|
||||
ssh_opts="-o StrictHostKeyChecking=accept-new"
|
||||
fi
|
||||
|
||||
scp -i /tmp/deploy_key $ssh_opts \
|
||||
"/tmp/artifact/${MCP_BINARY}" \
|
||||
"${DEPLOY_USER}@${DEPLOY_HOST}:/tmp/secrets-mcp.new"
|
||||
|
||||
ssh -i /tmp/deploy_key $ssh_opts "${DEPLOY_USER}@${DEPLOY_HOST}" "
|
||||
sudo mv /tmp/secrets-mcp.new /opt/secrets-mcp/secrets-mcp
|
||||
sudo chmod +x /opt/secrets-mcp/secrets-mcp
|
||||
sudo systemctl restart secrets-mcp
|
||||
sleep 2
|
||||
sudo systemctl is-active secrets-mcp && echo '服务启动成功' || (sudo journalctl -u secrets-mcp -n 20 && exit 1)
|
||||
"
|
||||
|
||||
- name: 飞书通知
|
||||
if: always()
|
||||
env:
|
||||
WEBHOOK_URL: ${{ vars.WEBHOOK_URL }}
|
||||
run: |
|
||||
[ -z "$WEBHOOK_URL" ] && exit 0
|
||||
tag="${{ needs.ci.outputs.tag }}"
|
||||
url="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}"
|
||||
result="${{ job.status }}"
|
||||
if [ "$result" = "success" ]; then icon="✅"; else icon="❌"; fi
|
||||
msg="secrets-mcp 部署 ${icon}
|
||||
版本:${tag}
|
||||
作者:${{ 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"
|
||||
|
||||
8
.gitignore
vendored
8
.gitignore
vendored
@@ -1,3 +1,9 @@
|
||||
/target
|
||||
.env
|
||||
.DS_Store
|
||||
.DS_Store
|
||||
.cursor/
|
||||
*.pem
|
||||
tmp/
|
||||
client_secret_*.apps.googleusercontent.com.json
|
||||
node_modules/
|
||||
*.pyc
|
||||
107
.vscode/tasks.json
vendored
107
.vscode/tasks.json
vendored
@@ -2,106 +2,45 @@
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"label": "build",
|
||||
"label": "mcp: build",
|
||||
"type": "shell",
|
||||
"command": "cargo build",
|
||||
"group": { "kind": "build", "isDefault": true }
|
||||
"command": "cargo build --locked -p secrets-mcp",
|
||||
"group": "build",
|
||||
"options": {
|
||||
"envFile": "${workspaceFolder}/.env"
|
||||
}
|
||||
},
|
||||
{
|
||||
"label": "cli: version",
|
||||
"label": "mcp: run",
|
||||
"type": "shell",
|
||||
"command": "./target/debug/secrets -V",
|
||||
"dependsOn": "build"
|
||||
"command": "cargo run --locked -p secrets-mcp",
|
||||
"options": {
|
||||
"envFile": "${workspaceFolder}/.env"
|
||||
}
|
||||
},
|
||||
{
|
||||
"label": "cli: help",
|
||||
"label": "test: workspace",
|
||||
"type": "shell",
|
||||
"command": "./target/debug/secrets --help",
|
||||
"dependsOn": "build"
|
||||
"command": "cargo test --workspace --locked",
|
||||
"group": { "kind": "test", "isDefault": true }
|
||||
},
|
||||
{
|
||||
"label": "cli: help add",
|
||||
"label": "fmt: check",
|
||||
"type": "shell",
|
||||
"command": "./target/debug/secrets help add",
|
||||
"dependsOn": "build"
|
||||
"command": "cargo fmt -- --check",
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "test: search all",
|
||||
"label": "clippy: workspace",
|
||||
"type": "shell",
|
||||
"command": "./target/debug/secrets search",
|
||||
"dependsOn": "build"
|
||||
"command": "cargo clippy --workspace --locked -- -D warnings",
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "test: search by namespace (refining)",
|
||||
"label": "ci: release-check",
|
||||
"type": "shell",
|
||||
"command": "./target/debug/secrets search -n refining",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "test: search by namespace (ricnsmart)",
|
||||
"type": "shell",
|
||||
"command": "./target/debug/secrets search -n ricnsmart",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "test: search servers",
|
||||
"type": "shell",
|
||||
"command": "./target/debug/secrets search --kind server",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "test: search services",
|
||||
"type": "shell",
|
||||
"command": "./target/debug/secrets search --kind service",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "test: search keys",
|
||||
"type": "shell",
|
||||
"command": "./target/debug/secrets search --kind key",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "test: search by tag (aliyun)",
|
||||
"type": "shell",
|
||||
"command": "./target/debug/secrets search --tag aliyun",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "test: search by tag (hongkong)",
|
||||
"type": "shell",
|
||||
"command": "./target/debug/secrets search --tag hongkong",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "test: search keyword (gitea)",
|
||||
"type": "shell",
|
||||
"command": "./target/debug/secrets search -q gitea",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "test: search with secrets revealed",
|
||||
"type": "shell",
|
||||
"command": "./target/debug/secrets search -n refining --kind service --name gitea --show-secrets",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "test: combined search (ricnsmart + server + shanghai)",
|
||||
"type": "shell",
|
||||
"command": "./target/debug/secrets search -n ricnsmart --kind server --tag shanghai",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "test: add + delete roundtrip",
|
||||
"type": "shell",
|
||||
"command": "echo '--- add ---' && ./target/debug/secrets add -n test --kind demo --name roundtrip-test --tag test -m foo=bar -s password=secret123 && echo '--- search ---' && ./target/debug/secrets search -n test --show-secrets && echo '--- delete ---' && ./target/debug/secrets delete -n test --kind demo --name roundtrip-test && echo '--- verify deleted ---' && ./target/debug/secrets search -n test",
|
||||
"dependsOn": "build"
|
||||
},
|
||||
{
|
||||
"label": "test: add with file secret",
|
||||
"type": "shell",
|
||||
"command": "echo '--- add key from file ---' && ./target/debug/secrets add -n test --kind key --name test-key --tag test -s content=@./refining/keys/Vultr && echo '--- verify ---' && ./target/debug/secrets search -n test --kind key --show-secrets && echo '--- cleanup ---' && ./target/debug/secrets delete -n test --kind key --name test-key",
|
||||
"dependsOn": "build"
|
||||
"command": "./scripts/release-check.sh",
|
||||
"problemMatcher": []
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
317
AGENTS.md
317
AGENTS.md
@@ -1,184 +1,243 @@
|
||||
# Secrets CLI — AGENTS.md
|
||||
# Secrets MCP — AGENTS.md
|
||||
|
||||
跨设备密钥与配置管理 CLI 工具,将 refining / ricnsmart 两个项目的服务器信息、服务凭据存储到 PostgreSQL 18,供 AI 工具读取上下文。
|
||||
本仓库为 **MCP SaaS**:`secrets-core`(业务与持久化)+ `secrets-mcp`(Streamable HTTP MCP、Web、OAuth、API Key)。对外入口见 `crates/secrets-mcp`。
|
||||
|
||||
## 版本控制
|
||||
|
||||
本仓库使用 **[Jujutsu (jj)](https://jj-vcs.dev/)** 作为版本控制系统(纯 jj 模式,无 `.git` 目录)。
|
||||
|
||||
### 常用 jj 命令对照
|
||||
|
||||
| 操作 | jj 命令 |
|
||||
|------|---------|
|
||||
| 查看历史 | `jj log` / `jj log 'all()'` |
|
||||
| 查看状态 | `jj status` |
|
||||
| 新建提交 | `jj commit` |
|
||||
| 创建新变更 | `jj new` |
|
||||
| 变基 | `jj rebase` |
|
||||
| 合并提交 | `jj squash` |
|
||||
| 撤销操作 | `jj undo` |
|
||||
| 查看标签 | `jj tag list` |
|
||||
| 查看分支 | `jj bookmark list` |
|
||||
| 推送远端 | `jj git push` |
|
||||
| 拉取远端 | `jj git fetch` |
|
||||
|
||||
### 注意事项
|
||||
- 本仓库为**纯 jj 模式**,无 `.git` 目录;本地不要使用 `git` 命令
|
||||
- CI/CD(Gitea Actions)仍通过 Git 协议拉取代码,Runner 侧自动使用 `git`,无需修改
|
||||
- 检查标签是否存在时使用 `jj log --no-graph --revisions "tag(${tag})"` 而非 `git rev-parse`
|
||||
|
||||
## 提交 / 推送硬规则(优先于下文)
|
||||
|
||||
**每次提交和推送前必须执行以下检查,无论是否明确「发版」:**
|
||||
|
||||
1. 涉及 `crates/**`、根目录 `Cargo.toml`/`Cargo.lock`、`secrets-mcp` 行为变更的提交,默认视为**需要发版**,除非明确说明「本次不发版」。
|
||||
2. 提交前检查 `crates/secrets-mcp/Cargo.toml` 的 `version`,再查 tag:`jj tag list`。若当前版本对应 tag 已存在且有代码变更,**必须 bump 版本号**并 `cargo build` 同步 `Cargo.lock`。
|
||||
3. 提交前运行 `./scripts/release-check.sh`(版本/tag + `fmt` + `clippy --locked` + `test --locked`)。若脚本不存在或不可用,至少运行 `cargo fmt -- --check && cargo clippy --locked -- -D warnings && cargo test --locked`。
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
secrets/
|
||||
src/
|
||||
main.rs # CLI 入口,clap 命令定义,auto-migrate
|
||||
db.rs # PgPool 创建 + 建表/索引(幂等)
|
||||
models.rs # Secret 结构体(sqlx::FromRow + serde)
|
||||
commands/
|
||||
add.rs # add 命令:upsert,支持 --meta key=value / --secret key=@file
|
||||
search.rs # search 命令:多条件动态查询
|
||||
delete.rs # delete 命令
|
||||
Cargo.toml
|
||||
crates/
|
||||
secrets-core/ # db / crypto / models / audit / service
|
||||
secrets-mcp/ # rmcp tools、axum、OAuth、Dashboard
|
||||
scripts/
|
||||
seed-data.sh # 从 refining/ricnsmart config.toml 导入全量数据
|
||||
.gitea/workflows/
|
||||
secrets.yml # CI:fmt + clippy + musl 构建 + Release 上传 + 飞书通知
|
||||
.vscode/tasks.json # 本地测试任务(build / search / add+delete roundtrip 等)
|
||||
.env # DATABASE_URL(gitignore,不提交)
|
||||
release-check.sh
|
||||
setup-gitea-actions.sh
|
||||
.gitea/workflows/secrets.yml
|
||||
.vscode/tasks.json
|
||||
```
|
||||
|
||||
## 数据库
|
||||
|
||||
- **Host**: `47.117.131.22:5432`(阿里云上海 ECS,PostgreSQL 18 with io_uring)
|
||||
- **Database**: `secrets`
|
||||
- **连接串**: `postgres://postgres:<password>@47.117.131.22:5432/secrets`
|
||||
- **表**: 单张 `secrets` 表,首次连接自动建表(auto-migrate)
|
||||
- **建议库名**:`secrets-mcp`(专用实例,与历史库名区分)。
|
||||
- **连接**:环境变量 **`SECRETS_DATABASE_URL`**(本分支无本地配置文件路径)。
|
||||
- **表**:`entries`(含 `user_id`)、`secrets`、`entries_history`、`secrets_history`、`audit_log`、`users`、`oauth_accounts`,首次连接 **auto-migrate**(`secrets-core` 的 `migrate`)。
|
||||
- **Web 会话**:与上项 **同一数据库 URL**;`secrets-mcp` 启动时对 tower-sessions 的 PostgreSQL 存储 **auto-migrate**(会话表与业务表共存于该实例,无需第二套连接串)。
|
||||
|
||||
### 表结构
|
||||
### 表结构(摘录)
|
||||
|
||||
```sql
|
||||
entries (
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||
user_id UUID, -- 多租户:NULL=遗留行;非空=归属用户
|
||||
folder VARCHAR(128) NOT NULL DEFAULT '',
|
||||
type VARCHAR(64) NOT NULL DEFAULT '',
|
||||
name VARCHAR(256) NOT NULL,
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
tags TEXT[] NOT NULL DEFAULT '{}',
|
||||
metadata JSONB NOT NULL DEFAULT '{}',
|
||||
version BIGINT NOT NULL DEFAULT 1,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
-- 唯一:UNIQUE(user_id, folder, name) WHERE user_id IS NOT NULL;
|
||||
-- UNIQUE(folder, name) WHERE user_id IS NULL(单租户遗留)
|
||||
```
|
||||
|
||||
```sql
|
||||
secrets (
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(), -- PG18 时间有序 UUID
|
||||
namespace VARCHAR(64) NOT NULL, -- 一级隔离: "refining" | "ricnsmart"
|
||||
kind VARCHAR(64) NOT NULL, -- 类型: "server" | "service"(可扩展)
|
||||
name VARCHAR(256) NOT NULL, -- 人类可读标识
|
||||
tags TEXT[] NOT NULL DEFAULT '{}', -- 灵活标签: ["aliyun","hongkong"]
|
||||
metadata JSONB NOT NULL DEFAULT '{}', -- 明文描述: ip, desc, domains, location...
|
||||
encrypted JSONB NOT NULL DEFAULT '{}', -- 敏感数据: ssh_key, password, token...
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE(namespace, kind, name)
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||
user_id UUID,
|
||||
name VARCHAR(256) NOT NULL,
|
||||
type VARCHAR(64) NOT NULL DEFAULT 'text',
|
||||
encrypted BYTEA NOT NULL DEFAULT '\x',
|
||||
version BIGINT NOT NULL DEFAULT 1,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
-- 唯一:UNIQUE(user_id, name) WHERE user_id IS NOT NULL
|
||||
```
|
||||
|
||||
```sql
|
||||
entry_secrets (
|
||||
entry_id UUID NOT NULL REFERENCES entries(id) ON DELETE CASCADE,
|
||||
secret_id UUID NOT NULL REFERENCES secrets(id) ON DELETE CASCADE,
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
PRIMARY KEY(entry_id, secret_id)
|
||||
)
|
||||
```
|
||||
|
||||
### 字段职责划分
|
||||
### users / oauth_accounts
|
||||
|
||||
| 字段 | 存什么 | 示例 |
|
||||
|------|--------|------|
|
||||
| `namespace` | 项目/团队隔离 | `refining`, `ricnsmart` |
|
||||
| `kind` | 记录类型 | `server`, `service` |
|
||||
| `name` | 唯一标识名 | `i-uf63f2uookgs5uxmrdyc`, `gitea` |
|
||||
| `tags` | 多维分类标签 | `["aliyun","hongkong","ricn"]` |
|
||||
| `metadata` | 明文非敏感信息 | `{"ip":"47.243.154.187","desc":"Grafana","domains":["..."]}` |
|
||||
| `encrypted` | 敏感凭据(MVP 阶段明文存储,后续对 value 加密) | `{"ssh_key":"-----BEGIN...","password":"..."}` |
|
||||
```sql
|
||||
users (
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||
email VARCHAR(256),
|
||||
name VARCHAR(256) NOT NULL DEFAULT '',
|
||||
avatar_url TEXT,
|
||||
key_salt BYTEA, -- PBKDF2 salt(32B),首次设置密码短语时写入
|
||||
key_check BYTEA, -- 派生密钥加密已知常量,用于验证密码短语
|
||||
key_params JSONB, -- 算法参数,如 {"alg":"pbkdf2-sha256","iterations":600000}
|
||||
api_key TEXT UNIQUE, -- MCP Bearer token,明文存储(设计决策,见下方说明)
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
|
||||
## CLI 命令
|
||||
|
||||
```bash
|
||||
# 查看版本
|
||||
secrets -V / --version
|
||||
|
||||
# 查看帮助
|
||||
secrets -h / --help
|
||||
secrets help <subcommand> # 子命令详细帮助,如 secrets help add
|
||||
|
||||
# 添加或更新记录(upsert)
|
||||
secrets add -n <namespace> --kind <kind> --name <name> \
|
||||
[--tag <tag>]... # 可重复
|
||||
[-m key=value]... # --meta 明文字段,-m 是短标志
|
||||
[-s key=value]... # --secret 敏感字段,value 以 @ 开头表示从文件读取
|
||||
|
||||
# 搜索(默认隐藏 encrypted 内容)
|
||||
secrets search [-n <namespace>] [--kind <kind>] [--tag <tag>] [-q <keyword>] [--show-secrets]
|
||||
# -q 匹配范围:name、namespace、kind、metadata 全文内容、tags
|
||||
|
||||
# 增量更新已有记录(合并语义,记录不存在则报错)
|
||||
secrets update -n <namespace> --kind <kind> --name <name> \
|
||||
[--add-tag <tag>]... # 添加标签(不影响已有标签)
|
||||
[--remove-tag <tag>]... # 移除标签
|
||||
[-m key=value]... # 新增或覆盖 metadata 字段(不影响其他字段)
|
||||
[--remove-meta <key>]... # 删除 metadata 字段
|
||||
[-s key=value]... # 新增或覆盖 encrypted 字段(不影响其他字段)
|
||||
[--remove-secret <key>]... # 删除 encrypted 字段
|
||||
|
||||
# 删除
|
||||
secrets delete -n <namespace> --kind <kind> --name <name>
|
||||
oauth_accounts (
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
provider VARCHAR(32) NOT NULL,
|
||||
provider_id VARCHAR(256) NOT NULL,
|
||||
email VARCHAR(256),
|
||||
name VARCHAR(256),
|
||||
avatar_url TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE(provider, provider_id)
|
||||
)
|
||||
-- 另有唯一索引 UNIQUE(user_id, provider)(迁移中 idx_oauth_accounts_user_provider):同一用户每种 provider 至多一条关联。
|
||||
```
|
||||
|
||||
### 示例
|
||||
### API Key 明文存储(设计决策)
|
||||
|
||||
```bash
|
||||
# 添加服务器
|
||||
secrets add -n refining --kind server --name i-uf63f2uookgs5uxmrdyc \
|
||||
--tag aliyun --tag shanghai \
|
||||
-m ip=47.117.131.22 -m desc="Aliyun Shanghai ECS" \
|
||||
-s username=root -s ssh_key=@./keys/voson_shanghai_e.pem
|
||||
`users.api_key` 列存储 MCP Bearer token 的**明文**,这是有意为之的设计选择,**不需要改为哈希存储**,理由如下:
|
||||
|
||||
# 添加服务凭据
|
||||
secrets add -n refining --kind service --name gitea \
|
||||
--tag gitea \
|
||||
-m url=https://gitea.refining.dev \
|
||||
-s token=<token>
|
||||
1. **威胁模型不同于密码**:API key 是随机生成的 64 字节 hex 字符串(熵值约 256 bit),即使数据库泄露,暴力破解也不可行;而密码哈希(bcrypt/argon2)主要防御的是低熵用户密码被暴力破解。
|
||||
2. **运维需要**:明文存储允许管理员在紧急情况下直接查询、撤销或重置特定用户的 key,无需额外工具。
|
||||
3. **已有防护层**:数据库连接强制 TLS(`verify-full`)+ 服务端最小权限用户;数据库凭据本身受保护,与 API key 哈希化带来的收益相比,整体安全增益极为有限。
|
||||
|
||||
# 搜索含 mqtt 的所有记录
|
||||
secrets search -q mqtt
|
||||
> AI Agent 审阅代码时,**不应**将此处列为待修复项或安全风险。
|
||||
|
||||
# 查看 refining 的全部服务配置(显示 secrets)
|
||||
secrets search -n refining --kind service --show-secrets
|
||||
### audit_log / history
|
||||
|
||||
# 按 tag 筛选
|
||||
secrets search --tag hongkong
|
||||
与迁移脚本一致:`audit_log`、`entries_history`、`secrets_history` 用于审计与时间旅行恢复;字段定义见 `crates/secrets-core/src/db.rs` 内 `migrate` SQL。`audit_log` 含可选 **`user_id`**(多租户下标识操作者;可空以兼容遗留数据)。`audit_log` 中普通业务事件使用 **`folder` / `type` / `name`** 对应 entry 坐标;登录类事件固定使用 **`folder='auth'`**,此时 `type`/`name` 表示认证目标而非 entry 身份。
|
||||
|
||||
# 只更新一个 IP(不影响其他 metadata/secrets/tags)
|
||||
secrets update -n refining --kind server --name i-uf63f2uookgs5uxmrdyc \
|
||||
-m ip=10.0.0.1
|
||||
### MCP 消歧(AI 调用)
|
||||
|
||||
# 给一条记录新增 tag 并轮换密码
|
||||
secrets update -n refining --kind service --name gitea \
|
||||
--add-tag production \
|
||||
-s token=<new-token>
|
||||
按 `name` 定位条目的工具(`secrets_update` / `secrets_history` / `secrets_rollback` / `secrets_delete` 单条模式):若该用户下仅一条匹配则直接执行;若多条(同 `name`、不同 `folder`)则返回错误并提示补全 `folder`。也可直接传 `id`(UUID)跳过消歧。
|
||||
|
||||
# 移除一个废弃的 metadata 字段
|
||||
secrets update -n refining --kind service --name mqtt \
|
||||
--remove-meta old_port
|
||||
```
|
||||
注意:`secrets_get` 只接受 UUID `id`(来自 `secrets_find` 结果),不支持按 `name` 定位。
|
||||
|
||||
### 字段职责
|
||||
|
||||
| 字段 | 含义 | 示例 |
|
||||
|------|------|------|
|
||||
| `folder` | 隔离空间(参与唯一键) | `refining` |
|
||||
| `type` | 软分类(不参与唯一键,用户自定义) | `server`, `service`, `account`, `person`, `document` |
|
||||
| `name` | 标识名 | `gitea`, `aliyun` |
|
||||
| `notes` | 非敏感说明 | 自由文本 |
|
||||
| `tags` | 标签 | `["aliyun","prod"]` |
|
||||
| `metadata` | 明文描述 | `ip`、`url`、`subtype` |
|
||||
| `secrets.name` | 密钥名称(调用方提供) | `token`, `ssh_key`, `password` |
|
||||
| `secrets.type` | 密钥类型(调用方提供,默认 `text`) | `text`, `password`, `key` |
|
||||
| `secrets.encrypted` | 密文 | AES-GCM |
|
||||
|
||||
### 共享密钥(N:N 关联)
|
||||
|
||||
多个 entry 可共享同一 secret 字段,通过 `entry_secrets` 中间表关联。
|
||||
添加条目时通过 `link_secret_names` 参数指定要关联的已有 secret name(按 `(user_id, name)` 精确匹配)。
|
||||
删除 entry 时仅解除关联,secret 本身若仍被引用则保留;不再被任何 entry 引用时自动清理。
|
||||
|
||||
## 代码规范
|
||||
|
||||
- 错误处理:统一使用 `anyhow::Result`,不用 `unwrap()`
|
||||
- 异步:全程 `tokio`,数据库操作 `sqlx` async
|
||||
- SQL:使用 `sqlx::query` / `sqlx::query_as` 绑定参数,禁止字符串拼接(搜索的动态 WHERE 子句除外,需使用参数绑定 `$1/$2`)
|
||||
- 新增 `kind` 类型时:只需在 `add` 调用时传入,无需改代码
|
||||
- 字段命名:CLI 短标志 `-n`=namespace,`-m`=meta,`-s`=secret,`-q`=query
|
||||
- 错误:业务层 `anyhow::Result`,避免生产路径 `unwrap()`。
|
||||
- 异步:`tokio` + `sqlx` async。
|
||||
- SQL:`sqlx::query` / `query_as` 参数绑定;动态 WHERE 仍须用占位符绑定。
|
||||
- 日志:运维用 `tracing`;面向用户的 Web 响应走 axum handler。tracing 字段风格:变量名即字段名时用简写(`%var`、`?var`、`var`),否则用显式形式(`field = %expr`)。
|
||||
- 审计:写操作成功后尽量 `audit::log_tx`;失败可 `warn`,不掩盖主错误。
|
||||
- 加密:密钥由用户密码短语通过 **PBKDF2-SHA256(600k 次)** 在客户端派生,服务端只存 `key_salt`/`key_check`/`key_params`,不持有原始密钥。Web 客户端在浏览器本地完成加解密;MCP 客户端通过 `X-Encryption-Key` 请求头传递密钥,服务端临时解密后返回明文。
|
||||
- MCP:tools 参数与 JSON Schema(`schemars`)保持同步,鉴权以请求扩展中的用户上下文为准。
|
||||
|
||||
## 提交前检查(必须全部通过)
|
||||
## 生产 CORS
|
||||
|
||||
每次提交代码前,请在本地依次执行以下检查,**全部通过后再 push**:
|
||||
生产环境 CORS 使用显式请求头白名单(`build_cors_layer`),而非 `allow_headers(Any)`,
|
||||
因为 `tower-http` 禁止 `allow_credentials(true)` 与 `allow_headers(Any)` 同时使用。
|
||||
|
||||
### 1. 版本号(按需)
|
||||
**维护约束**:若 MCP 协议或客户端新增自定义请求头,必须同步更新 `production_allowed_headers()`。
|
||||
当前允许的请求头:`Authorization`、`Content-Type`、`X-Encryption-Key`、`mcp-session-id`、`x-mcp-session`。
|
||||
|
||||
若本次改动需要发版,请先确认 `Cargo.toml` 中的 `version` 已提升,避免 CI 打出的 Tag 与已有版本重复。可通过 git tag 判断:
|
||||
## 提交前检查
|
||||
|
||||
```bash
|
||||
# 查看当前 Cargo.toml 版本
|
||||
grep '^version' Cargo.toml
|
||||
|
||||
# 查看是否已存在该版本对应的 tag(CI 使用格式 secrets-<version>)
|
||||
git tag -l 'secrets-*'
|
||||
./scripts/release-check.sh
|
||||
```
|
||||
|
||||
若当前版本已被 tag(例如已有 `secrets-0.1.0` 且 `Cargo.toml` 仍为 `0.1.0`),则应在 `Cargo.toml` 中 bump 版本号后再提交,以便 CI 自动打新 Tag 并发布 Release。
|
||||
|
||||
### 2. 格式、Lint、测试
|
||||
或手动:
|
||||
|
||||
```bash
|
||||
cargo fmt -- --check # 格式检查(不通过则运行 cargo fmt 修复)
|
||||
cargo clippy -- -D warnings # Lint 检查(消除所有 warning)
|
||||
cargo test # 单元/集成测试
|
||||
cargo fmt -- --check
|
||||
cargo clippy --locked -- -D warnings
|
||||
cargo test --locked
|
||||
```
|
||||
|
||||
或一次性执行:
|
||||
发版前确认未重复 tag:
|
||||
|
||||
```bash
|
||||
cargo fmt -- --check && cargo clippy -- -D warnings && cargo test
|
||||
grep '^version' crates/secrets-mcp/Cargo.toml
|
||||
jj tag list
|
||||
```
|
||||
|
||||
## CI/CD
|
||||
|
||||
- Gitea Actions(runner: debian)
|
||||
- 触发:`src/**`、`Cargo.toml`、`Cargo.lock` 变更推送到 main
|
||||
- 构建目标:`x86_64-unknown-linux-musl`(静态链接,无 glibc 依赖)
|
||||
- 新版本自动打 Tag(格式 `secrets-<version>`)并上传二进制到 Gitea Release
|
||||
- 通知:飞书 Webhook(`vars.WEBHOOK_URL`)
|
||||
- 所需 secrets/vars:`RELEASE_TOKEN`(Release 上传,Gitea PAT)、`vars.WEBHOOK_URL`(通知,可选)
|
||||
- **触发**:任意分支 `push`,且路径含 `crates/**`、`deploy/**`、根目录 `Cargo.toml`、`Cargo.lock`、`.gitea/workflows/**`(见 `.gitea/workflows/secrets.yml`)。
|
||||
- **版本与 tag**:从 `crates/secrets-mcp/Cargo.toml` 读版本;构建成功后打 `secrets-mcp-<version>`:若远端已存在同名 tag,CI 会先删后于**当前提交**重建并推送(覆盖式发版)。
|
||||
- **质量与构建**:`fmt` / `clippy --locked` / `test --locked` → `x86_64-unknown-linux-musl` 发布构建 `secrets-mcp`。
|
||||
- **Release(可选)**:`secrets.RELEASE_TOKEN`(Gitea PAT)用于通过 API **创建或更新**该 tag 的 Release(非 draft)、上传 `tar.gz` + `.sha256`;未配置则跳过 API Release,仅 tag + 构建。
|
||||
- **部署(可选)**:仅 `main`、`feat/mcp`、`mcp` 分支在构建成功时跑 `deploy-mcp`;需 `vars.DEPLOY_HOST`、`vars.DEPLOY_USER`、`secrets.DEPLOY_SSH_KEY`。勿把 OAuth/DB 等写进 workflow,用 `deploy/.env.example` 在目标机配置。
|
||||
- **Secrets 写法**:Actions **secrets 须为原始值**(PEM、PAT 明文),**勿** base64;否则 SSH/Release 会失败。**勿**在 CI 中保存 `GOOGLE_CLIENT_SECRET`、DB 密码。
|
||||
- **通知**:`vars.WEBHOOK_URL`(可选,飞书)。
|
||||
|
||||
## 环境变量
|
||||
## 环境变量(secrets-mcp)
|
||||
|
||||
| 变量 | 说明 |
|
||||
|------|------|
|
||||
| `DATABASE_URL` | PostgreSQL 连接串,优先级高于 `--db-url` 参数 |
|
||||
| `SECRETS_DATABASE_URL` | **必填**。PostgreSQL URL。 |
|
||||
| `SECRETS_DATABASE_SSL_MODE` | 可选但强烈建议生产必填。推荐 `verify-full`(至少 `verify-ca`)。 |
|
||||
| `SECRETS_DATABASE_SSL_ROOT_CERT` | 可选。私有 CA 或自签链路时指定 CA 根证书路径。 |
|
||||
| `SECRETS_DATABASE_POOL_SIZE` | 可选。连接池最大连接数,默认 `10`。 |
|
||||
| `SECRETS_DATABASE_ACQUIRE_TIMEOUT` | 可选。获取连接超时秒数,默认 `5`。 |
|
||||
| `SECRETS_ENV` | 可选。设为 `prod` / `production` 时会拒绝弱 PostgreSQL TLS 模式。 |
|
||||
| `BASE_URL` | 对外基址;OAuth 回调 `${BASE_URL}/auth/google/callback`。 |
|
||||
| `SECRETS_MCP_BIND` | 监听地址,默认 `127.0.0.1:9315`(容器/远程直接暴露时需改为 `0.0.0.0:9315`)。 |
|
||||
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | 可选;仅运行时配置。 |
|
||||
| `RUST_LOG` | 如 `secrets_mcp=debug`。 |
|
||||
| `RATE_LIMIT_GLOBAL_PER_SECOND` | 可选。全局限流速率,默认 `100` req/s。 |
|
||||
| `RATE_LIMIT_GLOBAL_BURST` | 可选。全局限流突发量,默认 `200`。 |
|
||||
| `RATE_LIMIT_IP_PER_SECOND` | 可选。单 IP 限流速率,默认 `20` req/s。 |
|
||||
| `RATE_LIMIT_IP_BURST` | 可选。单 IP 限流突发量,默认 `40`。 |
|
||||
| `TRUST_PROXY` | 可选。设为 `1`/`true`/`yes` 时从 `X-Forwarded-For` / `X-Real-IP` 提取客户端 IP。 |
|
||||
|
||||
> `SERVER_MASTER_KEY` 已不再需要。新架构下密钥由用户密码短语在客户端派生,服务端不持有。
|
||||
|
||||
55
CONTRIBUTING.md
Normal file
55
CONTRIBUTING.md
Normal file
@@ -0,0 +1,55 @@
|
||||
# Contributing
|
||||
|
||||
## 版本控制
|
||||
|
||||
本仓库使用 **[Jujutsu (jj)](https://jj-vcs.dev/)**。请勿使用 `git` 命令。
|
||||
|
||||
```bash
|
||||
jj log # 查看历史
|
||||
jj status # 查看状态
|
||||
jj new # 创建新变更
|
||||
jj commit # 提交
|
||||
jj rebase # 变基
|
||||
jj squash # 合并提交
|
||||
jj git push # 推送到远端
|
||||
```
|
||||
|
||||
详见 [AGENTS.md](AGENTS.md) 的「版本控制」章节。
|
||||
|
||||
## 本地开发
|
||||
|
||||
```bash
|
||||
# 复制环境变量
|
||||
cp deploy/.env.example .env
|
||||
|
||||
# 填写数据库连接等配置后
|
||||
cargo build
|
||||
cargo test --locked
|
||||
```
|
||||
|
||||
## 提交前检查
|
||||
|
||||
每次提交前必须通过:
|
||||
|
||||
```bash
|
||||
cargo fmt -- --check
|
||||
cargo clippy --locked -- -D warnings
|
||||
cargo test --locked
|
||||
```
|
||||
|
||||
或使用脚本:
|
||||
|
||||
```bash
|
||||
./scripts/release-check.sh
|
||||
```
|
||||
|
||||
## 发版规则
|
||||
|
||||
涉及 `crates/**`、根目录 `Cargo.toml`/`Cargo.lock`、`secrets-mcp` 行为变更的提交,默认需要发版。
|
||||
|
||||
1. 检查 `crates/secrets-mcp/Cargo.toml` 的 `version`
|
||||
2. 运行 `jj tag list` 确认对应 tag 是否已存在
|
||||
3. 若 tag 已存在且有代码变更,**必须 bump 版本**并 `cargo build` 同步 `Cargo.lock`
|
||||
4. 通过 release-check 后再提交
|
||||
|
||||
详见 [AGENTS.md](AGENTS.md) 的「提交 / 推送硬规则」章节。
|
||||
1652
Cargo.lock
generated
1652
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
51
Cargo.toml
51
Cargo.toml
@@ -1,16 +1,39 @@
|
||||
[package]
|
||||
name = "secrets"
|
||||
version = "0.2.0"
|
||||
[workspace]
|
||||
members = [
|
||||
"crates/secrets-core",
|
||||
"crates/secrets-mcp",
|
||||
]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.102"
|
||||
chrono = { version = "0.4.44", features = ["serde"] }
|
||||
clap = { version = "4.6.0", features = ["derive", "env"] }
|
||||
dotenvy = "0.15.7"
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = "1.0.149"
|
||||
sqlx = { version = "0.8.6", features = ["runtime-tokio", "tls-rustls", "postgres", "uuid", "json", "chrono"] }
|
||||
tokio = { version = "1.50.0", features = ["full"] }
|
||||
toml = "1.0.7"
|
||||
uuid = { version = "1.22.0", features = ["serde", "v4"] }
|
||||
[workspace.dependencies]
|
||||
# Async runtime
|
||||
tokio = { version = "^1.50.0", features = ["rt-multi-thread", "macros", "fs", "io-util", "process", "signal"] }
|
||||
|
||||
# Database
|
||||
sqlx = { version = "^0.8.6", features = ["runtime-tokio", "tls-rustls", "postgres", "uuid", "json", "chrono"] }
|
||||
|
||||
# Serialization
|
||||
serde = { version = "^1.0.228", features = ["derive"] }
|
||||
serde_json = "^1.0.149"
|
||||
serde_yaml = "^0.9"
|
||||
toml = "^1.0.7"
|
||||
|
||||
# Crypto
|
||||
aes-gcm = "^0.10.3"
|
||||
sha2 = "^0.10.9"
|
||||
rand = "^0.10.0"
|
||||
|
||||
# Utils
|
||||
anyhow = "^1.0.102"
|
||||
thiserror = "^2"
|
||||
chrono = { version = "^0.4.44", features = ["serde"] }
|
||||
uuid = { version = "^1.22.0", features = ["serde"] }
|
||||
tracing = "^0.1"
|
||||
tracing-subscriber = { version = "^0.3", features = ["env-filter"] }
|
||||
dotenvy = "^0.15"
|
||||
|
||||
# HTTP
|
||||
reqwest = { version = "^0.12", default-features = false, features = ["rustls-tls", "json"] }
|
||||
|
||||
285
README.md
285
README.md
@@ -1,111 +1,254 @@
|
||||
# secrets
|
||||
# secrets-mcp
|
||||
|
||||
跨设备密钥与配置管理 CLI,基于 Rust + PostgreSQL 18。
|
||||
|
||||
将服务器信息、服务凭据统一存入数据库,供本地工具和 AI 读取上下文。
|
||||
Workspace:**`secrets-core`** + **`secrets-mcp`**(HTTP Streamable MCP + Web)。多租户密钥与元数据存 PostgreSQL;用户通过 **Google OAuth** 登录,**API Key** 鉴权 MCP 请求;秘密数据用**用户密码短语派生的密钥**在客户端加密,服务端不持有原始密钥。
|
||||
|
||||
## 安装
|
||||
|
||||
```bash
|
||||
cargo build --release
|
||||
# 或从 Release 页面下载预编译二进制
|
||||
cargo build --release -p secrets-mcp
|
||||
# 产物: target/release/secrets-mcp
|
||||
```
|
||||
|
||||
配置数据库连接:
|
||||
发版产物见 Gitea Release(tag:`secrets-mcp-<version>`,Linux musl 预编译);其它平台本地 `cargo build`。
|
||||
|
||||
## 环境变量与本地运行
|
||||
|
||||
复制 `deploy/.env.example` 为项目根目录 `.env`(已在 `.gitignore`),或导出同名变量:
|
||||
|
||||
| 变量 | 说明 |
|
||||
|------|------|
|
||||
| `SECRETS_DATABASE_URL` | **必填**。PostgreSQL 连接串(推荐使用域名,例如 `db.refining.ltd`,避免直连 IP)。 |
|
||||
| `SECRETS_DATABASE_SSL_MODE` | 可选但强烈建议生产必填。推荐 `verify-full`(至少 `verify-ca`),避免回退到弱 TLS 模式。 |
|
||||
| `SECRETS_DATABASE_SSL_ROOT_CERT` | 可选。私有 CA 或自签链路时指定 CA 根证书路径(如 `/etc/secrets/pg-ca.crt`)。 |
|
||||
| `SECRETS_ENV` | 可选。设为 `prod` / `production` 时会拒绝弱 PostgreSQL TLS 模式(`prefer`、`disable`、`allow`、`require`)。 |
|
||||
| `BASE_URL` | 对外访问基址;OAuth 回调为 `{BASE_URL}/auth/google/callback`。默认 `http://localhost:9315`。 |
|
||||
| `SECRETS_MCP_BIND` | 监听地址,默认 `127.0.0.1:9315`。容器内或直接对外暴露端口时请改为 `0.0.0.0:9315`;反代时常为 `127.0.0.1:9315`。 |
|
||||
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | 可选;不配置则无 Google 登录入口。运行时从环境读取,勿写入 CI、勿打入二进制。 |
|
||||
| `RUST_LOG` | 可选;日志级别,如 `secrets_mcp=debug`。 |
|
||||
| `SECRETS_DATABASE_POOL_SIZE` | 可选。连接池最大连接数,默认 `10`。 |
|
||||
| `SECRETS_DATABASE_ACQUIRE_TIMEOUT` | 可选。获取连接超时秒数,默认 `5`。 |
|
||||
| `RATE_LIMIT_GLOBAL_PER_SECOND` | 可选。全局限流速率,默认 `100` req/s。 |
|
||||
| `RATE_LIMIT_GLOBAL_BURST` | 可选。全局限流突发量,默认 `200`。 |
|
||||
| `RATE_LIMIT_IP_PER_SECOND` | 可选。单 IP 限流速率,默认 `20` req/s。 |
|
||||
| `RATE_LIMIT_IP_BURST` | 可选。单 IP 限流突发量,默认 `40`。 |
|
||||
| `TRUST_PROXY` | 可选。设为 `1`/`true`/`yes` 时从 `X-Forwarded-For` / `X-Real-IP` 提取客户端 IP;仅在反代环境下启用。 |
|
||||
|
||||
```bash
|
||||
export DATABASE_URL=postgres://postgres:<password>@<host>:5432/secrets
|
||||
# 或在项目根目录创建 .env 文件写入上述变量
|
||||
cargo run -p secrets-mcp
|
||||
```
|
||||
|
||||
## 使用
|
||||
生产推荐示例(PostgreSQL TLS):
|
||||
|
||||
```bash
|
||||
# 查看版本
|
||||
secrets -V
|
||||
secrets --version
|
||||
SECRETS_DATABASE_URL=postgres://postgres:***@db.refining.ltd:5432/secrets-mcp
|
||||
SECRETS_DATABASE_SSL_MODE=verify-full
|
||||
SECRETS_DATABASE_SSL_ROOT_CERT=/etc/secrets/pg-ca.crt
|
||||
SECRETS_ENV=production
|
||||
```
|
||||
|
||||
# 查看帮助
|
||||
secrets --help
|
||||
secrets -h
|
||||
- **Web**:`BASE_URL`(登录、Dashboard、设置密码短语、创建 API Key)。
|
||||
- **MCP**:Streamable HTTP 基址 `{BASE_URL}/mcp`,需 `Authorization: Bearer <api_key>` + `X-Encryption-Key: <hex>` 请求头(读密文工具须带密钥)。
|
||||
|
||||
# 查看子命令帮助
|
||||
secrets help add
|
||||
secrets help search
|
||||
secrets help delete
|
||||
secrets help update
|
||||
## PostgreSQL TLS 加固
|
||||
|
||||
# 添加服务器
|
||||
secrets add -n refining --kind server --name my-server \
|
||||
--tag aliyun --tag shanghai \
|
||||
-m ip=1.2.3.4 -m desc="My Server" \
|
||||
-s username=root \
|
||||
-s ssh_key=@./keys/my.pem
|
||||
- 推荐将数据库域名单独设置为 `db.refining.ltd`,服务域名保持 `secrets.refining.app`。
|
||||
- 数据库证书建议使用可校验链路(如 Let's Encrypt 或私有 CA),并保证证书 `SAN` 包含 `db.refining.ltd`。
|
||||
- PostgreSQL 侧建议使用 `hostssl` 规则限制应用来源(如 `47.238.146.244/32`),逐步移除公网明文 `host` 访问。
|
||||
- 应用端推荐 `SECRETS_DATABASE_SSL_MODE=verify-full`;仅在过渡阶段可临时用 `verify-ca`。
|
||||
- 可执行运维步骤见 [`deploy/postgres-tls-hardening.md`](deploy/postgres-tls-hardening.md)。
|
||||
|
||||
# 添加服务凭据
|
||||
secrets add -n refining --kind service --name gitea \
|
||||
-m url=https://gitea.example.com \
|
||||
-s token=<token>
|
||||
## MCP 与 AI 工作流(v0.3+)
|
||||
|
||||
# 搜索(默认隐藏敏感字段)
|
||||
secrets search
|
||||
secrets search -n refining --kind server
|
||||
secrets search --tag hongkong
|
||||
secrets search -q mqtt # 关键词匹配 name / metadata / tags
|
||||
secrets search -n refining --kind service --name gitea --show-secrets
|
||||
条目在逻辑上以 **`(folder, name)`** 在用户内唯一(数据库唯一索引:`user_id + folder + name`)。同名可在不同 folder 下各存一条(例如 `refining/aliyun` 与 `ricnsmart/aliyun`)。
|
||||
|
||||
# 增量更新已有记录(合并语义,记录不存在则报错)
|
||||
secrets update -n refining --kind server --name my-server -m ip=10.0.0.1
|
||||
secrets update -n refining --kind service --name gitea --add-tag production -s token=<new-token>
|
||||
secrets update -n refining --kind service --name mqtt --remove-meta old_port --remove-secret old_key
|
||||
### 工具列表
|
||||
|
||||
# 删除
|
||||
secrets delete -n refining --kind server --name my-server
|
||||
| 工具 | 需要加密密钥 | 说明 |
|
||||
|------|-------------|------|
|
||||
| `secrets_find` | 否 | 发现条目(返回含 secret_fields schema),支持 `name_query` 模糊匹配 |
|
||||
| `secrets_search` | 否 | 搜索条目,支持 `query`/`folder`/`type`/`name` 过滤、`sort`/`offset` 分页、`summary` 摘要模式 |
|
||||
| `secrets_get` | 是 | 按 UUID `id` 获取单条条目及解密后的 secrets |
|
||||
| `secrets_add` | 是 | 添加新条目,支持 `meta_obj`/`secrets_obj` JSON 对象参数、`secret_types` 指定密钥类型、`link_secret_names` 关联已有 secret |
|
||||
| `secrets_update` | 是 | 更新条目,支持 `id` 或 `name`+`folder` 定位 |
|
||||
| `secrets_delete` | 否 | 删除条目,支持 `id` 或 `name`+`folder` 定位;`dry_run=true` 预览删除 |
|
||||
| `secrets_history` | 否 | 查看条目历史,支持 `id` 或 `name`+`folder` 定位 |
|
||||
| `secrets_rollback` | 是 | 回滚条目到指定历史版本,支持 `id` 或 `name`+`folder` 定位 |
|
||||
| `secrets_export` | 是 | 导出条目(含解密明文),支持 JSON/TOML/YAML 格式 |
|
||||
| `secrets_env_map` | 是 | 将 secrets 转换为环境变量映射(`UPPER(entry)_UPPER(field)` 格式),支持 `prefix` |
|
||||
| `secrets_overview` | 否 | 返回各 folder 和 type 的 entry 计数概览 |
|
||||
|
||||
### 消歧规则
|
||||
|
||||
- **按 `name` 定位的工具**(`secrets_update` / `secrets_delete` / `secrets_history` / `secrets_rollback`):若该用户下仅一条匹配则直接执行;若多条(同 `name`、不同 `folder`)则返回错误并提示补全 `folder`。也可直接传 `id`(UUID)跳过消歧。
|
||||
- **`secrets_get`** 仅支持通过 `id`(UUID)获取。
|
||||
- **`secrets_delete`** 的 `dry_run=true` 与真实删除使用相同消歧规则——唯一则预览一条,多条则报错并要求 `folder`。
|
||||
|
||||
### 共享密钥
|
||||
|
||||
N:N 关联下,删除 entry 仅解除关联,被共享的 secret 若仍被其他 entry 引用则保留;无引用时自动清理。
|
||||
|
||||
## 加密架构(混合 E2EE)
|
||||
|
||||
### 密钥派生
|
||||
|
||||
用户在 Web Dashboard 设置**密码短语**,浏览器使用 **Web Crypto API(PBKDF2-SHA256,600k 次迭代)**在本地派生 256-bit AES 密钥。
|
||||
|
||||
- **Salt(32B)**:首次设置时在浏览器生成,存入服务端 `users.key_salt`
|
||||
- **key_check**:派生密钥加密已知常量 `"secrets-mcp-key-check"`,存入 `users.key_check`,用于登录时验证密码短语
|
||||
- **服务端不存储原始密钥**,只存 salt + key_check
|
||||
|
||||
跨设备同步:新设备登录 → 输入相同密码短语 → 从服务端取 salt → 同样的 PBKDF2 → 得到相同密钥。
|
||||
|
||||
### 写入与读取流程
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph Web["Web 浏览器(E2E)"]
|
||||
P["密码短语"] --> K["PBKDF2 → 256-bit key"]
|
||||
K --> Enc["AES-256-GCM 加密"]
|
||||
K --> Dec["AES-256-GCM 解密"]
|
||||
end
|
||||
|
||||
subgraph AI["AI 客户端(MCP)"]
|
||||
HdrKey["X-Encryption-Key: hex"]
|
||||
end
|
||||
|
||||
subgraph Server["secrets-mcp 服务端"]
|
||||
Middleware["请求中临时持有 key\n请求结束即丢弃"]
|
||||
DB[(PostgreSQL\nsecrets.encrypted = 密文\nentries.metadata = 明文)]
|
||||
end
|
||||
|
||||
Enc -->|密文| Server
|
||||
HdrKey -->|key + 请求| Middleware
|
||||
Middleware <-->|加解密| DB
|
||||
DB -->|密文| Dec
|
||||
```
|
||||
|
||||
### 两种客户端对比
|
||||
|
||||
| | Web 浏览器 | AI 客户端(MCP) |
|
||||
|---|---|---|
|
||||
| 密钥位置 | 仅在浏览器内存 / sessionStorage | MCP 配置 headers 中 |
|
||||
| 加解密位置 | 客户端(真正 E2E) | 服务端临时(请求级生命周期) |
|
||||
| 安全边界 | 服务端零知识 | 依赖 TLS + 服务端内存隔离 |
|
||||
|
||||
### 敏感数据传输
|
||||
|
||||
- **OAuth `client_secret`** 只存服务端环境变量,不发给浏览器
|
||||
- **API Key** 当前存放在 `users.api_key`,Dashboard 会明文展示并可重置
|
||||
- **X-Encryption-Key** 随 MCP 请求经 TLS 传输,服务端仅在请求处理期间持有(不持久化)
|
||||
- **生产环境必须走 HTTPS/TLS**
|
||||
|
||||
## AI 客户端配置
|
||||
|
||||
在 Web Dashboard 设置密码短语后,解锁页面会按客户端格式生成配置。常见客户端示例如下:
|
||||
|
||||
`Cursor / Claude Desktop` 风格:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"secrets": {
|
||||
"url": "https://secrets.example.com/mcp",
|
||||
"headers": {
|
||||
"Authorization": "Bearer sk_abc123...",
|
||||
"X-Encryption-Key": "a1b2c3...(64位hex)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`OpenCode` 风格:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcp": {
|
||||
"secrets": {
|
||||
"type": "remote",
|
||||
"enabled": true,
|
||||
"url": "https://secrets.example.com/mcp",
|
||||
"headers": {
|
||||
"Authorization": "Bearer sk_abc123...",
|
||||
"X-Encryption-Key": "a1b2c3...(64位hex)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 数据模型
|
||||
|
||||
单张 `secrets` 表,首次连接自动建表。
|
||||
主表 **`entries`**(`folder`、`type`、`name`、`notes`、`tags`、`metadata`,多租户时带 `user_id`)+ 子表 **`secrets`**(每行一个加密字段:`name`、`type`、`encrypted`,通过 `entry_secrets` 中间表与 entry 建立 N:N 关联)。**唯一性**:`UNIQUE(user_id, folder, name)`(`user_id` 为空时为遗留行唯一 `(folder, name)`)。另有 `entries_history`、`secrets_history`、`audit_log`,以及 **`users`**(含 `key_salt`、`key_check`、`key_params`、`api_key`)、**`oauth_accounts`**。首次连库自动迁移建表(`secrets-core` 的 `migrate`);已有库在进程启动时亦由同一 `migrate()` 增量补齐表、索引与 N:N 结构。若需从更早版本对照一次性 SQL,可在 git 历史中检索已移除的 `scripts/migrate-v0.3.0.sql`。**Web 登录会话**(tower-sessions)使用同一 `SECRETS_DATABASE_URL`,进程启动时对会话存储执行迁移(见 `secrets-mcp` 中 `PostgresStore::migrate`),无需额外环境变量。
|
||||
|
||||
| 字段 | 说明 |
|
||||
|------|------|
|
||||
| `namespace` | 一级隔离,如 `refining`、`ricnsmart` |
|
||||
| `kind` | 记录类型,如 `server`、`service`(可自由扩展) |
|
||||
| `name` | 人类可读唯一标识 |
|
||||
| `tags` | 多维标签,如 `["aliyun","hongkong"]` |
|
||||
| `metadata` | 明文描述信息(ip、desc、domains 等) |
|
||||
| `encrypted` | 敏感凭据(ssh_key、password、token 等),MVP 阶段明文存储,预留加密字段 |
|
||||
| 位置 | 字段 | 说明 |
|
||||
|------|------|------|
|
||||
| entries | folder | 组织/隔离空间,如 `refining`、`ricnsmart`;参与唯一键 |
|
||||
| entries | type | 软分类,用户自定义,如 `server`、`service`、`account`、`person`、`document`(不参与唯一键) |
|
||||
| entries | name | 人类可读标识;与 `folder` 一起在用户内唯一 |
|
||||
| entries | notes | 非敏感说明文本 |
|
||||
| entries | metadata | 明文 JSON(ip、url、subtype 等) |
|
||||
| secrets | name | 密钥名称(调用方提供) |
|
||||
| secrets | type | 密钥类型(调用方提供,默认 `text`) |
|
||||
| secrets | encrypted | AES-GCM 密文(含 nonce) |
|
||||
| users | key_salt | PBKDF2 salt(32B),首次设置密码短语时写入 |
|
||||
| users | key_check | 派生密钥加密已知常量,用于验证密码短语 |
|
||||
| users | key_params | 派生算法参数,如 `{"alg":"pbkdf2-sha256","iterations":600000}` |
|
||||
|
||||
`-m` / `--meta` 写入 `metadata`,`-s` / `--secret` 写入 `encrypted`,`value=@file` 从文件读取内容。
|
||||
### 共享密钥(N:N 关联)
|
||||
|
||||
多个条目可共享同一密文字段,通过 `entry_secrets` 中间表实现 N:N 关联:
|
||||
- 添加条目时可通过 `link_secret_names` 参数关联已有的 secret(按 `(user_id, name)` 精确匹配查找)
|
||||
- 同一 secret 可被多个 entry 引用,删除某 entry 不会级联删除被共享的 secret
|
||||
- 当 secret 不再被任何 entry 引用时,自动清理(`NOT EXISTS` 子查询)
|
||||
|
||||
### 类型(Type)
|
||||
|
||||
`type` 字段用于软分类,由用户自由填写,不做任何自动转换或归一化。常见示例:`server`、`service`、`account`、`person`、`document`,但任何值均可接受。
|
||||
|
||||
## 审计日志
|
||||
|
||||
`add`、`update`、`delete` 等写操作写入 **`audit_log`**(操作类型、对象、摘要,不含 secret 明文)。多租户场景下可写 **`user_id`**(可空,兼容遗留行)。
|
||||
业务条目事件使用 **`folder` / `type` / `name`**;登录类事件使用 **`folder='auth'`**,此时 `type`/`name` 表示认证目标(例如 `oauth` / `google`),不表示某条 secrets entry。
|
||||
|
||||
```sql
|
||||
SELECT action, folder, type, name, detail, user_id, created_at
|
||||
FROM audit_log
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 20;
|
||||
```
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
src/
|
||||
main.rs # CLI 入口(clap)
|
||||
db.rs # 连接池 + auto-migrate
|
||||
models.rs # Secret 结构体
|
||||
commands/
|
||||
add.rs # upsert
|
||||
search.rs # 多条件查询
|
||||
delete.rs # 删除
|
||||
update.rs # 增量更新(合并 tags/metadata/encrypted)
|
||||
Cargo.toml
|
||||
crates/secrets-core/ # db / crypto / models / audit / service
|
||||
src/
|
||||
taxonomy.rs # SECRET_TYPE_OPTIONS(secret 字段类型下拉选项)
|
||||
service/ # 业务逻辑(add, search, update, delete, export, env_map 等)
|
||||
crates/secrets-mcp/ # MCP HTTP、Web、OAuth、API Key
|
||||
scripts/
|
||||
seed-data.sh # 导入 refining / ricnsmart 全量数据
|
||||
release-check.sh # 发版前 fmt / clippy / test
|
||||
setup-gitea-actions.sh
|
||||
sync-test-to-prod.sh # 测试库同步到生产(按需)
|
||||
deploy/
|
||||
.env.example # 环境变量模板
|
||||
secrets-mcp.service # systemd 服务文件(生产部署用)
|
||||
postgres-tls-hardening.md # PostgreSQL TLS 加固运维手册
|
||||
```
|
||||
|
||||
## CI/CD(Gitea Actions)
|
||||
|
||||
推送 `main` 分支时自动:fmt/clippy 检查 → musl 构建 → 创建 Release 并上传二进制。
|
||||
见 [`.gitea/workflows/secrets.yml`](.gitea/workflows/secrets.yml)。
|
||||
|
||||
**首次使用需配置 Actions 变量和 Secrets:**
|
||||
- **触发**:任意分支 `push`,且变更路径包含 `crates/**`、`deploy/**`、根目录 `Cargo.toml` / `Cargo.lock`、`.gitea/workflows/**`。
|
||||
- **流水线**:解析 `crates/secrets-mcp/Cargo.toml` 版本 → `cargo fmt` / `clippy --locked` / `test --locked` → 交叉编译 `x86_64-unknown-linux-musl` 的 `secrets-mcp` → 构建成功后打 tag `secrets-mcp-<version>`(若远端已存在同名 tag,会先删除再于**当前提交**重建并推送,覆盖式发版)。
|
||||
- **Release(可选)**:配置仓库 Secret `RELEASE_TOKEN`(Gitea PAT,明文勿 base64)时,会通过 API **创建或更新**已指向该 tag 的 Release(非 draft)、上传 `tar.gz` 与 `.sha256`;未配置则跳过 API Release,仅 tag + 构建结果。
|
||||
- **部署(可选)**:仅在 `main`、`feat/mcp` 或 `mcp` 分支且构建成功时,若已配置 `vars.DEPLOY_HOST`、`vars.DEPLOY_USER` 与 `secrets.DEPLOY_SSH_KEY`,则 `deploy-mcp` 通过 SCP/SSH 更新目标机二进制并 `systemctl restart secrets-mcp`。
|
||||
- **通知(可选)**:`vars.WEBHOOK_URL` 为飞书 Webhook 时,构建/部署/发布节点会推送简要状态。
|
||||
|
||||
```bash
|
||||
# 需有 ~/.config/gitea/config.env(GITEA_URL、GITEA_TOKEN、GITEA_WEBHOOK_URL)
|
||||
./scripts/setup-gitea-actions.sh
|
||||
./scripts/setup-gitea-actions.sh # 通过 Gitea API 写入 RELEASE_TOKEN、WEBHOOK_URL、部署相关变量等
|
||||
```
|
||||
|
||||
- `RELEASE_TOKEN`(Secret):Gitea PAT,用于创建 Release 上传二进制
|
||||
- `WEBHOOK_URL`(Variable):飞书通知,可选
|
||||
|
||||
详见 [AGENTS.md](AGENTS.md)。
|
||||
详见 [AGENTS.md](AGENTS.md)(发版规则、代码规范)。
|
||||
|
||||
27
crates/secrets-core/Cargo.toml
Normal file
27
crates/secrets-core/Cargo.toml
Normal file
@@ -0,0 +1,27 @@
|
||||
[package]
|
||||
name = "secrets-core"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
|
||||
[lib]
|
||||
name = "secrets_core"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
aes-gcm.workspace = true
|
||||
anyhow.workspace = true
|
||||
thiserror.workspace = true
|
||||
chrono.workspace = true
|
||||
hex = "0.4"
|
||||
rand.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
serde_yaml.workspace = true
|
||||
sqlx.workspace = true
|
||||
toml.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
88
crates/secrets-core/src/audit.rs
Normal file
88
crates/secrets-core/src/audit.rs
Normal file
@@ -0,0 +1,88 @@
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{PgPool, Postgres, Transaction};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub const ACTION_LOGIN: &str = "login";
|
||||
pub const FOLDER_AUTH: &str = "auth";
|
||||
|
||||
fn login_detail(provider: &str, client_ip: Option<&str>, user_agent: Option<&str>) -> Value {
|
||||
json!({
|
||||
"provider": provider,
|
||||
"client_ip": client_ip,
|
||||
"user_agent": user_agent,
|
||||
})
|
||||
}
|
||||
|
||||
/// Write a login audit entry without requiring an explicit transaction.
|
||||
pub async fn log_login(
|
||||
pool: &PgPool,
|
||||
entry_type: &str,
|
||||
provider: &str,
|
||||
user_id: Uuid,
|
||||
client_ip: Option<&str>,
|
||||
user_agent: Option<&str>,
|
||||
) {
|
||||
let detail = login_detail(provider, client_ip, user_agent);
|
||||
let result: Result<_, sqlx::Error> = sqlx::query(
|
||||
"INSERT INTO audit_log (user_id, action, folder, type, name, detail) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(ACTION_LOGIN)
|
||||
.bind(FOLDER_AUTH)
|
||||
.bind(entry_type)
|
||||
.bind(provider)
|
||||
.bind(&detail)
|
||||
.execute(pool)
|
||||
.await;
|
||||
|
||||
if let Err(e) = result {
|
||||
tracing::warn!(error = %e, entry_type, provider, "failed to write login audit log");
|
||||
} else {
|
||||
tracing::debug!(entry_type, provider, ?user_id, "login audit logged");
|
||||
}
|
||||
}
|
||||
|
||||
/// Write an audit entry within an existing transaction.
|
||||
pub async fn log_tx(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
user_id: Option<Uuid>,
|
||||
action: &str,
|
||||
folder: &str,
|
||||
entry_type: &str,
|
||||
name: &str,
|
||||
detail: Value,
|
||||
) {
|
||||
let result: Result<_, sqlx::Error> = sqlx::query(
|
||||
"INSERT INTO audit_log (user_id, action, folder, type, name, detail) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(action)
|
||||
.bind(folder)
|
||||
.bind(entry_type)
|
||||
.bind(name)
|
||||
.bind(&detail)
|
||||
.execute(&mut **tx)
|
||||
.await;
|
||||
|
||||
if let Err(e) = result {
|
||||
tracing::warn!(error = %e, "failed to write audit log");
|
||||
} else {
|
||||
tracing::debug!(action, folder, entry_type, name, "audit logged");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn login_detail_includes_expected_fields() {
|
||||
let detail = login_detail("google", Some("127.0.0.1"), Some("Mozilla/5.0"));
|
||||
|
||||
assert_eq!(detail["provider"], "google");
|
||||
assert_eq!(detail["client_ip"], "127.0.0.1");
|
||||
assert_eq!(detail["user_agent"], "Mozilla/5.0");
|
||||
}
|
||||
}
|
||||
82
crates/secrets-core/src/config.rs
Normal file
82
crates/secrets-core/src/config.rs
Normal file
@@ -0,0 +1,82 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use sqlx::postgres::PgSslMode;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DatabaseConfig {
|
||||
pub url: String,
|
||||
pub ssl_mode: Option<PgSslMode>,
|
||||
pub ssl_root_cert: Option<PathBuf>,
|
||||
pub enforce_strict_tls: bool,
|
||||
}
|
||||
|
||||
/// Resolve database URL from environment.
|
||||
/// Priority: `SECRETS_DATABASE_URL` env var → error.
|
||||
pub fn resolve_db_url(override_url: &str) -> Result<String> {
|
||||
if !override_url.is_empty() {
|
||||
return Ok(override_url.to_string());
|
||||
}
|
||||
|
||||
if let Ok(url) = std::env::var("SECRETS_DATABASE_URL")
|
||||
&& !url.is_empty()
|
||||
{
|
||||
return Ok(url);
|
||||
}
|
||||
|
||||
anyhow::bail!(
|
||||
"Database not configured. Set the SECRETS_DATABASE_URL environment variable.\n\
|
||||
Example: SECRETS_DATABASE_URL=postgres://user:pass@host:port/dbname"
|
||||
)
|
||||
}
|
||||
|
||||
fn env_var_non_empty(name: &str) -> Option<String> {
|
||||
std::env::var(name)
|
||||
.ok()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
}
|
||||
|
||||
fn parse_ssl_mode_from_env() -> Result<Option<PgSslMode>> {
|
||||
let Some(mode) = env_var_non_empty("SECRETS_DATABASE_SSL_MODE") else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let parsed = mode.parse::<PgSslMode>().with_context(|| {
|
||||
format!(
|
||||
"Invalid SECRETS_DATABASE_SSL_MODE='{mode}'. Use one of: disable, allow, prefer, require, verify-ca, verify-full."
|
||||
)
|
||||
})?;
|
||||
Ok(Some(parsed))
|
||||
}
|
||||
|
||||
fn resolve_ssl_root_cert_from_env() -> Result<Option<PathBuf>> {
|
||||
let Some(path) = env_var_non_empty("SECRETS_DATABASE_SSL_ROOT_CERT") else {
|
||||
return Ok(None);
|
||||
};
|
||||
let path = PathBuf::from(path);
|
||||
if !path.exists() {
|
||||
anyhow::bail!(
|
||||
"SECRETS_DATABASE_SSL_ROOT_CERT points to a missing file: {}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
Ok(Some(path))
|
||||
}
|
||||
|
||||
fn is_production_env() -> bool {
|
||||
matches!(
|
||||
env_var_non_empty("SECRETS_ENV")
|
||||
.as_deref()
|
||||
.map(|value| value.to_ascii_lowercase()),
|
||||
Some(value) if value == "prod" || value == "production"
|
||||
)
|
||||
}
|
||||
|
||||
pub fn resolve_db_config(override_url: &str) -> Result<DatabaseConfig> {
|
||||
Ok(DatabaseConfig {
|
||||
url: resolve_db_url(override_url)?,
|
||||
ssl_mode: parse_ssl_mode_from_env()?,
|
||||
ssl_root_cert: resolve_ssl_root_cert_from_env()?,
|
||||
enforce_strict_tls: is_production_env(),
|
||||
})
|
||||
}
|
||||
128
crates/secrets-core/src/crypto.rs
Normal file
128
crates/secrets-core/src/crypto.rs
Normal file
@@ -0,0 +1,128 @@
|
||||
use aes_gcm::{
|
||||
Aes256Gcm, Key, Nonce,
|
||||
aead::{Aead, AeadCore, KeyInit, OsRng},
|
||||
};
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::error::AppError;
|
||||
|
||||
const NONCE_LEN: usize = 12;
|
||||
|
||||
// ─── AES-256-GCM encrypt / decrypt ───────────────────────────────────────────
|
||||
|
||||
/// Encrypt plaintext bytes with AES-256-GCM.
|
||||
/// Returns `nonce (12 B) || ciphertext+tag`.
|
||||
pub fn encrypt(master_key: &[u8; 32], plaintext: &[u8]) -> Result<Vec<u8>> {
|
||||
let key = Key::<Aes256Gcm>::from_slice(master_key);
|
||||
let cipher = Aes256Gcm::new(key);
|
||||
let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
|
||||
let ciphertext = cipher
|
||||
.encrypt(&nonce, plaintext)
|
||||
.map_err(|e| anyhow::anyhow!("AES-256-GCM encryption failed: {}", e))?;
|
||||
let mut out = Vec::with_capacity(NONCE_LEN + ciphertext.len());
|
||||
out.extend_from_slice(&nonce);
|
||||
out.extend_from_slice(&ciphertext);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Decrypt `nonce (12 B) || ciphertext+tag` with AES-256-GCM.
|
||||
pub fn decrypt(master_key: &[u8; 32], data: &[u8]) -> Result<Vec<u8>> {
|
||||
if data.len() < NONCE_LEN {
|
||||
bail!(
|
||||
"encrypted data too short ({}B); possibly corrupted",
|
||||
data.len()
|
||||
);
|
||||
}
|
||||
let (nonce_bytes, ciphertext) = data.split_at(NONCE_LEN);
|
||||
let key = Key::<Aes256Gcm>::from_slice(master_key);
|
||||
let cipher = Aes256Gcm::new(key);
|
||||
let nonce = Nonce::from_slice(nonce_bytes);
|
||||
cipher
|
||||
.decrypt(nonce, ciphertext)
|
||||
.map_err(|_| AppError::DecryptionFailed.into())
|
||||
}
|
||||
|
||||
// ─── JSON helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// Serialize a JSON Value and encrypt it. Returns the encrypted blob.
|
||||
pub fn encrypt_json(master_key: &[u8; 32], value: &Value) -> Result<Vec<u8>> {
|
||||
let bytes = serde_json::to_vec(value).context("serialize JSON for encryption")?;
|
||||
encrypt(master_key, &bytes)
|
||||
}
|
||||
|
||||
/// Decrypt an encrypted blob and deserialize it as a JSON Value.
|
||||
pub fn decrypt_json(master_key: &[u8; 32], data: &[u8]) -> Result<Value> {
|
||||
let bytes = decrypt(master_key, data)?;
|
||||
serde_json::from_slice(&bytes).context("deserialize decrypted JSON")
|
||||
}
|
||||
|
||||
// ─── Client-supplied key extraction ──────────────────────────────────────────
|
||||
|
||||
/// Parse a 64-char hex string (from X-Encryption-Key header) into a 32-byte key.
|
||||
pub fn extract_key_from_hex(hex_str: &str) -> Result<[u8; 32]> {
|
||||
let bytes = ::hex::decode(hex_str.trim())?;
|
||||
if bytes.len() != 32 {
|
||||
bail!(
|
||||
"X-Encryption-Key must be 64 hex chars (32 bytes), got {} bytes",
|
||||
bytes.len()
|
||||
);
|
||||
}
|
||||
let mut key = [0u8; 32];
|
||||
key.copy_from_slice(&bytes);
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
// ─── Public hex helpers ───────────────────────────────────────────────────────
|
||||
|
||||
pub mod hex {
|
||||
use anyhow::Result;
|
||||
|
||||
pub fn encode_hex(bytes: &[u8]) -> String {
|
||||
::hex::encode(bytes)
|
||||
}
|
||||
|
||||
pub fn decode_hex(s: &str) -> Result<Vec<u8>> {
|
||||
Ok(::hex::decode(s.trim())?)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn roundtrip_encrypt_decrypt() {
|
||||
let key = [0x42u8; 32];
|
||||
let plaintext = b"hello world";
|
||||
let enc = encrypt(&key, plaintext).unwrap();
|
||||
let dec = decrypt(&key, &enc).unwrap();
|
||||
assert_eq!(dec, plaintext);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encrypt_produces_different_ciphertexts() {
|
||||
let key = [0x42u8; 32];
|
||||
let plaintext = b"hello world";
|
||||
let enc1 = encrypt(&key, plaintext).unwrap();
|
||||
let enc2 = encrypt(&key, plaintext).unwrap();
|
||||
assert_ne!(enc1, enc2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_key_fails_decryption() {
|
||||
let key1 = [0x42u8; 32];
|
||||
let key2 = [0x43u8; 32];
|
||||
let enc = encrypt(&key1, b"secret").unwrap();
|
||||
assert!(decrypt(&key2, &enc).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_roundtrip() {
|
||||
let key = [0x42u8; 32];
|
||||
let value = serde_json::json!({"token": "abc123", "password": "hunter2"});
|
||||
let enc = encrypt_json(&key, &value).unwrap();
|
||||
let dec = decrypt_json(&key, &enc).unwrap();
|
||||
assert_eq!(dec, value);
|
||||
}
|
||||
}
|
||||
639
crates/secrets-core/src/db.rs
Normal file
639
crates/secrets-core/src/db.rs
Normal file
@@ -0,0 +1,639 @@
|
||||
use std::str::FromStr;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use serde_json::{Map, Value};
|
||||
use sqlx::PgPool;
|
||||
use sqlx::postgres::{PgConnectOptions, PgPoolOptions, PgSslMode};
|
||||
|
||||
use crate::config::DatabaseConfig;
|
||||
|
||||
fn build_connect_options(config: &DatabaseConfig) -> Result<PgConnectOptions> {
|
||||
let mut options = PgConnectOptions::from_str(&config.url)
|
||||
.with_context(|| "failed to parse SECRETS_DATABASE_URL".to_string())?;
|
||||
|
||||
if let Some(mode) = config.ssl_mode {
|
||||
options = options.ssl_mode(mode);
|
||||
}
|
||||
if let Some(path) = &config.ssl_root_cert {
|
||||
options = options.ssl_root_cert(path);
|
||||
}
|
||||
|
||||
if config.enforce_strict_tls
|
||||
&& !matches!(
|
||||
options.get_ssl_mode(),
|
||||
PgSslMode::VerifyCa | PgSslMode::VerifyFull
|
||||
)
|
||||
{
|
||||
anyhow::bail!(
|
||||
"Refusing to start in production with weak PostgreSQL TLS mode. \
|
||||
Set SECRETS_DATABASE_SSL_MODE=verify-ca or verify-full."
|
||||
);
|
||||
}
|
||||
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
pub async fn create_pool(config: &DatabaseConfig) -> Result<PgPool> {
|
||||
tracing::debug!("connecting to database");
|
||||
let connect_options = build_connect_options(config)?;
|
||||
|
||||
// Connection pool configuration from environment
|
||||
let max_connections = std::env::var("SECRETS_DATABASE_POOL_SIZE")
|
||||
.ok()
|
||||
.and_then(|v| v.parse::<u32>().ok())
|
||||
.unwrap_or(10);
|
||||
|
||||
let acquire_timeout_secs = std::env::var("SECRETS_DATABASE_ACQUIRE_TIMEOUT")
|
||||
.ok()
|
||||
.and_then(|v| v.parse::<u64>().ok())
|
||||
.unwrap_or(5);
|
||||
|
||||
let pool = PgPoolOptions::new()
|
||||
.max_connections(max_connections)
|
||||
.acquire_timeout(std::time::Duration::from_secs(acquire_timeout_secs))
|
||||
.max_lifetime(std::time::Duration::from_secs(1800)) // 30 minutes
|
||||
.idle_timeout(std::time::Duration::from_secs(600)) // 10 minutes
|
||||
.connect_with(connect_options)
|
||||
.await?;
|
||||
|
||||
tracing::debug!(
|
||||
max_connections,
|
||||
acquire_timeout_secs,
|
||||
"database connection established"
|
||||
);
|
||||
Ok(pool)
|
||||
}
|
||||
|
||||
pub async fn migrate(pool: &PgPool) -> Result<()> {
|
||||
tracing::debug!("running migrations");
|
||||
sqlx::raw_sql(
|
||||
r#"
|
||||
-- ── entries: top-level entities ─────────────────────────────────────────
|
||||
CREATE TABLE IF NOT EXISTS entries (
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||
user_id UUID,
|
||||
folder VARCHAR(128) NOT NULL DEFAULT '',
|
||||
type VARCHAR(64) NOT NULL DEFAULT '',
|
||||
name VARCHAR(256) NOT NULL,
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
tags TEXT[] NOT NULL DEFAULT '{}',
|
||||
metadata JSONB NOT NULL DEFAULT '{}',
|
||||
version BIGINT NOT NULL DEFAULT 1,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Legacy unique constraint without user_id (single-user mode)
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_entries_unique_legacy
|
||||
ON entries(folder, name)
|
||||
WHERE user_id IS NULL;
|
||||
|
||||
-- Multi-user unique constraint
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_entries_unique_user
|
||||
ON entries(user_id, folder, name)
|
||||
WHERE user_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_entries_folder ON entries(folder) WHERE folder <> '';
|
||||
CREATE INDEX IF NOT EXISTS idx_entries_type ON entries(type) WHERE type <> '';
|
||||
CREATE INDEX IF NOT EXISTS idx_entries_user_id ON entries(user_id) WHERE user_id IS NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_entries_tags ON entries USING GIN(tags);
|
||||
CREATE INDEX IF NOT EXISTS idx_entries_metadata ON entries USING GIN(metadata jsonb_path_ops);
|
||||
|
||||
-- ── secrets: one row per encrypted field ─────────────────────────────────
|
||||
CREATE TABLE IF NOT EXISTS secrets (
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||
user_id UUID,
|
||||
name VARCHAR(256) NOT NULL,
|
||||
type VARCHAR(64) NOT NULL DEFAULT 'text',
|
||||
encrypted BYTEA NOT NULL DEFAULT '\x',
|
||||
version BIGINT NOT NULL DEFAULT 1,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_secrets_user_id ON secrets(user_id) WHERE user_id IS NOT NULL;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_secrets_unique_user_name
|
||||
ON secrets(user_id, name) WHERE user_id IS NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_secrets_name ON secrets(name);
|
||||
CREATE INDEX IF NOT EXISTS idx_secrets_type ON secrets(type);
|
||||
|
||||
-- ── entry_secrets: N:N relation ────────────────────────────────────────────
|
||||
CREATE TABLE IF NOT EXISTS entry_secrets (
|
||||
entry_id UUID NOT NULL REFERENCES entries(id) ON DELETE CASCADE,
|
||||
secret_id UUID NOT NULL REFERENCES secrets(id) ON DELETE CASCADE,
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
PRIMARY KEY(entry_id, secret_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_entry_secrets_secret_id ON entry_secrets(secret_id);
|
||||
|
||||
-- ── audit_log: append-only operation log ─────────────────────────────────
|
||||
CREATE TABLE IF NOT EXISTS audit_log (
|
||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
user_id UUID,
|
||||
action VARCHAR(32) NOT NULL,
|
||||
folder VARCHAR(128) NOT NULL DEFAULT '',
|
||||
type VARCHAR(64) NOT NULL DEFAULT '',
|
||||
name VARCHAR(256) NOT NULL,
|
||||
detail JSONB 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_folder_type ON audit_log(folder, type);
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_log_user_id ON audit_log(user_id) WHERE user_id IS NOT NULL;
|
||||
|
||||
-- ── entries_history ───────────────────────────────────────────────────────
|
||||
CREATE TABLE IF NOT EXISTS entries_history (
|
||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
entry_id UUID NOT NULL,
|
||||
folder VARCHAR(128) NOT NULL DEFAULT '',
|
||||
type VARCHAR(64) NOT NULL DEFAULT '',
|
||||
name VARCHAR(256) NOT NULL,
|
||||
version BIGINT NOT NULL,
|
||||
action VARCHAR(16) NOT NULL,
|
||||
tags TEXT[] NOT NULL DEFAULT '{}',
|
||||
metadata JSONB NOT NULL DEFAULT '{}',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_entries_history_entry_id
|
||||
ON entries_history(entry_id, version DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_entries_history_folder_type_name
|
||||
ON entries_history(folder, type, name, version DESC);
|
||||
|
||||
-- Backfill: add user_id to entries_history for multi-tenant isolation
|
||||
ALTER TABLE entries_history ADD COLUMN IF NOT EXISTS user_id UUID;
|
||||
CREATE INDEX IF NOT EXISTS idx_entries_history_user_id
|
||||
ON entries_history(user_id) WHERE user_id IS NOT NULL;
|
||||
ALTER TABLE entries_history DROP COLUMN IF EXISTS actor;
|
||||
|
||||
-- Backfill: add notes to entries if not present (fresh installs already have it)
|
||||
ALTER TABLE entries ADD COLUMN IF NOT EXISTS notes TEXT NOT NULL DEFAULT '';
|
||||
|
||||
-- ── secrets_history: field-level snapshot ────────────────────────────────
|
||||
CREATE TABLE IF NOT EXISTS secrets_history (
|
||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
secret_id UUID NOT NULL,
|
||||
name VARCHAR(256) NOT NULL,
|
||||
encrypted BYTEA NOT NULL DEFAULT '\x',
|
||||
action VARCHAR(16) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_secrets_history_secret_id
|
||||
ON secrets_history(secret_id);
|
||||
|
||||
-- Drop redundant actor column (derivable via entries_history JOIN)
|
||||
ALTER TABLE secrets_history DROP COLUMN IF EXISTS actor;
|
||||
|
||||
-- ── users ─────────────────────────────────────────────────────────────────
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||
email VARCHAR(256),
|
||||
name VARCHAR(256) NOT NULL DEFAULT '',
|
||||
avatar_url TEXT,
|
||||
key_salt BYTEA,
|
||||
key_check BYTEA,
|
||||
key_params JSONB,
|
||||
api_key TEXT UNIQUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- ── oauth_accounts: per-provider identity links ───────────────────────────
|
||||
CREATE TABLE IF NOT EXISTS oauth_accounts (
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
provider VARCHAR(32) NOT NULL,
|
||||
provider_id VARCHAR(256) NOT NULL,
|
||||
email VARCHAR(256),
|
||||
name VARCHAR(256),
|
||||
avatar_url TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE(provider, provider_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_oauth_accounts_user ON oauth_accounts(user_id);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_oauth_accounts_user_provider
|
||||
ON oauth_accounts(user_id, provider);
|
||||
|
||||
-- FK: user_id columns -> users(id) (nullable = legacy rows; ON DELETE SET NULL)
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'fk_entries_user_id'
|
||||
) THEN
|
||||
ALTER TABLE entries
|
||||
ADD CONSTRAINT fk_entries_user_id
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'fk_entries_history_user_id'
|
||||
) THEN
|
||||
ALTER TABLE entries_history
|
||||
ADD CONSTRAINT fk_entries_history_user_id
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'fk_secrets_user_id'
|
||||
) THEN
|
||||
ALTER TABLE secrets
|
||||
ADD CONSTRAINT fk_secrets_user_id
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'fk_audit_log_user_id'
|
||||
) THEN
|
||||
ALTER TABLE audit_log
|
||||
ADD CONSTRAINT fk_audit_log_user_id
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL;
|
||||
END IF;
|
||||
END $$;
|
||||
"#,
|
||||
)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
migrate_schema(pool).await?;
|
||||
restore_plaintext_api_keys(pool).await?;
|
||||
|
||||
tracing::debug!("migrations complete");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Idempotent schema migration: rename namespace→folder, kind→type in existing databases.
|
||||
async fn migrate_schema(pool: &PgPool) -> Result<()> {
|
||||
sqlx::raw_sql(
|
||||
r#"
|
||||
-- ── entries: rename namespace→folder, kind→type ──────────────────────────
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'entries' AND column_name = 'namespace'
|
||||
) THEN
|
||||
ALTER TABLE entries RENAME COLUMN namespace TO folder;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'entries' AND column_name = 'kind'
|
||||
) THEN
|
||||
ALTER TABLE entries RENAME COLUMN kind TO type;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- ── audit_log: rename namespace→folder, kind→type ────────────────────────
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'audit_log' AND column_name = 'namespace'
|
||||
) THEN
|
||||
ALTER TABLE audit_log RENAME COLUMN namespace TO folder;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'audit_log' AND column_name = 'kind'
|
||||
) THEN
|
||||
ALTER TABLE audit_log RENAME COLUMN kind TO type;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- ── entries_history: rename namespace→folder, kind→type ──────────────────
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'entries_history' AND column_name = 'namespace'
|
||||
) THEN
|
||||
ALTER TABLE entries_history RENAME COLUMN namespace TO folder;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'entries_history' AND column_name = 'kind'
|
||||
) THEN
|
||||
ALTER TABLE entries_history RENAME COLUMN kind TO type;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- ── Set empty defaults for new folder/type columns ────────────────────────
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'entries' AND column_name = 'folder'
|
||||
) THEN
|
||||
UPDATE entries SET folder = '' WHERE folder IS NULL;
|
||||
ALTER TABLE entries ALTER COLUMN folder SET NOT NULL;
|
||||
ALTER TABLE entries ALTER COLUMN folder SET DEFAULT '';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'entries' AND column_name = 'type'
|
||||
) THEN
|
||||
UPDATE entries SET type = '' WHERE type IS NULL;
|
||||
ALTER TABLE entries ALTER COLUMN type SET NOT NULL;
|
||||
ALTER TABLE entries ALTER COLUMN type SET DEFAULT '';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'audit_log' AND column_name = 'folder'
|
||||
) THEN
|
||||
UPDATE audit_log SET folder = '' WHERE folder IS NULL;
|
||||
ALTER TABLE audit_log ALTER COLUMN folder SET NOT NULL;
|
||||
ALTER TABLE audit_log ALTER COLUMN folder SET DEFAULT '';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'audit_log' AND column_name = 'type'
|
||||
) THEN
|
||||
UPDATE audit_log SET type = '' WHERE type IS NULL;
|
||||
ALTER TABLE audit_log ALTER COLUMN type SET NOT NULL;
|
||||
ALTER TABLE audit_log ALTER COLUMN type SET DEFAULT '';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'entries_history' AND column_name = 'folder'
|
||||
) THEN
|
||||
UPDATE entries_history SET folder = '' WHERE folder IS NULL;
|
||||
ALTER TABLE entries_history ALTER COLUMN folder SET NOT NULL;
|
||||
ALTER TABLE entries_history ALTER COLUMN folder SET DEFAULT '';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'entries_history' AND column_name = 'type'
|
||||
) THEN
|
||||
UPDATE entries_history SET type = '' WHERE type IS NULL;
|
||||
ALTER TABLE entries_history ALTER COLUMN type SET NOT NULL;
|
||||
ALTER TABLE entries_history ALTER COLUMN type SET DEFAULT '';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- ── Rebuild unique indexes on entries: folder is now part of the key ────────
|
||||
-- (user_id, folder, name) allows same name in different folders.
|
||||
DROP INDEX IF EXISTS idx_entries_unique_legacy;
|
||||
DROP INDEX IF EXISTS idx_entries_unique_user;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_entries_unique_legacy
|
||||
ON entries(folder, name)
|
||||
WHERE user_id IS NULL;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_entries_unique_user
|
||||
ON entries(user_id, folder, name)
|
||||
WHERE user_id IS NOT NULL;
|
||||
|
||||
-- ── Replace old namespace/kind indexes ────────────────────────────────────
|
||||
DROP INDEX IF EXISTS idx_entries_namespace;
|
||||
DROP INDEX IF EXISTS idx_entries_kind;
|
||||
DROP INDEX IF EXISTS idx_audit_log_ns_kind;
|
||||
DROP INDEX IF EXISTS idx_entries_history_ns_kind_name;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_entries_folder
|
||||
ON entries(folder) WHERE folder <> '';
|
||||
CREATE INDEX IF NOT EXISTS idx_entries_type
|
||||
ON entries(type) WHERE type <> '';
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_log_folder_type
|
||||
ON audit_log(folder, type);
|
||||
CREATE INDEX IF NOT EXISTS idx_entries_history_folder_type_name
|
||||
ON entries_history(folder, type, name, version DESC);
|
||||
|
||||
-- ── Drop legacy actor columns ─────────────────────────────────────────────
|
||||
ALTER TABLE secrets_history DROP COLUMN IF EXISTS actor;
|
||||
ALTER TABLE audit_log DROP COLUMN IF EXISTS actor;
|
||||
|
||||
-- ── key_version: incremented on passphrase change to invalidate other sessions ──
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS key_version BIGINT NOT NULL DEFAULT 0;
|
||||
"#,
|
||||
)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn restore_plaintext_api_keys(pool: &PgPool) -> Result<()> {
|
||||
let has_users_api_key: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema = 'public'
|
||||
AND table_name = 'users'
|
||||
AND column_name = 'api_key'
|
||||
)",
|
||||
)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
|
||||
if !has_users_api_key {
|
||||
sqlx::query("ALTER TABLE users ADD COLUMN api_key TEXT")
|
||||
.execute(pool)
|
||||
.await?;
|
||||
sqlx::query("CREATE UNIQUE INDEX IF NOT EXISTS idx_users_api_key ON users(api_key) WHERE api_key IS NOT NULL")
|
||||
.execute(pool)
|
||||
.await?;
|
||||
}
|
||||
|
||||
let has_api_keys_table: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.tables
|
||||
WHERE table_schema = 'public'
|
||||
AND table_name = 'api_keys'
|
||||
)",
|
||||
)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
|
||||
if !has_api_keys_table {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct UserWithoutKey {
|
||||
id: uuid::Uuid,
|
||||
}
|
||||
|
||||
let users_without_key: Vec<UserWithoutKey> =
|
||||
sqlx::query_as("SELECT DISTINCT user_id AS id FROM api_keys WHERE user_id NOT IN (SELECT id FROM users WHERE api_key IS NOT NULL)")
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
|
||||
for user in users_without_key {
|
||||
let new_key = crate::service::api_key::generate_api_key();
|
||||
sqlx::query("UPDATE users SET api_key = $1 WHERE id = $2")
|
||||
.bind(&new_key)
|
||||
.bind(user.id)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
}
|
||||
|
||||
sqlx::query("DROP TABLE IF EXISTS api_keys")
|
||||
.execute(pool)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ── Entry-level history snapshot ─────────────────────────────────────────────
|
||||
|
||||
pub struct EntrySnapshotParams<'a> {
|
||||
pub entry_id: uuid::Uuid,
|
||||
pub user_id: Option<uuid::Uuid>,
|
||||
pub folder: &'a str,
|
||||
pub entry_type: &'a str,
|
||||
pub name: &'a str,
|
||||
pub version: i64,
|
||||
pub action: &'a str,
|
||||
pub tags: &'a [String],
|
||||
pub metadata: &'a Value,
|
||||
}
|
||||
|
||||
pub async fn snapshot_entry_history(
|
||||
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
p: EntrySnapshotParams<'_>,
|
||||
) -> Result<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO entries_history \
|
||||
(entry_id, folder, type, name, version, action, tags, metadata, user_id) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)",
|
||||
)
|
||||
.bind(p.entry_id)
|
||||
.bind(p.folder)
|
||||
.bind(p.entry_type)
|
||||
.bind(p.name)
|
||||
.bind(p.version)
|
||||
.bind(p.action)
|
||||
.bind(p.tags)
|
||||
.bind(p.metadata)
|
||||
.bind(p.user_id)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ── Secret field-level history snapshot ──────────────────────────────────────
|
||||
|
||||
pub struct SecretSnapshotParams<'a> {
|
||||
pub secret_id: uuid::Uuid,
|
||||
pub name: &'a str,
|
||||
pub encrypted: &'a [u8],
|
||||
pub action: &'a str,
|
||||
}
|
||||
|
||||
pub async fn snapshot_secret_history(
|
||||
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
p: SecretSnapshotParams<'_>,
|
||||
) -> Result<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO secrets_history \
|
||||
(secret_id, name, encrypted, action) \
|
||||
VALUES ($1, $2, $3, $4)",
|
||||
)
|
||||
.bind(p.secret_id)
|
||||
.bind(p.name)
|
||||
.bind(p.encrypted)
|
||||
.bind(p.action)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub const ENTRY_HISTORY_SECRETS_KEY: &str = "__secrets_snapshot_v1";
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct EntrySecretSnapshot {
|
||||
pub name: String,
|
||||
#[serde(rename = "type")]
|
||||
pub secret_type: String,
|
||||
pub encrypted_hex: String,
|
||||
}
|
||||
|
||||
pub async fn metadata_with_secret_snapshot(
|
||||
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
entry_id: uuid::Uuid,
|
||||
metadata: &Value,
|
||||
) -> Result<Value> {
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct Row {
|
||||
name: String,
|
||||
#[sqlx(rename = "type")]
|
||||
secret_type: String,
|
||||
encrypted: Vec<u8>,
|
||||
}
|
||||
|
||||
let rows: Vec<Row> = sqlx::query_as(
|
||||
"SELECT s.name, s.type, s.encrypted \
|
||||
FROM entry_secrets es \
|
||||
JOIN secrets s ON s.id = es.secret_id \
|
||||
WHERE es.entry_id = $1 \
|
||||
ORDER BY s.name ASC",
|
||||
)
|
||||
.bind(entry_id)
|
||||
.fetch_all(&mut **tx)
|
||||
.await?;
|
||||
|
||||
let snapshots: Vec<EntrySecretSnapshot> = rows
|
||||
.into_iter()
|
||||
.map(|r| EntrySecretSnapshot {
|
||||
name: r.name,
|
||||
secret_type: r.secret_type,
|
||||
encrypted_hex: ::hex::encode(r.encrypted),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut merged = match metadata.clone() {
|
||||
Value::Object(obj) => obj,
|
||||
_ => Map::new(),
|
||||
};
|
||||
merged.insert(
|
||||
ENTRY_HISTORY_SECRETS_KEY.to_string(),
|
||||
serde_json::to_value(snapshots)?,
|
||||
);
|
||||
Ok(Value::Object(merged))
|
||||
}
|
||||
|
||||
pub fn strip_secret_snapshot_from_metadata(metadata: &Value) -> Value {
|
||||
let mut m = match metadata.clone() {
|
||||
Value::Object(obj) => obj,
|
||||
_ => return metadata.clone(),
|
||||
};
|
||||
m.remove(ENTRY_HISTORY_SECRETS_KEY);
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
pub fn entry_secret_snapshot_from_metadata(metadata: &Value) -> Option<Vec<EntrySecretSnapshot>> {
|
||||
let Value::Object(map) = metadata else {
|
||||
return None;
|
||||
};
|
||||
let raw = map.get(ENTRY_HISTORY_SECRETS_KEY)?;
|
||||
serde_json::from_value(raw.clone()).ok()
|
||||
}
|
||||
|
||||
// ── DB helpers ────────────────────────────────────────────────────────────────
|
||||
172
crates/secrets-core/src/error.rs
Normal file
172
crates/secrets-core/src/error.rs
Normal file
@@ -0,0 +1,172 @@
|
||||
use sqlx::error::DatabaseError;
|
||||
|
||||
/// Structured business errors for the secrets service.
|
||||
///
|
||||
/// These replace ad-hoc `anyhow` strings for expected failure modes,
|
||||
/// allowing MCP and Web layers to map to appropriate protocol-level errors.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum AppError {
|
||||
#[error("A secret with the name '{secret_name}' already exists for this user")]
|
||||
ConflictSecretName { secret_name: String },
|
||||
|
||||
#[error("An entry with folder='{folder}' and name='{name}' already exists")]
|
||||
ConflictEntryName { folder: String, name: String },
|
||||
|
||||
#[error("Entry not found")]
|
||||
NotFoundEntry,
|
||||
|
||||
#[error("User not found")]
|
||||
NotFoundUser,
|
||||
|
||||
#[error("Secret not found")]
|
||||
NotFoundSecret,
|
||||
|
||||
#[error("Authentication failed")]
|
||||
AuthenticationFailed,
|
||||
|
||||
#[error("Unauthorized: insufficient permissions")]
|
||||
Unauthorized,
|
||||
|
||||
#[error("Validation failed: {message}")]
|
||||
Validation { message: String },
|
||||
|
||||
#[error("Concurrent modification detected")]
|
||||
ConcurrentModification,
|
||||
|
||||
#[error("Decryption failed — the encryption key may be incorrect")]
|
||||
DecryptionFailed,
|
||||
|
||||
#[error("Encryption key not set — user must set passphrase first")]
|
||||
EncryptionKeyNotSet,
|
||||
|
||||
#[error(transparent)]
|
||||
Internal(#[from] anyhow::Error),
|
||||
}
|
||||
|
||||
impl AppError {
|
||||
/// Try to convert a sqlx database error into a structured `AppError`.
|
||||
///
|
||||
/// The caller should provide the context (which table was being written,
|
||||
/// what values were being inserted) so we can produce a meaningful error.
|
||||
pub fn from_db_error(err: sqlx::Error, ctx: DbErrorContext<'_>) -> Self {
|
||||
if let sqlx::Error::Database(ref db_err) = err
|
||||
&& db_err.code().as_deref() == Some("23505")
|
||||
{
|
||||
return Self::from_unique_violation(db_err.as_ref(), ctx);
|
||||
}
|
||||
AppError::Internal(err.into())
|
||||
}
|
||||
|
||||
fn from_unique_violation(db_err: &dyn DatabaseError, ctx: DbErrorContext<'_>) -> Self {
|
||||
let constraint = db_err.constraint();
|
||||
|
||||
match constraint {
|
||||
Some("idx_secrets_unique_user_name") => AppError::ConflictSecretName {
|
||||
secret_name: ctx.secret_name.unwrap_or("unknown").to_string(),
|
||||
},
|
||||
Some("idx_entries_unique_user") | Some("idx_entries_unique_legacy") => {
|
||||
AppError::ConflictEntryName {
|
||||
folder: ctx.folder.unwrap_or("").to_string(),
|
||||
name: ctx.name.unwrap_or("unknown").to_string(),
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// Fall back to message-based detection for unnamed constraints
|
||||
let msg = db_err.message();
|
||||
if msg.contains("secrets") {
|
||||
AppError::ConflictSecretName {
|
||||
secret_name: ctx.secret_name.unwrap_or("unknown").to_string(),
|
||||
}
|
||||
} else {
|
||||
AppError::ConflictEntryName {
|
||||
folder: ctx.folder.unwrap_or("").to_string(),
|
||||
name: ctx.name.unwrap_or("unknown").to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Context hints used when converting a database error to `AppError`.
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
pub struct DbErrorContext<'a> {
|
||||
pub secret_name: Option<&'a str>,
|
||||
pub folder: Option<&'a str>,
|
||||
pub name: Option<&'a str>,
|
||||
}
|
||||
|
||||
impl<'a> DbErrorContext<'a> {
|
||||
pub fn secret_name(name: &'a str) -> Self {
|
||||
Self {
|
||||
secret_name: Some(name),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn entry(folder: &'a str, name: &'a str) -> Self {
|
||||
Self {
|
||||
folder: Some(folder),
|
||||
name: Some(name),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn app_error_display_messages() {
|
||||
let err = AppError::ConflictSecretName {
|
||||
secret_name: "token".to_string(),
|
||||
};
|
||||
assert!(err.to_string().contains("token"));
|
||||
|
||||
let err = AppError::ConflictEntryName {
|
||||
folder: "refining".to_string(),
|
||||
name: "gitea".to_string(),
|
||||
};
|
||||
assert!(err.to_string().contains("refining"));
|
||||
assert!(err.to_string().contains("gitea"));
|
||||
|
||||
let err = AppError::NotFoundEntry;
|
||||
assert_eq!(err.to_string(), "Entry not found");
|
||||
|
||||
let err = AppError::NotFoundUser;
|
||||
assert_eq!(err.to_string(), "User not found");
|
||||
|
||||
let err = AppError::NotFoundSecret;
|
||||
assert_eq!(err.to_string(), "Secret not found");
|
||||
|
||||
let err = AppError::AuthenticationFailed;
|
||||
assert_eq!(err.to_string(), "Authentication failed");
|
||||
|
||||
let err = AppError::Unauthorized;
|
||||
assert!(err.to_string().contains("Unauthorized"));
|
||||
|
||||
let err = AppError::Validation {
|
||||
message: "too long".to_string(),
|
||||
};
|
||||
assert!(err.to_string().contains("too long"));
|
||||
|
||||
let err = AppError::ConcurrentModification;
|
||||
assert!(err.to_string().contains("Concurrent modification"));
|
||||
|
||||
let err = AppError::EncryptionKeyNotSet;
|
||||
assert!(err.to_string().contains("Encryption key not set"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn db_error_context_helpers() {
|
||||
let ctx = DbErrorContext::secret_name("my_key");
|
||||
assert_eq!(ctx.secret_name, Some("my_key"));
|
||||
assert!(ctx.folder.is_none());
|
||||
|
||||
let ctx = DbErrorContext::entry("prod", "db-creds");
|
||||
assert_eq!(ctx.folder, Some("prod"));
|
||||
assert_eq!(ctx.name, Some("db-creds"));
|
||||
assert!(ctx.secret_name.is_none());
|
||||
}
|
||||
}
|
||||
8
crates/secrets-core/src/lib.rs
Normal file
8
crates/secrets-core/src/lib.rs
Normal file
@@ -0,0 +1,8 @@
|
||||
pub mod audit;
|
||||
pub mod config;
|
||||
pub mod crypto;
|
||||
pub mod db;
|
||||
pub mod error;
|
||||
pub mod models;
|
||||
pub mod service;
|
||||
pub mod taxonomy;
|
||||
309
crates/secrets-core/src/models.rs
Normal file
309
crates/secrets-core/src/models.rs
Normal file
@@ -0,0 +1,309 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// A top-level entry (server, service, account, person, …).
|
||||
/// Sensitive fields are stored separately in `secrets`.
|
||||
#[derive(Debug, Serialize, Deserialize, sqlx::FromRow)]
|
||||
pub struct Entry {
|
||||
pub id: Uuid,
|
||||
pub user_id: Option<Uuid>,
|
||||
pub folder: String,
|
||||
#[serde(rename = "type")]
|
||||
#[sqlx(rename = "type")]
|
||||
pub entry_type: String,
|
||||
pub name: String,
|
||||
pub notes: String,
|
||||
pub tags: Vec<String>,
|
||||
pub metadata: Value,
|
||||
pub version: i64,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// A single encrypted field belonging to an Entry.
|
||||
#[derive(Debug, Serialize, Deserialize, sqlx::FromRow)]
|
||||
pub struct SecretField {
|
||||
pub id: Uuid,
|
||||
pub user_id: Option<Uuid>,
|
||||
pub name: String,
|
||||
#[serde(rename = "type")]
|
||||
#[sqlx(rename = "type")]
|
||||
pub secret_type: String,
|
||||
/// AES-256-GCM ciphertext: nonce(12B) || ciphertext+tag
|
||||
pub encrypted: Vec<u8>,
|
||||
pub version: i64,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
// ── Internal query row types (shared across commands) ─────────────────────────
|
||||
|
||||
/// Minimal entry row fetched for write operations (add / update / delete / rollback).
|
||||
#[derive(Debug, sqlx::FromRow)]
|
||||
pub struct EntryRow {
|
||||
pub id: Uuid,
|
||||
pub version: i64,
|
||||
pub folder: String,
|
||||
#[sqlx(rename = "type")]
|
||||
pub entry_type: String,
|
||||
pub tags: Vec<String>,
|
||||
pub metadata: Value,
|
||||
pub notes: String,
|
||||
}
|
||||
|
||||
/// Entry row including `name` (used for id-scoped web / service updates).
|
||||
#[derive(Debug, sqlx::FromRow)]
|
||||
pub struct EntryWriteRow {
|
||||
pub id: Uuid,
|
||||
pub version: i64,
|
||||
pub folder: String,
|
||||
#[sqlx(rename = "type")]
|
||||
pub entry_type: String,
|
||||
pub name: String,
|
||||
pub tags: Vec<String>,
|
||||
pub metadata: Value,
|
||||
pub notes: String,
|
||||
}
|
||||
|
||||
impl From<&EntryWriteRow> for EntryRow {
|
||||
fn from(r: &EntryWriteRow) -> Self {
|
||||
EntryRow {
|
||||
id: r.id,
|
||||
version: r.version,
|
||||
folder: r.folder.clone(),
|
||||
entry_type: r.entry_type.clone(),
|
||||
tags: r.tags.clone(),
|
||||
metadata: r.metadata.clone(),
|
||||
notes: r.notes.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal secret field row fetched before snapshots or cascade deletes.
|
||||
#[derive(Debug, sqlx::FromRow)]
|
||||
pub struct SecretFieldRow {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub encrypted: Vec<u8>,
|
||||
}
|
||||
|
||||
// ── Export / Import types ──────────────────────────────────────────────────────
|
||||
|
||||
/// Supported file formats for export/import.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum ExportFormat {
|
||||
Json,
|
||||
Toml,
|
||||
Yaml,
|
||||
}
|
||||
|
||||
impl std::str::FromStr for ExportFormat {
|
||||
type Err = anyhow::Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s.to_lowercase().as_str() {
|
||||
"json" => Ok(Self::Json),
|
||||
"toml" => Ok(Self::Toml),
|
||||
"yaml" | "yml" => Ok(Self::Yaml),
|
||||
other => anyhow::bail!("Unknown format '{}'. Expected: json, toml, or yaml", other),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ExportFormat {
|
||||
/// Infer format from file extension (.json / .toml / .yaml / .yml).
|
||||
pub fn from_extension(path: &str) -> anyhow::Result<Self> {
|
||||
let ext = path.rsplit('.').next().unwrap_or("").to_lowercase();
|
||||
ext.parse().map_err(|_| {
|
||||
anyhow::anyhow!(
|
||||
"Cannot infer format from extension '.{}'. Use --format json|toml|yaml",
|
||||
ext
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Serialize ExportData to a string in this format.
|
||||
pub fn serialize(&self, data: &ExportData) -> anyhow::Result<String> {
|
||||
match self {
|
||||
Self::Json => Ok(serde_json::to_string_pretty(data)?),
|
||||
Self::Toml => {
|
||||
let toml_val = json_to_toml_value(&serde_json::to_value(data)?)?;
|
||||
toml::to_string_pretty(&toml_val)
|
||||
.map_err(|e| anyhow::anyhow!("TOML serialization failed: {}", e))
|
||||
}
|
||||
Self::Yaml => serde_yaml::to_string(data)
|
||||
.map_err(|e| anyhow::anyhow!("YAML serialization failed: {}", e)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Deserialize ExportData from a string in this format.
|
||||
pub fn deserialize(&self, content: &str) -> anyhow::Result<ExportData> {
|
||||
match self {
|
||||
Self::Json => Ok(serde_json::from_str(content)?),
|
||||
Self::Toml => {
|
||||
let toml_val: toml::Value = toml::from_str(content)
|
||||
.map_err(|e| anyhow::anyhow!("TOML parse error: {}", e))?;
|
||||
let json_val = toml_to_json_value(&toml_val);
|
||||
Ok(serde_json::from_value(json_val)?)
|
||||
}
|
||||
Self::Yaml => serde_yaml::from_str(content)
|
||||
.map_err(|e| anyhow::anyhow!("YAML parse error: {}", e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Top-level structure for export/import files.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ExportData {
|
||||
pub version: u32,
|
||||
pub exported_at: String,
|
||||
pub entries: Vec<ExportEntry>,
|
||||
}
|
||||
|
||||
/// A single entry with decrypted secrets for export/import.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ExportEntry {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub folder: String,
|
||||
#[serde(default, rename = "type")]
|
||||
pub entry_type: String,
|
||||
#[serde(default)]
|
||||
pub notes: String,
|
||||
#[serde(default)]
|
||||
pub tags: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub metadata: Value,
|
||||
/// Decrypted secret fields. None means no secrets in this export (--no-secrets).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub secrets: Option<BTreeMap<String, Value>>,
|
||||
}
|
||||
|
||||
// ── Multi-user models ──────────────────────────────────────────────────────────
|
||||
|
||||
/// A registered user (created on first OAuth login).
|
||||
#[derive(Debug, Serialize, Deserialize, sqlx::FromRow)]
|
||||
pub struct User {
|
||||
pub id: Uuid,
|
||||
pub email: Option<String>,
|
||||
pub name: String,
|
||||
pub avatar_url: Option<String>,
|
||||
/// PBKDF2 salt (32 B). NULL until user sets up passphrase.
|
||||
pub key_salt: Option<Vec<u8>>,
|
||||
/// AES-256-GCM encryption of the known constant "secrets-mcp-key-check".
|
||||
/// Used to verify the passphrase without storing the key itself.
|
||||
pub key_check: Option<Vec<u8>>,
|
||||
/// Key derivation parameters, e.g. {"alg":"pbkdf2-sha256","iterations":600000}.
|
||||
pub key_params: Option<serde_json::Value>,
|
||||
/// Plaintext API key for MCP Bearer authentication. Auto-created on first login.
|
||||
pub api_key: Option<String>,
|
||||
/// Incremented each time the passphrase is changed; used to invalidate sessions on other devices.
|
||||
pub key_version: i64,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// An OAuth account linked to a user.
|
||||
#[derive(Debug, Serialize, Deserialize, sqlx::FromRow)]
|
||||
pub struct OauthAccount {
|
||||
pub id: Uuid,
|
||||
pub user_id: Uuid,
|
||||
pub provider: String,
|
||||
pub provider_id: String,
|
||||
pub email: Option<String>,
|
||||
pub name: Option<String>,
|
||||
pub avatar_url: Option<String>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// A single audit log row, optionally scoped to a business user.
|
||||
#[derive(Debug, Serialize, Deserialize, sqlx::FromRow)]
|
||||
pub struct AuditLogEntry {
|
||||
pub id: i64,
|
||||
pub user_id: Option<Uuid>,
|
||||
pub action: String,
|
||||
pub folder: String,
|
||||
#[serde(rename = "type")]
|
||||
#[sqlx(rename = "type")]
|
||||
pub entry_type: String,
|
||||
pub name: String,
|
||||
pub detail: Value,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
// ── TOML ↔ JSON value conversion ──────────────────────────────────────────────
|
||||
|
||||
/// Convert a serde_json Value to a toml Value.
|
||||
/// `null` values are filtered out (TOML does not support null).
|
||||
/// Mixed-type arrays are serialised as JSON strings.
|
||||
pub fn json_to_toml_value(v: &Value) -> anyhow::Result<toml::Value> {
|
||||
match v {
|
||||
Value::Null => anyhow::bail!("TOML does not support null values"),
|
||||
Value::Bool(b) => Ok(toml::Value::Boolean(*b)),
|
||||
Value::Number(n) => {
|
||||
if let Some(i) = n.as_i64() {
|
||||
Ok(toml::Value::Integer(i))
|
||||
} else if let Some(f) = n.as_f64() {
|
||||
Ok(toml::Value::Float(f))
|
||||
} else {
|
||||
anyhow::bail!("unsupported number: {}", n)
|
||||
}
|
||||
}
|
||||
Value::String(s) => Ok(toml::Value::String(s.clone())),
|
||||
Value::Array(arr) => {
|
||||
let items: anyhow::Result<Vec<toml::Value>> =
|
||||
arr.iter().map(json_to_toml_value).collect();
|
||||
match items {
|
||||
Ok(vals) => Ok(toml::Value::Array(vals)),
|
||||
Err(e) => {
|
||||
tracing::debug!(error = %e, "mixed-type array; falling back to JSON string");
|
||||
Ok(toml::Value::String(serde_json::to_string(v)?))
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Object(map) => {
|
||||
let mut toml_map = toml::map::Map::new();
|
||||
for (k, val) in map {
|
||||
if val.is_null() {
|
||||
// Skip null entries
|
||||
continue;
|
||||
}
|
||||
match json_to_toml_value(val) {
|
||||
Ok(tv) => {
|
||||
toml_map.insert(k.clone(), tv);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::debug!(key = %k, error = %e, "field not representable in TOML; falling back to JSON string");
|
||||
toml_map
|
||||
.insert(k.clone(), toml::Value::String(serde_json::to_string(val)?));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(toml::Value::Table(toml_map))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert a toml Value back to a serde_json Value.
|
||||
pub fn toml_to_json_value(v: &toml::Value) -> Value {
|
||||
match v {
|
||||
toml::Value::Boolean(b) => Value::Bool(*b),
|
||||
toml::Value::Integer(i) => Value::Number((*i).into()),
|
||||
toml::Value::Float(f) => serde_json::Number::from_f64(*f)
|
||||
.map(Value::Number)
|
||||
.unwrap_or(Value::Null),
|
||||
toml::Value::String(s) => Value::String(s.clone()),
|
||||
toml::Value::Datetime(dt) => Value::String(dt.to_string()),
|
||||
toml::Value::Array(arr) => Value::Array(arr.iter().map(toml_to_json_value).collect()),
|
||||
toml::Value::Table(map) => {
|
||||
let obj: serde_json::Map<String, Value> = map
|
||||
.iter()
|
||||
.map(|(k, v)| (k.clone(), toml_to_json_value(v)))
|
||||
.collect();
|
||||
Value::Object(obj)
|
||||
}
|
||||
}
|
||||
}
|
||||
811
crates/secrets-core/src/service/add.rs
Normal file
811
crates/secrets-core/src/service/add.rs
Normal file
@@ -0,0 +1,811 @@
|
||||
use anyhow::Result;
|
||||
use serde_json::{Map, Value};
|
||||
use sqlx::PgPool;
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
use std::fs;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::crypto;
|
||||
use crate::db;
|
||||
use crate::error::{AppError, DbErrorContext};
|
||||
use crate::models::EntryRow;
|
||||
|
||||
// ── Key/value parsing helpers ─────────────────────────────────────────────────
|
||||
|
||||
pub fn parse_kv(entry: &str) -> Result<(Vec<String>, Value)> {
|
||||
if let Some((key, json_str)) = entry.split_once(":=") {
|
||||
let val: Value = serde_json::from_str(json_str).map_err(|e| {
|
||||
anyhow::anyhow!(
|
||||
"Invalid JSON value for key '{}': {} (use key=value for plain strings)",
|
||||
key,
|
||||
e
|
||||
)
|
||||
})?;
|
||||
return Ok((parse_key_path(key)?, val));
|
||||
}
|
||||
|
||||
if let Some((key, raw_val)) = entry.split_once('=') {
|
||||
let value = if let Some(path) = raw_val.strip_prefix('@') {
|
||||
fs::read_to_string(path)
|
||||
.map_err(|e| anyhow::anyhow!("Failed to read file '{}': {}", path, e))?
|
||||
} else {
|
||||
raw_val.to_string()
|
||||
};
|
||||
return Ok((parse_key_path(key)?, Value::String(value)));
|
||||
}
|
||||
|
||||
if let Some((key, path)) = entry.split_once('@') {
|
||||
let value = fs::read_to_string(path)
|
||||
.map_err(|e| anyhow::anyhow!("Failed to read file '{}': {}", path, e))?;
|
||||
return Ok((parse_key_path(key)?, Value::String(value)));
|
||||
}
|
||||
|
||||
anyhow::bail!(
|
||||
"Invalid format '{}'. Expected: key=value, key=@file, nested:key@file, or key:=<json>",
|
||||
entry
|
||||
)
|
||||
}
|
||||
|
||||
pub fn build_json(entries: &[String]) -> Result<Value> {
|
||||
let mut map = Map::new();
|
||||
for entry in entries {
|
||||
let (path, value) = parse_kv(entry)?;
|
||||
insert_path(&mut map, &path, value)?;
|
||||
}
|
||||
Ok(Value::Object(map))
|
||||
}
|
||||
|
||||
pub fn key_path_to_string(path: &[String]) -> String {
|
||||
path.join(":")
|
||||
}
|
||||
|
||||
pub fn collect_key_paths(entries: &[String]) -> Result<Vec<String>> {
|
||||
entries
|
||||
.iter()
|
||||
.map(|entry| parse_kv(entry).map(|(path, _)| key_path_to_string(&path)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn collect_field_paths(entries: &[String]) -> Result<Vec<String>> {
|
||||
entries
|
||||
.iter()
|
||||
.map(|entry| parse_key_path(entry).map(|path| key_path_to_string(&path)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn parse_key_path(key: &str) -> Result<Vec<String>> {
|
||||
let path: Vec<String> = key
|
||||
.split(':')
|
||||
.map(str::trim)
|
||||
.map(ToOwned::to_owned)
|
||||
.collect();
|
||||
|
||||
if path.is_empty() || path.iter().any(|part| part.is_empty()) {
|
||||
anyhow::bail!(
|
||||
"Invalid key path '{}'. Use non-empty segments like 'credentials:content'.",
|
||||
key
|
||||
);
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
pub fn insert_path(map: &mut Map<String, Value>, path: &[String], value: Value) -> Result<()> {
|
||||
if path.is_empty() {
|
||||
anyhow::bail!("Key path cannot be empty");
|
||||
}
|
||||
if path.len() == 1 {
|
||||
map.insert(path[0].clone(), value);
|
||||
return Ok(());
|
||||
}
|
||||
let head = path[0].clone();
|
||||
let tail = &path[1..];
|
||||
match map.entry(head.clone()) {
|
||||
serde_json::map::Entry::Vacant(entry) => {
|
||||
let mut child = Map::new();
|
||||
insert_path(&mut child, tail, value)?;
|
||||
entry.insert(Value::Object(child));
|
||||
}
|
||||
serde_json::map::Entry::Occupied(mut entry) => match entry.get_mut() {
|
||||
Value::Object(child) => insert_path(child, tail, value)?,
|
||||
_ => {
|
||||
anyhow::bail!(
|
||||
"Cannot set nested key '{}' because '{}' is already a non-object value",
|
||||
key_path_to_string(path),
|
||||
head
|
||||
);
|
||||
}
|
||||
},
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove_path(map: &mut Map<String, Value>, path: &[String]) -> Result<bool> {
|
||||
if path.is_empty() {
|
||||
anyhow::bail!("Key path cannot be empty");
|
||||
}
|
||||
if path.len() == 1 {
|
||||
return Ok(map.remove(&path[0]).is_some());
|
||||
}
|
||||
let Some(value) = map.get_mut(&path[0]) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let Value::Object(child) = value else {
|
||||
return Ok(false);
|
||||
};
|
||||
let removed = remove_path(child, &path[1..])?;
|
||||
if child.is_empty() {
|
||||
map.remove(&path[0]);
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
pub fn flatten_json_fields(prefix: &str, value: &Value) -> Vec<(String, Value)> {
|
||||
match value {
|
||||
Value::Object(map) => {
|
||||
let mut out = Vec::new();
|
||||
for (k, v) in map {
|
||||
let full_key = if prefix.is_empty() {
|
||||
k.clone()
|
||||
} else {
|
||||
format!("{}.{}", prefix, k)
|
||||
};
|
||||
out.extend(flatten_json_fields(&full_key, v));
|
||||
}
|
||||
out
|
||||
}
|
||||
other => vec![(prefix.to_string(), other.clone())],
|
||||
}
|
||||
}
|
||||
|
||||
// ── AddResult ─────────────────────────────────────────────────────────────────
|
||||
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
pub struct AddResult {
|
||||
pub name: String,
|
||||
pub folder: String,
|
||||
#[serde(rename = "type")]
|
||||
pub entry_type: String,
|
||||
pub tags: Vec<String>,
|
||||
pub meta_keys: Vec<String>,
|
||||
pub secret_keys: Vec<String>,
|
||||
}
|
||||
|
||||
pub struct AddParams<'a> {
|
||||
pub name: &'a str,
|
||||
pub folder: &'a str,
|
||||
pub entry_type: &'a str,
|
||||
pub notes: &'a str,
|
||||
pub tags: &'a [String],
|
||||
pub meta_entries: &'a [String],
|
||||
pub secret_entries: &'a [String],
|
||||
pub secret_types: &'a std::collections::HashMap<String, String>,
|
||||
pub link_secret_names: &'a [String],
|
||||
/// Optional user_id for multi-user isolation (None = single-user CLI mode)
|
||||
pub user_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) -> Result<AddResult> {
|
||||
if params.folder.chars().count() > 128 {
|
||||
anyhow::bail!("folder must be at most 128 characters");
|
||||
}
|
||||
if params.name.chars().count() > 256 {
|
||||
anyhow::bail!("name must be at most 256 characters");
|
||||
}
|
||||
if params.entry_type.trim().chars().count() > 64 {
|
||||
anyhow::bail!("type must be at most 64 characters");
|
||||
}
|
||||
let Value::Object(metadata_map) = build_json(params.meta_entries)? else {
|
||||
unreachable!("build_json always returns a JSON object");
|
||||
};
|
||||
let entry_type = params.entry_type.trim();
|
||||
let metadata = Value::Object(metadata_map);
|
||||
let secret_json = build_json(params.secret_entries)?;
|
||||
let meta_keys = collect_key_paths(params.meta_entries)?;
|
||||
let secret_keys = collect_key_paths(params.secret_entries)?;
|
||||
let flat_fields = flatten_json_fields("", &secret_json);
|
||||
let new_secret_names: BTreeSet<String> =
|
||||
flat_fields.iter().map(|(name, _)| name.clone()).collect();
|
||||
let link_secret_names =
|
||||
validate_link_secret_names(params.link_secret_names, &new_secret_names)?;
|
||||
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
// Fetch existing entry by (user_id, folder, name) — the natural unique key
|
||||
let existing: Option<EntryRow> = if let Some(uid) = params.user_id {
|
||||
sqlx::query_as(
|
||||
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||
WHERE user_id = $1 AND folder = $2 AND name = $3",
|
||||
)
|
||||
.bind(uid)
|
||||
.bind(params.folder)
|
||||
.bind(params.name)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_as(
|
||||
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||
WHERE user_id IS NULL AND folder = $1 AND name = $2",
|
||||
)
|
||||
.bind(params.folder)
|
||||
.bind(params.name)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
};
|
||||
|
||||
if let Some(ref ex) = existing {
|
||||
let history_metadata =
|
||||
match db::metadata_with_secret_snapshot(&mut tx, ex.id, &ex.metadata).await {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "failed to build secret snapshot for entry history");
|
||||
ex.metadata.clone()
|
||||
}
|
||||
};
|
||||
if let Err(e) = db::snapshot_entry_history(
|
||||
&mut tx,
|
||||
db::EntrySnapshotParams {
|
||||
entry_id: ex.id,
|
||||
user_id: params.user_id,
|
||||
folder: params.folder,
|
||||
entry_type,
|
||||
name: params.name,
|
||||
version: ex.version,
|
||||
action: "add",
|
||||
tags: &ex.tags,
|
||||
metadata: &history_metadata,
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to snapshot entry history before upsert");
|
||||
}
|
||||
}
|
||||
|
||||
// Upsert the entry row. On conflict (existing entry with same user_id+folder+name),
|
||||
// the entry columns are replaced wholesale. The old secret associations are torn down
|
||||
// below within the same transaction, so the whole operation is atomic: if any step
|
||||
// after this point fails, the transaction rolls back and the entry reverts to its
|
||||
// pre-upsert state (including the version bump that happened in the DO UPDATE clause).
|
||||
let entry_id: Uuid = if let Some(uid) = params.user_id {
|
||||
sqlx::query_scalar(
|
||||
r#"INSERT INTO entries (user_id, folder, type, name, notes, tags, metadata, version, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, 1, NOW())
|
||||
ON CONFLICT (user_id, folder, name) WHERE user_id IS NOT NULL
|
||||
DO UPDATE SET
|
||||
folder = EXCLUDED.folder,
|
||||
type = EXCLUDED.type,
|
||||
notes = EXCLUDED.notes,
|
||||
tags = EXCLUDED.tags,
|
||||
metadata = EXCLUDED.metadata,
|
||||
version = entries.version + 1,
|
||||
updated_at = NOW()
|
||||
RETURNING id"#,
|
||||
)
|
||||
.bind(uid)
|
||||
.bind(params.folder)
|
||||
.bind(entry_type)
|
||||
.bind(params.name)
|
||||
.bind(params.notes)
|
||||
.bind(params.tags)
|
||||
.bind(&metadata)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_scalar(
|
||||
r#"INSERT INTO entries (folder, type, name, notes, tags, metadata, version, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, 1, NOW())
|
||||
ON CONFLICT (folder, name) WHERE user_id IS NULL
|
||||
DO UPDATE SET
|
||||
folder = EXCLUDED.folder,
|
||||
type = EXCLUDED.type,
|
||||
notes = EXCLUDED.notes,
|
||||
tags = EXCLUDED.tags,
|
||||
metadata = EXCLUDED.metadata,
|
||||
version = entries.version + 1,
|
||||
updated_at = NOW()
|
||||
RETURNING id"#,
|
||||
)
|
||||
.bind(params.folder)
|
||||
.bind(entry_type)
|
||||
.bind(params.name)
|
||||
.bind(params.notes)
|
||||
.bind(params.tags)
|
||||
.bind(&metadata)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?
|
||||
};
|
||||
|
||||
let current_entry_version: i64 =
|
||||
sqlx::query_scalar("SELECT version FROM entries WHERE id = $1")
|
||||
.bind(entry_id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
|
||||
if existing.is_some() {
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct ExistingField {
|
||||
id: Uuid,
|
||||
name: String,
|
||||
encrypted: Vec<u8>,
|
||||
}
|
||||
let existing_fields: Vec<ExistingField> = sqlx::query_as(
|
||||
"SELECT s.id, s.name, s.encrypted \
|
||||
FROM entry_secrets es \
|
||||
JOIN secrets s ON s.id = es.secret_id \
|
||||
WHERE es.entry_id = $1",
|
||||
)
|
||||
.bind(entry_id)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
|
||||
for f in &existing_fields {
|
||||
if let Err(e) = db::snapshot_secret_history(
|
||||
&mut tx,
|
||||
db::SecretSnapshotParams {
|
||||
secret_id: f.id,
|
||||
name: &f.name,
|
||||
encrypted: &f.encrypted,
|
||||
action: "add",
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to snapshot secret field history");
|
||||
}
|
||||
}
|
||||
|
||||
let orphan_candidates: Vec<Uuid> = existing_fields.iter().map(|f| f.id).collect();
|
||||
|
||||
sqlx::query("DELETE FROM entry_secrets WHERE entry_id = $1")
|
||||
.bind(entry_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
if !orphan_candidates.is_empty() {
|
||||
sqlx::query(
|
||||
"DELETE FROM secrets s \
|
||||
WHERE s.id = ANY($1) \
|
||||
AND NOT EXISTS (SELECT 1 FROM entry_secrets es WHERE es.secret_id = s.id)",
|
||||
)
|
||||
.bind(&orphan_candidates)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
|
||||
for (field_name, field_value) in &flat_fields {
|
||||
let encrypted = crypto::encrypt_json(master_key, field_value)?;
|
||||
let secret_type = params
|
||||
.secret_types
|
||||
.get(field_name)
|
||||
.map(|s| s.as_str())
|
||||
.unwrap_or("text");
|
||||
let secret_id: Uuid = sqlx::query_scalar(
|
||||
"INSERT INTO secrets (user_id, name, type, encrypted) VALUES ($1, $2, $3, $4) RETURNING id",
|
||||
)
|
||||
.bind(params.user_id)
|
||||
.bind(field_name)
|
||||
.bind(secret_type)
|
||||
.bind(&encrypted)
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.map_err(|e| AppError::from_db_error(e, DbErrorContext::secret_name(field_name)))?;
|
||||
sqlx::query("INSERT INTO entry_secrets (entry_id, secret_id) VALUES ($1, $2)")
|
||||
.bind(entry_id)
|
||||
.bind(secret_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
|
||||
for link_name in &link_secret_names {
|
||||
let secret_ids: Vec<Uuid> = if let Some(uid) = params.user_id {
|
||||
sqlx::query_scalar("SELECT id FROM secrets WHERE user_id = $1 AND name = $2")
|
||||
.bind(uid)
|
||||
.bind(link_name)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_scalar("SELECT id FROM secrets WHERE user_id IS NULL AND name = $1")
|
||||
.bind(link_name)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?
|
||||
};
|
||||
|
||||
match secret_ids.len() {
|
||||
0 => anyhow::bail!("Not found: secret named '{}'", link_name),
|
||||
1 => {
|
||||
sqlx::query(
|
||||
"INSERT INTO entry_secrets (entry_id, secret_id) VALUES ($1, $2) ON CONFLICT DO NOTHING",
|
||||
)
|
||||
.bind(entry_id)
|
||||
.bind(secret_ids[0])
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
n => anyhow::bail!(
|
||||
"Ambiguous: {} secrets named '{}' found. Please deduplicate names first.",
|
||||
n,
|
||||
link_name
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
if existing.is_none() {
|
||||
let history_metadata =
|
||||
match db::metadata_with_secret_snapshot(&mut tx, entry_id, &metadata).await {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "failed to build secret snapshot for entry history");
|
||||
metadata.clone()
|
||||
}
|
||||
};
|
||||
if let Err(e) = db::snapshot_entry_history(
|
||||
&mut tx,
|
||||
db::EntrySnapshotParams {
|
||||
entry_id,
|
||||
user_id: params.user_id,
|
||||
folder: params.folder,
|
||||
entry_type,
|
||||
name: params.name,
|
||||
version: current_entry_version,
|
||||
action: "create",
|
||||
tags: params.tags,
|
||||
metadata: &history_metadata,
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to snapshot entry history on create");
|
||||
}
|
||||
}
|
||||
|
||||
crate::audit::log_tx(
|
||||
&mut tx,
|
||||
params.user_id,
|
||||
"add",
|
||||
params.folder,
|
||||
entry_type,
|
||||
params.name,
|
||||
serde_json::json!({
|
||||
"tags": params.tags,
|
||||
"meta_keys": meta_keys,
|
||||
"secret_keys": secret_keys,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(AddResult {
|
||||
name: params.name.to_string(),
|
||||
folder: params.folder.to_string(),
|
||||
entry_type: entry_type.to_string(),
|
||||
tags: params.tags.to_vec(),
|
||||
meta_keys,
|
||||
secret_keys,
|
||||
})
|
||||
}
|
||||
|
||||
fn validate_link_secret_names(
|
||||
link_secret_names: &[String],
|
||||
new_secret_names: &BTreeSet<String>,
|
||||
) -> Result<Vec<String>> {
|
||||
let mut deduped = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
|
||||
for raw in link_secret_names {
|
||||
let trimmed = raw.trim();
|
||||
if trimmed.is_empty() {
|
||||
anyhow::bail!("link_secret_names contains an empty name");
|
||||
}
|
||||
if new_secret_names.contains(trimmed) {
|
||||
anyhow::bail!(
|
||||
"Conflict: secret '{}' is provided both in secrets/secrets_obj and link_secret_names",
|
||||
trimmed
|
||||
);
|
||||
}
|
||||
if seen.insert(trimmed.to_string()) {
|
||||
deduped.push(trimmed.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(deduped)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use sqlx::PgPool;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
#[test]
|
||||
fn parse_nested_file_shorthand() {
|
||||
use std::io::Write;
|
||||
let mut f = tempfile::NamedTempFile::new().unwrap();
|
||||
writeln!(f, "line1\nline2").unwrap();
|
||||
let path = f.path().to_str().unwrap().to_string();
|
||||
let entry = format!("credentials:content@{}", path);
|
||||
let (path_parts, value) = parse_kv(&entry).unwrap();
|
||||
assert_eq!(key_path_to_string(&path_parts), "credentials:content");
|
||||
assert!(matches!(value, Value::String(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flatten_json_fields_nested() {
|
||||
let v = serde_json::json!({
|
||||
"username": "root",
|
||||
"credentials": {
|
||||
"type": "ssh",
|
||||
"content": "pem"
|
||||
}
|
||||
});
|
||||
let mut fields = flatten_json_fields("", &v);
|
||||
fields.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
assert_eq!(fields[0].0, "credentials.content");
|
||||
assert_eq!(fields[1].0, "credentials.type");
|
||||
assert_eq!(fields[2].0, "username");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_link_secret_names_conflict_with_new_secret() {
|
||||
let mut new_names = BTreeSet::new();
|
||||
new_names.insert("password".to_string());
|
||||
let err = validate_link_secret_names(&[String::from("password")], &new_names)
|
||||
.expect_err("must fail on overlap");
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("provided both in secrets/secrets_obj and link_secret_names")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_link_secret_names_dedup_and_trim() {
|
||||
let names = vec![
|
||||
" shared_key ".to_string(),
|
||||
"shared_key".to_string(),
|
||||
"runner_token".to_string(),
|
||||
];
|
||||
let deduped = validate_link_secret_names(&names, &BTreeSet::new()).unwrap();
|
||||
assert_eq!(deduped, vec!["shared_key", "runner_token"]);
|
||||
}
|
||||
|
||||
async fn maybe_test_pool() -> Option<PgPool> {
|
||||
let Ok(url) = std::env::var("SECRETS_DATABASE_URL") else {
|
||||
eprintln!("skip add linkage tests: SECRETS_DATABASE_URL is not set");
|
||||
return None;
|
||||
};
|
||||
let Ok(pool) = PgPool::connect(&url).await else {
|
||||
eprintln!("skip add linkage tests: cannot connect to database");
|
||||
return None;
|
||||
};
|
||||
if let Err(e) = crate::db::migrate(&pool).await {
|
||||
eprintln!("skip add linkage tests: migrate failed: {e}");
|
||||
return None;
|
||||
}
|
||||
Some(pool)
|
||||
}
|
||||
|
||||
async fn cleanup_test_rows(pool: &PgPool, marker: &str) -> Result<()> {
|
||||
sqlx::query(
|
||||
"DELETE FROM entries WHERE user_id IS NULL AND (name LIKE $1 OR folder LIKE $1)",
|
||||
)
|
||||
.bind(format!("%{marker}%"))
|
||||
.execute(pool)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"DELETE FROM secrets WHERE user_id IS NULL AND name LIKE $1 \
|
||||
AND NOT EXISTS (SELECT 1 FROM entry_secrets es WHERE es.secret_id = secrets.id)",
|
||||
)
|
||||
.bind(format!("%{marker}%"))
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn add_links_existing_secret_by_unique_name() -> Result<()> {
|
||||
let Some(pool) = maybe_test_pool().await else {
|
||||
return Ok(());
|
||||
};
|
||||
let suffix = Uuid::from_u128(rand::random()).to_string();
|
||||
let marker = format!("link_unique_{}", &suffix[..8]);
|
||||
let secret_name = format!("{}_secret", marker);
|
||||
let entry_name = format!("{}_entry", marker);
|
||||
|
||||
cleanup_test_rows(&pool, &marker).await?;
|
||||
|
||||
let secret_id: Uuid = sqlx::query_scalar(
|
||||
"INSERT INTO secrets (user_id, name, type, encrypted) VALUES (NULL, $1, 'text', $2) RETURNING id",
|
||||
)
|
||||
.bind(&secret_name)
|
||||
.bind(vec![1_u8, 2, 3])
|
||||
.fetch_one(&pool)
|
||||
.await?;
|
||||
|
||||
run(
|
||||
&pool,
|
||||
AddParams {
|
||||
name: &entry_name,
|
||||
folder: &marker,
|
||||
entry_type: "service",
|
||||
notes: "",
|
||||
tags: &[],
|
||||
meta_entries: &[],
|
||||
secret_entries: &[],
|
||||
secret_types: &Default::default(),
|
||||
link_secret_names: std::slice::from_ref(&secret_name),
|
||||
user_id: None,
|
||||
},
|
||||
&[0_u8; 32],
|
||||
)
|
||||
.await?;
|
||||
|
||||
let linked: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS( \
|
||||
SELECT 1 FROM entry_secrets es \
|
||||
JOIN entries e ON e.id = es.entry_id \
|
||||
WHERE e.user_id IS NULL AND e.name = $1 AND es.secret_id = $2 \
|
||||
)",
|
||||
)
|
||||
.bind(&entry_name)
|
||||
.bind(secret_id)
|
||||
.fetch_one(&pool)
|
||||
.await?;
|
||||
assert!(linked);
|
||||
|
||||
cleanup_test_rows(&pool, &marker).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn add_link_secret_name_not_found_fails() -> Result<()> {
|
||||
let Some(pool) = maybe_test_pool().await else {
|
||||
return Ok(());
|
||||
};
|
||||
let suffix = Uuid::from_u128(rand::random()).to_string();
|
||||
let marker = format!("link_missing_{}", &suffix[..8]);
|
||||
let secret_name = format!("{}_secret", marker);
|
||||
let entry_name = format!("{}_entry", marker);
|
||||
|
||||
cleanup_test_rows(&pool, &marker).await?;
|
||||
|
||||
let err = run(
|
||||
&pool,
|
||||
AddParams {
|
||||
name: &entry_name,
|
||||
folder: &marker,
|
||||
entry_type: "service",
|
||||
notes: "",
|
||||
tags: &[],
|
||||
meta_entries: &[],
|
||||
secret_entries: &[],
|
||||
secret_types: &Default::default(),
|
||||
link_secret_names: std::slice::from_ref(&secret_name),
|
||||
user_id: None,
|
||||
},
|
||||
&[0_u8; 32],
|
||||
)
|
||||
.await
|
||||
.expect_err("must fail when linked secret is not found");
|
||||
assert!(err.to_string().contains("Not found: secret named"));
|
||||
|
||||
cleanup_test_rows(&pool, &marker).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn add_link_secret_name_ambiguous_fails() -> Result<()> {
|
||||
let Some(pool) = maybe_test_pool().await else {
|
||||
return Ok(());
|
||||
};
|
||||
let suffix = Uuid::from_u128(rand::random()).to_string();
|
||||
let marker = format!("link_amb_{}", &suffix[..8]);
|
||||
let secret_name = format!("{}_dup_secret", marker);
|
||||
let entry_name = format!("{}_entry", marker);
|
||||
|
||||
cleanup_test_rows(&pool, &marker).await?;
|
||||
|
||||
sqlx::query(
|
||||
"INSERT INTO secrets (user_id, name, type, encrypted) VALUES (NULL, $1, 'text', $2)",
|
||||
)
|
||||
.bind(&secret_name)
|
||||
.bind(vec![1_u8])
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO secrets (user_id, name, type, encrypted) VALUES (NULL, $1, 'text', $2)",
|
||||
)
|
||||
.bind(&secret_name)
|
||||
.bind(vec![2_u8])
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
|
||||
let err = run(
|
||||
&pool,
|
||||
AddParams {
|
||||
name: &entry_name,
|
||||
folder: &marker,
|
||||
entry_type: "service",
|
||||
notes: "",
|
||||
tags: &[],
|
||||
meta_entries: &[],
|
||||
secret_entries: &[],
|
||||
secret_types: &Default::default(),
|
||||
link_secret_names: std::slice::from_ref(&secret_name),
|
||||
user_id: None,
|
||||
},
|
||||
&[0_u8; 32],
|
||||
)
|
||||
.await
|
||||
.expect_err("must fail on ambiguous linked secret name");
|
||||
assert!(err.to_string().contains("Ambiguous:"));
|
||||
|
||||
cleanup_test_rows(&pool, &marker).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn add_duplicate_secret_name_returns_conflict_error() -> Result<()> {
|
||||
let Some(pool) = maybe_test_pool().await else {
|
||||
return Ok(());
|
||||
};
|
||||
let suffix = Uuid::from_u128(rand::random()).to_string();
|
||||
let marker = format!("dup_secret_{}", &suffix[..8]);
|
||||
let entry_name = format!("{}_entry", marker);
|
||||
let secret_name = "shared_token";
|
||||
|
||||
cleanup_test_rows(&pool, &marker).await?;
|
||||
|
||||
// First add succeeds
|
||||
run(
|
||||
&pool,
|
||||
AddParams {
|
||||
name: &entry_name,
|
||||
folder: &marker,
|
||||
entry_type: "service",
|
||||
notes: "",
|
||||
tags: &[],
|
||||
meta_entries: &[],
|
||||
secret_entries: &[format!("{}=value1", secret_name)],
|
||||
secret_types: &Default::default(),
|
||||
link_secret_names: &[],
|
||||
user_id: None,
|
||||
},
|
||||
&[0_u8; 32],
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Second add with same secret name under same user_id should fail with ConflictSecretName
|
||||
let entry_name2 = format!("{}_entry2", marker);
|
||||
let err = run(
|
||||
&pool,
|
||||
AddParams {
|
||||
name: &entry_name2,
|
||||
folder: &marker,
|
||||
entry_type: "service",
|
||||
notes: "",
|
||||
tags: &[],
|
||||
meta_entries: &[],
|
||||
secret_entries: &[format!("{}=value2", secret_name)],
|
||||
secret_types: &Default::default(),
|
||||
link_secret_names: &[],
|
||||
user_id: None,
|
||||
},
|
||||
&[0_u8; 32],
|
||||
)
|
||||
.await
|
||||
.expect_err("must fail on duplicate secret name");
|
||||
|
||||
let app_err = err
|
||||
.downcast_ref::<crate::error::AppError>()
|
||||
.expect("error should be AppError");
|
||||
assert!(
|
||||
matches!(app_err, crate::error::AppError::ConflictSecretName { .. }),
|
||||
"expected ConflictSecretName, got: {}",
|
||||
app_err
|
||||
);
|
||||
|
||||
cleanup_test_rows(&pool, &marker).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
65
crates/secrets-core/src/service/api_key.rs
Normal file
65
crates/secrets-core/src/service/api_key.rs
Normal file
@@ -0,0 +1,65 @@
|
||||
use anyhow::Result;
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
|
||||
const KEY_PREFIX: &str = "sk_";
|
||||
|
||||
/// Generate a new API key: `sk_<64 hex chars>` = 67 characters total.
|
||||
pub fn generate_api_key() -> String {
|
||||
use rand::RngExt;
|
||||
let mut bytes = [0u8; 32];
|
||||
rand::rng().fill(&mut bytes);
|
||||
format!("{}{}", KEY_PREFIX, ::hex::encode(bytes))
|
||||
}
|
||||
|
||||
/// Return the user's existing API key, or generate and store a new one if NULL.
|
||||
/// Uses a transaction with atomic update to prevent TOCTOU race conditions.
|
||||
pub async fn ensure_api_key(pool: &PgPool, user_id: Uuid) -> Result<String> {
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
// Lock the row and check existing key
|
||||
let existing: (Option<String>,) =
|
||||
sqlx::query_as("SELECT api_key FROM users WHERE id = $1 FOR UPDATE")
|
||||
.bind(user_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.ok_or(AppError::NotFoundUser)?;
|
||||
|
||||
if let Some(key) = existing.0 {
|
||||
tx.commit().await?;
|
||||
return Ok(key);
|
||||
}
|
||||
|
||||
// Generate and store new key atomically
|
||||
let new_key = generate_api_key();
|
||||
sqlx::query("UPDATE users SET api_key = $1 WHERE id = $2")
|
||||
.bind(&new_key)
|
||||
.bind(user_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
tx.commit().await?;
|
||||
Ok(new_key)
|
||||
}
|
||||
|
||||
/// Generate a fresh API key for the user, replacing the old one.
|
||||
pub async fn regenerate_api_key(pool: &PgPool, user_id: Uuid) -> Result<String> {
|
||||
let new_key = generate_api_key();
|
||||
sqlx::query("UPDATE users SET api_key = $1 WHERE id = $2")
|
||||
.bind(&new_key)
|
||||
.bind(user_id)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(new_key)
|
||||
}
|
||||
|
||||
/// Validate a Bearer token. Returns the `user_id` if the key matches.
|
||||
pub async fn validate_api_key(pool: &PgPool, raw_key: &str) -> Result<Option<Uuid>> {
|
||||
let row: Option<(Uuid,)> = sqlx::query_as("SELECT id FROM users WHERE api_key = $1")
|
||||
.bind(raw_key)
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
Ok(row.map(|(id,)| id))
|
||||
}
|
||||
39
crates/secrets-core/src/service/audit_log.rs
Normal file
39
crates/secrets-core/src/service/audit_log.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
use anyhow::Result;
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::models::AuditLogEntry;
|
||||
|
||||
pub async fn list_for_user(
|
||||
pool: &PgPool,
|
||||
user_id: Uuid,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<AuditLogEntry>> {
|
||||
let limit = limit.clamp(1, 200);
|
||||
let offset = offset.max(0);
|
||||
|
||||
let rows = sqlx::query_as(
|
||||
"SELECT id, user_id, action, folder, type, name, detail, created_at \
|
||||
FROM audit_log \
|
||||
WHERE user_id = $1 \
|
||||
ORDER BY created_at DESC, id DESC \
|
||||
LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
pub async fn count_for_user(pool: &PgPool, user_id: Uuid) -> Result<i64> {
|
||||
let count: i64 =
|
||||
sqlx::query_scalar("SELECT COUNT(*)::bigint FROM audit_log WHERE user_id = $1")
|
||||
.bind(user_id)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
Ok(count)
|
||||
}
|
||||
643
crates/secrets-core/src/service/delete.rs
Normal file
643
crates/secrets-core/src/service/delete.rs
Normal file
@@ -0,0 +1,643 @@
|
||||
use anyhow::Result;
|
||||
use serde_json::json;
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::db;
|
||||
use crate::models::{EntryRow, EntryWriteRow, SecretFieldRow};
|
||||
use crate::service::util::user_scope_condition;
|
||||
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
pub struct DeletedEntry {
|
||||
pub name: String,
|
||||
pub folder: String,
|
||||
#[serde(rename = "type")]
|
||||
pub entry_type: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
pub struct DeleteResult {
|
||||
pub deleted: Vec<DeletedEntry>,
|
||||
pub dry_run: bool,
|
||||
}
|
||||
|
||||
pub struct DeleteParams<'a> {
|
||||
/// If set, delete a single entry by name.
|
||||
pub name: Option<&'a str>,
|
||||
/// Folder filter for bulk delete.
|
||||
pub folder: Option<&'a str>,
|
||||
/// Type filter for bulk delete.
|
||||
pub entry_type: Option<&'a str>,
|
||||
pub dry_run: bool,
|
||||
pub user_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
/// Maximum number of entries that can be deleted in a single bulk operation.
|
||||
/// Prevents accidental mass deletion when filters are too broad.
|
||||
pub const MAX_BULK_DELETE: usize = 1000;
|
||||
|
||||
/// Delete a single entry by id (multi-tenant: `user_id` must match).
|
||||
pub async fn delete_by_id(pool: &PgPool, entry_id: Uuid, user_id: Uuid) -> Result<DeleteResult> {
|
||||
let mut tx = pool.begin().await?;
|
||||
let row: Option<EntryWriteRow> = sqlx::query_as(
|
||||
"SELECT id, version, folder, type, name, tags, metadata, notes FROM entries \
|
||||
WHERE id = $1 AND user_id = $2 FOR UPDATE",
|
||||
)
|
||||
.bind(entry_id)
|
||||
.bind(user_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
|
||||
let row = match row {
|
||||
Some(r) => r,
|
||||
None => {
|
||||
tx.rollback().await?;
|
||||
anyhow::bail!("Entry not found");
|
||||
}
|
||||
};
|
||||
|
||||
let folder = row.folder.clone();
|
||||
let entry_type = row.entry_type.clone();
|
||||
let name = row.name.clone();
|
||||
let entry_row: EntryRow = (&row).into();
|
||||
|
||||
snapshot_and_delete(
|
||||
&mut tx,
|
||||
&folder,
|
||||
&entry_type,
|
||||
&name,
|
||||
&entry_row,
|
||||
Some(user_id),
|
||||
)
|
||||
.await?;
|
||||
crate::audit::log_tx(
|
||||
&mut tx,
|
||||
Some(user_id),
|
||||
"delete",
|
||||
&folder,
|
||||
&entry_type,
|
||||
&name,
|
||||
json!({ "source": "web", "entry_id": entry_id }),
|
||||
)
|
||||
.await;
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(DeleteResult {
|
||||
deleted: vec![DeletedEntry {
|
||||
name,
|
||||
folder,
|
||||
entry_type,
|
||||
}],
|
||||
dry_run: false,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn run(pool: &PgPool, params: DeleteParams<'_>) -> Result<DeleteResult> {
|
||||
match params.name {
|
||||
Some(name) => delete_one(pool, name, params.folder, params.dry_run, params.user_id).await,
|
||||
None => {
|
||||
if params.folder.is_none() && params.entry_type.is_none() {
|
||||
anyhow::bail!(
|
||||
"Bulk delete requires at least one of: name, folder, or type filter."
|
||||
);
|
||||
}
|
||||
delete_bulk(
|
||||
pool,
|
||||
params.folder,
|
||||
params.entry_type,
|
||||
params.dry_run,
|
||||
params.user_id,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn delete_one(
|
||||
pool: &PgPool,
|
||||
name: &str,
|
||||
folder: Option<&str>,
|
||||
dry_run: bool,
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<DeleteResult> {
|
||||
if dry_run {
|
||||
// Dry-run uses the same disambiguation logic as actual delete:
|
||||
// - 0 matches → nothing to delete
|
||||
// - 1 match → show what would be deleted (with correct folder/type)
|
||||
// - 2+ matches → disambiguation error (same as non-dry-run)
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct DryRunRow {
|
||||
folder: String,
|
||||
#[sqlx(rename = "type")]
|
||||
entry_type: String,
|
||||
}
|
||||
|
||||
let mut idx = 1i32;
|
||||
let user_cond = user_scope_condition(user_id, &mut idx);
|
||||
let mut conditions = vec![user_cond];
|
||||
if folder.is_some() {
|
||||
conditions.push(format!("folder = ${}", idx));
|
||||
idx += 1;
|
||||
}
|
||||
conditions.push(format!("name = ${}", idx));
|
||||
let sql = format!(
|
||||
"SELECT folder, type FROM entries WHERE {}",
|
||||
conditions.join(" AND ")
|
||||
);
|
||||
let mut q = sqlx::query_as::<_, DryRunRow>(&sql);
|
||||
if let Some(uid) = user_id {
|
||||
q = q.bind(uid);
|
||||
}
|
||||
if let Some(f) = folder {
|
||||
q = q.bind(f);
|
||||
}
|
||||
q = q.bind(name);
|
||||
let rows = q.fetch_all(pool).await?;
|
||||
|
||||
return match rows.len() {
|
||||
0 => Ok(DeleteResult {
|
||||
deleted: vec![],
|
||||
dry_run: true,
|
||||
}),
|
||||
1 => {
|
||||
let row = rows
|
||||
.into_iter()
|
||||
.next()
|
||||
.ok_or_else(|| anyhow::anyhow!("internal: matched row vanished"))?;
|
||||
Ok(DeleteResult {
|
||||
deleted: vec![DeletedEntry {
|
||||
name: name.to_string(),
|
||||
folder: row.folder,
|
||||
entry_type: row.entry_type,
|
||||
}],
|
||||
dry_run: true,
|
||||
})
|
||||
}
|
||||
_ => {
|
||||
let folders: Vec<&str> = rows.iter().map(|r| r.folder.as_str()).collect();
|
||||
anyhow::bail!(
|
||||
"Ambiguous: {} entries named '{}' found in folders: [{}]. \
|
||||
Specify 'folder' to disambiguate.",
|
||||
rows.len(),
|
||||
name,
|
||||
folders.join(", ")
|
||||
)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
// Fetch matching rows with FOR UPDATE; use folder when provided to resolve ambiguity.
|
||||
let mut idx = 1i32;
|
||||
let user_cond = user_scope_condition(user_id, &mut idx);
|
||||
let mut conditions = vec![user_cond];
|
||||
if folder.is_some() {
|
||||
conditions.push(format!("folder = ${}", idx));
|
||||
idx += 1;
|
||||
}
|
||||
conditions.push(format!("name = ${}", idx));
|
||||
let sql = format!(
|
||||
"SELECT id, version, folder, type, tags, metadata, notes FROM entries WHERE {} FOR UPDATE",
|
||||
conditions.join(" AND ")
|
||||
);
|
||||
let mut q = sqlx::query_as::<_, EntryRow>(&sql);
|
||||
if let Some(uid) = user_id {
|
||||
q = q.bind(uid);
|
||||
}
|
||||
if let Some(f) = folder {
|
||||
q = q.bind(f);
|
||||
}
|
||||
q = q.bind(name);
|
||||
let rows = q.fetch_all(&mut *tx).await?;
|
||||
|
||||
let row = match rows.len() {
|
||||
0 => {
|
||||
tx.rollback().await?;
|
||||
return Ok(DeleteResult {
|
||||
deleted: vec![],
|
||||
dry_run: false,
|
||||
});
|
||||
}
|
||||
1 => rows
|
||||
.into_iter()
|
||||
.next()
|
||||
.ok_or_else(|| anyhow::anyhow!("internal: matched row vanished"))?,
|
||||
_ => {
|
||||
tx.rollback().await?;
|
||||
let folders: Vec<&str> = rows.iter().map(|r| r.folder.as_str()).collect();
|
||||
anyhow::bail!(
|
||||
"Ambiguous: {} entries named '{}' found in folders: [{}]. \
|
||||
Specify 'folder' to disambiguate.",
|
||||
rows.len(),
|
||||
name,
|
||||
folders.join(", ")
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
let folder = row.folder.clone();
|
||||
let entry_type = row.entry_type.clone();
|
||||
snapshot_and_delete(&mut tx, &folder, &entry_type, name, &row, user_id).await?;
|
||||
crate::audit::log_tx(
|
||||
&mut tx,
|
||||
user_id,
|
||||
"delete",
|
||||
&folder,
|
||||
&entry_type,
|
||||
name,
|
||||
json!({}),
|
||||
)
|
||||
.await;
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(DeleteResult {
|
||||
deleted: vec![DeletedEntry {
|
||||
name: name.to_string(),
|
||||
folder,
|
||||
entry_type,
|
||||
}],
|
||||
dry_run: false,
|
||||
})
|
||||
}
|
||||
|
||||
async fn delete_bulk(
|
||||
pool: &PgPool,
|
||||
folder: Option<&str>,
|
||||
entry_type: Option<&str>,
|
||||
dry_run: bool,
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<DeleteResult> {
|
||||
#[derive(Debug, sqlx::FromRow)]
|
||||
struct FullEntryRow {
|
||||
id: Uuid,
|
||||
version: i64,
|
||||
folder: String,
|
||||
#[sqlx(rename = "type")]
|
||||
entry_type: String,
|
||||
name: String,
|
||||
metadata: serde_json::Value,
|
||||
tags: Vec<String>,
|
||||
notes: String,
|
||||
}
|
||||
|
||||
let mut conditions: Vec<String> = Vec::new();
|
||||
let mut idx: i32 = 1;
|
||||
|
||||
if user_id.is_some() {
|
||||
conditions.push(format!("user_id = ${}", idx));
|
||||
idx += 1;
|
||||
} else {
|
||||
conditions.push("user_id IS NULL".to_string());
|
||||
}
|
||||
if folder.is_some() {
|
||||
conditions.push(format!("folder = ${}", idx));
|
||||
idx += 1;
|
||||
}
|
||||
if entry_type.is_some() {
|
||||
conditions.push(format!("type = ${}", idx));
|
||||
idx += 1;
|
||||
}
|
||||
|
||||
let where_clause = format!("WHERE {}", conditions.join(" AND "));
|
||||
let _ = idx; // used only for placeholder numbering in conditions
|
||||
|
||||
if dry_run {
|
||||
let sql = format!(
|
||||
"SELECT id, version, folder, type, name, metadata, tags, notes \
|
||||
FROM entries {where_clause} ORDER BY type, name"
|
||||
);
|
||||
let mut q = sqlx::query_as::<_, FullEntryRow>(&sql);
|
||||
if let Some(uid) = user_id {
|
||||
q = q.bind(uid);
|
||||
}
|
||||
if let Some(f) = folder {
|
||||
q = q.bind(f);
|
||||
}
|
||||
if let Some(t) = entry_type {
|
||||
q = q.bind(t);
|
||||
}
|
||||
let rows = q.fetch_all(pool).await?;
|
||||
|
||||
let deleted = rows
|
||||
.iter()
|
||||
.map(|r| DeletedEntry {
|
||||
name: r.name.clone(),
|
||||
folder: r.folder.clone(),
|
||||
entry_type: r.entry_type.clone(),
|
||||
})
|
||||
.collect();
|
||||
return Ok(DeleteResult {
|
||||
deleted,
|
||||
dry_run: true,
|
||||
});
|
||||
}
|
||||
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
let sql = format!(
|
||||
"SELECT id, version, folder, type, name, metadata, tags, notes \
|
||||
FROM entries {where_clause} ORDER BY type, name FOR UPDATE"
|
||||
);
|
||||
let mut q = sqlx::query_as::<_, FullEntryRow>(&sql);
|
||||
if let Some(uid) = user_id {
|
||||
q = q.bind(uid);
|
||||
}
|
||||
if let Some(f) = folder {
|
||||
q = q.bind(f);
|
||||
}
|
||||
if let Some(t) = entry_type {
|
||||
q = q.bind(t);
|
||||
}
|
||||
let rows = q.fetch_all(&mut *tx).await?;
|
||||
|
||||
if rows.len() > MAX_BULK_DELETE {
|
||||
tx.rollback().await?;
|
||||
anyhow::bail!(
|
||||
"Bulk delete would affect {} entries (limit: {}). \
|
||||
Narrow your filters or delete entries individually.",
|
||||
rows.len(),
|
||||
MAX_BULK_DELETE,
|
||||
);
|
||||
}
|
||||
|
||||
let mut deleted = Vec::with_capacity(rows.len());
|
||||
for row in &rows {
|
||||
let entry_row: EntryRow = EntryRow {
|
||||
id: row.id,
|
||||
version: row.version,
|
||||
folder: row.folder.clone(),
|
||||
entry_type: row.entry_type.clone(),
|
||||
tags: row.tags.clone(),
|
||||
metadata: row.metadata.clone(),
|
||||
notes: row.notes.clone(),
|
||||
};
|
||||
snapshot_and_delete(
|
||||
&mut tx,
|
||||
&row.folder,
|
||||
&row.entry_type,
|
||||
&row.name,
|
||||
&entry_row,
|
||||
user_id,
|
||||
)
|
||||
.await?;
|
||||
crate::audit::log_tx(
|
||||
&mut tx,
|
||||
user_id,
|
||||
"delete",
|
||||
&row.folder,
|
||||
&row.entry_type,
|
||||
&row.name,
|
||||
json!({"bulk": true}),
|
||||
)
|
||||
.await;
|
||||
deleted.push(DeletedEntry {
|
||||
name: row.name.clone(),
|
||||
folder: row.folder.clone(),
|
||||
entry_type: row.entry_type.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(DeleteResult {
|
||||
deleted,
|
||||
dry_run: false,
|
||||
})
|
||||
}
|
||||
|
||||
async fn snapshot_and_delete(
|
||||
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
folder: &str,
|
||||
entry_type: &str,
|
||||
name: &str,
|
||||
row: &EntryRow,
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<()> {
|
||||
let history_metadata = match db::metadata_with_secret_snapshot(tx, row.id, &row.metadata).await
|
||||
{
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "failed to build secret snapshot for entry history");
|
||||
row.metadata.clone()
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = db::snapshot_entry_history(
|
||||
tx,
|
||||
db::EntrySnapshotParams {
|
||||
entry_id: row.id,
|
||||
user_id,
|
||||
folder,
|
||||
entry_type,
|
||||
name,
|
||||
version: row.version,
|
||||
action: "delete",
|
||||
tags: &row.tags,
|
||||
metadata: &history_metadata,
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to snapshot entry history before delete");
|
||||
}
|
||||
|
||||
let fields: Vec<SecretFieldRow> = sqlx::query_as(
|
||||
"SELECT s.id, s.name, s.encrypted \
|
||||
FROM entry_secrets es \
|
||||
JOIN secrets s ON s.id = es.secret_id \
|
||||
WHERE es.entry_id = $1",
|
||||
)
|
||||
.bind(row.id)
|
||||
.fetch_all(&mut **tx)
|
||||
.await?;
|
||||
|
||||
for f in &fields {
|
||||
if let Err(e) = db::snapshot_secret_history(
|
||||
tx,
|
||||
db::SecretSnapshotParams {
|
||||
secret_id: f.id,
|
||||
name: &f.name,
|
||||
encrypted: &f.encrypted,
|
||||
action: "delete",
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to snapshot secret history before delete");
|
||||
}
|
||||
}
|
||||
|
||||
sqlx::query("DELETE FROM entries WHERE id = $1")
|
||||
.bind(row.id)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
|
||||
let secret_ids: Vec<Uuid> = fields.iter().map(|f| f.id).collect();
|
||||
if !secret_ids.is_empty() {
|
||||
sqlx::query(
|
||||
"DELETE FROM secrets s \
|
||||
WHERE s.id = ANY($1) \
|
||||
AND NOT EXISTS (SELECT 1 FROM entry_secrets es WHERE es.secret_id = s.id)",
|
||||
)
|
||||
.bind(&secret_ids)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use sqlx::PgPool;
|
||||
|
||||
async fn maybe_test_pool() -> Option<PgPool> {
|
||||
let Ok(url) = std::env::var("SECRETS_DATABASE_URL") else {
|
||||
eprintln!("skip delete tests: SECRETS_DATABASE_URL is not set");
|
||||
return None;
|
||||
};
|
||||
let Ok(pool) = PgPool::connect(&url).await else {
|
||||
eprintln!("skip delete tests: cannot connect to database");
|
||||
return None;
|
||||
};
|
||||
if let Err(e) = crate::db::migrate(&pool).await {
|
||||
eprintln!("skip delete tests: migrate failed: {e}");
|
||||
return None;
|
||||
}
|
||||
Some(pool)
|
||||
}
|
||||
|
||||
async fn cleanup_single_user_rows(pool: &PgPool, marker: &str) -> Result<()> {
|
||||
sqlx::query(
|
||||
"DELETE FROM entries WHERE user_id IS NULL AND (name LIKE $1 OR folder LIKE $1)",
|
||||
)
|
||||
.bind(format!("%{marker}%"))
|
||||
.execute(pool)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"DELETE FROM secrets WHERE user_id IS NULL AND name LIKE $1 \
|
||||
AND NOT EXISTS (SELECT 1 FROM entry_secrets es WHERE es.secret_id = secrets.id)",
|
||||
)
|
||||
.bind(format!("%{marker}%"))
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_dry_run_reports_matching_entry_without_writes() -> Result<()> {
|
||||
let Some(pool) = maybe_test_pool().await else {
|
||||
return Ok(());
|
||||
};
|
||||
let suffix = Uuid::from_u128(rand::random()).to_string();
|
||||
let marker = format!("delete_dry_{}", &suffix[..8]);
|
||||
let entry_name = format!("{}_entry", marker);
|
||||
|
||||
cleanup_single_user_rows(&pool, &marker).await?;
|
||||
|
||||
sqlx::query(
|
||||
"INSERT INTO entries (user_id, folder, type, name, notes, tags, metadata) \
|
||||
VALUES (NULL, $1, 'service', $2, '', '{}', '{}')",
|
||||
)
|
||||
.bind(&marker)
|
||||
.bind(&entry_name)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
|
||||
let result = run(
|
||||
&pool,
|
||||
DeleteParams {
|
||||
name: Some(&entry_name),
|
||||
folder: Some(&marker),
|
||||
entry_type: None,
|
||||
dry_run: true,
|
||||
user_id: None,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
assert!(result.dry_run);
|
||||
assert_eq!(result.deleted.len(), 1);
|
||||
assert_eq!(result.deleted[0].name, entry_name);
|
||||
|
||||
let still_exists: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM entries WHERE user_id IS NULL AND folder = $1 AND name = $2)",
|
||||
)
|
||||
.bind(&marker)
|
||||
.bind(&entry_name)
|
||||
.fetch_one(&pool)
|
||||
.await?;
|
||||
assert!(still_exists);
|
||||
|
||||
cleanup_single_user_rows(&pool, &marker).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_by_id_removes_entry_and_orphan_secret() -> Result<()> {
|
||||
let Some(pool) = maybe_test_pool().await else {
|
||||
return Ok(());
|
||||
};
|
||||
let suffix = Uuid::from_u128(rand::random()).to_string();
|
||||
let marker = format!("delete_id_{}", &suffix[..8]);
|
||||
let user_id = Uuid::from_u128(rand::random());
|
||||
let entry_name = format!("{}_entry", marker);
|
||||
let secret_name = format!("{}_secret", marker);
|
||||
|
||||
sqlx::query("DELETE FROM entries WHERE user_id = $1 AND folder = $2")
|
||||
.bind(user_id)
|
||||
.bind(&marker)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM secrets WHERE user_id = $1 AND name = $2")
|
||||
.bind(user_id)
|
||||
.bind(&secret_name)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
|
||||
let entry_id: Uuid = sqlx::query_scalar(
|
||||
"INSERT INTO entries (user_id, folder, type, name, notes, tags, metadata) \
|
||||
VALUES ($1, $2, 'service', $3, '', '{}', '{}') RETURNING id",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(&marker)
|
||||
.bind(&entry_name)
|
||||
.fetch_one(&pool)
|
||||
.await?;
|
||||
let secret_id: Uuid = sqlx::query_scalar(
|
||||
"INSERT INTO secrets (user_id, name, type, encrypted) VALUES ($1, $2, 'text', $3) RETURNING id",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(&secret_name)
|
||||
.bind(vec![1_u8, 2, 3])
|
||||
.fetch_one(&pool)
|
||||
.await?;
|
||||
sqlx::query("INSERT INTO entry_secrets (entry_id, secret_id) VALUES ($1, $2)")
|
||||
.bind(entry_id)
|
||||
.bind(secret_id)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
|
||||
let result = delete_by_id(&pool, entry_id, user_id).await?;
|
||||
assert!(!result.dry_run);
|
||||
assert_eq!(result.deleted.len(), 1);
|
||||
assert_eq!(result.deleted[0].name, entry_name);
|
||||
|
||||
let entry_exists: bool =
|
||||
sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM entries WHERE id = $1)")
|
||||
.bind(entry_id)
|
||||
.fetch_one(&pool)
|
||||
.await?;
|
||||
let secret_exists: bool =
|
||||
sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM secrets WHERE id = $1)")
|
||||
.bind(secret_id)
|
||||
.fetch_one(&pool)
|
||||
.await?;
|
||||
assert!(!entry_exists);
|
||||
assert!(!secret_exists);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
77
crates/secrets-core/src/service/env_map.rs
Normal file
77
crates/secrets-core/src/service/env_map.rs
Normal file
@@ -0,0 +1,77 @@
|
||||
use anyhow::Result;
|
||||
use serde_json::Value;
|
||||
use sqlx::PgPool;
|
||||
use std::collections::HashMap;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::crypto;
|
||||
use crate::service::search::{fetch_entries, fetch_secrets_for_entries};
|
||||
|
||||
/// Build an env variable map from entry secrets (for dry-run preview or injection).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn build_env_map(
|
||||
pool: &PgPool,
|
||||
folder: Option<&str>,
|
||||
entry_type: Option<&str>,
|
||||
name: Option<&str>,
|
||||
tags: &[String],
|
||||
only_fields: &[String],
|
||||
prefix: &str,
|
||||
master_key: &[u8; 32],
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<HashMap<String, String>> {
|
||||
let entries = fetch_entries(pool, folder, entry_type, name, tags, None, user_id).await?;
|
||||
if entries.is_empty() {
|
||||
return Ok(HashMap::new());
|
||||
}
|
||||
|
||||
let entry_ids: Vec<Uuid> = entries.iter().map(|e| e.id).collect();
|
||||
let secrets_map = fetch_secrets_for_entries(pool, &entry_ids).await?;
|
||||
|
||||
let mut combined: HashMap<String, String> = HashMap::new();
|
||||
|
||||
for entry in &entries {
|
||||
let all_fields = secrets_map.get(&entry.id).map(Vec::as_slice).unwrap_or(&[]);
|
||||
let effective_prefix = env_prefix(entry, prefix);
|
||||
|
||||
let fields: Vec<_> = if only_fields.is_empty() {
|
||||
all_fields.iter().collect()
|
||||
} else {
|
||||
all_fields
|
||||
.iter()
|
||||
.filter(|f| only_fields.contains(&f.name))
|
||||
.collect()
|
||||
};
|
||||
|
||||
for f in fields {
|
||||
let decrypted = crypto::decrypt_json(master_key, &f.encrypted)?;
|
||||
let key = format!(
|
||||
"{}_{}",
|
||||
effective_prefix,
|
||||
f.name.to_uppercase().replace(['-', '.'], "_")
|
||||
);
|
||||
combined.insert(key, json_to_env_string(&decrypted));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(combined)
|
||||
}
|
||||
|
||||
fn env_prefix(entry: &crate::models::Entry, prefix: &str) -> String {
|
||||
let name_part = entry.name.to_uppercase().replace(['-', '.', ' '], "_");
|
||||
if prefix.is_empty() {
|
||||
name_part
|
||||
} else {
|
||||
let normalized = prefix.to_uppercase().replace(['-', '.', ' '], "_");
|
||||
let normalized = normalized.trim_end_matches('_');
|
||||
format!("{}_{}", normalized, name_part)
|
||||
}
|
||||
}
|
||||
|
||||
fn json_to_env_string(v: &Value) -> String {
|
||||
match v {
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Null => String::new(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
140
crates/secrets-core/src/service/export.rs
Normal file
140
crates/secrets-core/src/service/export.rs
Normal file
@@ -0,0 +1,140 @@
|
||||
use anyhow::Result;
|
||||
use serde_json::Value;
|
||||
use sqlx::PgPool;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::crypto;
|
||||
use crate::models::{ExportData, ExportEntry, ExportFormat};
|
||||
use crate::service::search::{fetch_entries, fetch_secrets_for_entries};
|
||||
|
||||
pub struct ExportParams<'a> {
|
||||
pub folder: Option<&'a str>,
|
||||
pub entry_type: Option<&'a str>,
|
||||
pub name: Option<&'a str>,
|
||||
pub tags: &'a [String],
|
||||
pub query: Option<&'a str>,
|
||||
pub no_secrets: bool,
|
||||
pub user_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
pub async fn export(
|
||||
pool: &PgPool,
|
||||
params: ExportParams<'_>,
|
||||
master_key: Option<&[u8; 32]>,
|
||||
) -> Result<ExportData> {
|
||||
let entries = fetch_entries(
|
||||
pool,
|
||||
params.folder,
|
||||
params.entry_type,
|
||||
params.name,
|
||||
params.tags,
|
||||
params.query,
|
||||
params.user_id,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let entry_ids: Vec<Uuid> = entries.iter().map(|e| e.id).collect();
|
||||
let secrets_map: HashMap<Uuid, Vec<_>> = if !params.no_secrets && !entry_ids.is_empty() {
|
||||
fetch_secrets_for_entries(pool, &entry_ids).await?
|
||||
} else {
|
||||
HashMap::new()
|
||||
};
|
||||
|
||||
let mut export_entries: Vec<ExportEntry> = Vec::with_capacity(entries.len());
|
||||
for entry in &entries {
|
||||
let secrets = if params.no_secrets {
|
||||
None
|
||||
} else {
|
||||
let fields = secrets_map.get(&entry.id).map(Vec::as_slice).unwrap_or(&[]);
|
||||
if fields.is_empty() {
|
||||
Some(BTreeMap::new())
|
||||
} else {
|
||||
let mk = master_key
|
||||
.ok_or_else(|| anyhow::anyhow!("master key required to decrypt secrets"))?;
|
||||
let mut map = BTreeMap::new();
|
||||
for f in fields {
|
||||
let decrypted = crypto::decrypt_json(mk, &f.encrypted)?;
|
||||
map.insert(f.name.clone(), decrypted);
|
||||
}
|
||||
Some(map)
|
||||
}
|
||||
};
|
||||
|
||||
export_entries.push(ExportEntry {
|
||||
name: entry.name.clone(),
|
||||
folder: entry.folder.clone(),
|
||||
entry_type: entry.entry_type.clone(),
|
||||
notes: entry.notes.clone(),
|
||||
tags: entry.tags.clone(),
|
||||
metadata: entry.metadata.clone(),
|
||||
secrets,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(ExportData {
|
||||
version: 1,
|
||||
exported_at: chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
|
||||
entries: export_entries,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn export_to_file(
|
||||
pool: &PgPool,
|
||||
params: ExportParams<'_>,
|
||||
master_key: Option<&[u8; 32]>,
|
||||
file_path: &str,
|
||||
format_override: Option<&str>,
|
||||
) -> Result<usize> {
|
||||
let format = if let Some(f) = format_override {
|
||||
f.parse::<ExportFormat>()?
|
||||
} else {
|
||||
ExportFormat::from_extension(file_path).unwrap_or(ExportFormat::Json)
|
||||
};
|
||||
|
||||
let data = export(pool, params, master_key).await?;
|
||||
let count = data.entries.len();
|
||||
let serialized = format.serialize(&data)?;
|
||||
std::fs::write(file_path, &serialized)?;
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
pub async fn export_to_string(
|
||||
pool: &PgPool,
|
||||
params: ExportParams<'_>,
|
||||
master_key: Option<&[u8; 32]>,
|
||||
format: &str,
|
||||
) -> Result<String> {
|
||||
let fmt = format.parse::<ExportFormat>()?;
|
||||
let data = export(pool, params, master_key).await?;
|
||||
fmt.serialize(&data)
|
||||
}
|
||||
|
||||
// ── Build helpers for re-encoding values as CLI-style entries ─────────────────
|
||||
|
||||
pub fn build_meta_entries(metadata: &Value) -> Vec<String> {
|
||||
let mut entries = Vec::new();
|
||||
if let Some(obj) = metadata.as_object() {
|
||||
for (k, v) in obj {
|
||||
entries.push(value_to_kv_entry(k, v));
|
||||
}
|
||||
}
|
||||
entries
|
||||
}
|
||||
|
||||
pub fn build_secret_entries(secrets: Option<&BTreeMap<String, Value>>) -> Vec<String> {
|
||||
let mut entries = Vec::new();
|
||||
if let Some(map) = secrets {
|
||||
for (k, v) in map {
|
||||
entries.push(value_to_kv_entry(k, v));
|
||||
}
|
||||
}
|
||||
entries
|
||||
}
|
||||
|
||||
pub fn value_to_kv_entry(key: &str, value: &Value) -> String {
|
||||
match value {
|
||||
Value::String(s) => format!("{}={}", key, s),
|
||||
other => format!("{}:={}", key, other),
|
||||
}
|
||||
}
|
||||
105
crates/secrets-core/src/service/get_secret.rs
Normal file
105
crates/secrets-core/src/service/get_secret.rs
Normal file
@@ -0,0 +1,105 @@
|
||||
use anyhow::Result;
|
||||
use serde_json::Value;
|
||||
use sqlx::PgPool;
|
||||
use std::collections::HashMap;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::crypto;
|
||||
use crate::error::AppError;
|
||||
use crate::service::search::{fetch_secrets_for_entries, resolve_entry, resolve_entry_by_id};
|
||||
|
||||
/// Decrypt a single named field from an entry.
|
||||
/// `folder` is optional; if omitted and multiple entries share the name, an error is returned.
|
||||
pub async fn get_secret_field(
|
||||
pool: &PgPool,
|
||||
name: &str,
|
||||
folder: Option<&str>,
|
||||
field_name: &str,
|
||||
master_key: &[u8; 32],
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<Value> {
|
||||
let entry = resolve_entry(pool, name, folder, user_id).await?;
|
||||
|
||||
let entry_ids = vec![entry.id];
|
||||
let secrets_map = fetch_secrets_for_entries(pool, &entry_ids).await?;
|
||||
let fields = secrets_map.get(&entry.id).map(Vec::as_slice).unwrap_or(&[]);
|
||||
|
||||
let field = fields
|
||||
.iter()
|
||||
.find(|f| f.name == field_name)
|
||||
.ok_or_else(|| anyhow::anyhow!("Secret field '{}' not found", field_name))?;
|
||||
|
||||
crypto::decrypt_json(master_key, &field.encrypted)
|
||||
}
|
||||
|
||||
/// Decrypt all secret fields from an entry. Returns a map field_name → decrypted Value.
|
||||
/// `folder` is optional; if omitted and multiple entries share the name, an error is returned.
|
||||
pub async fn get_all_secrets(
|
||||
pool: &PgPool,
|
||||
name: &str,
|
||||
folder: Option<&str>,
|
||||
master_key: &[u8; 32],
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<HashMap<String, Value>> {
|
||||
let entry = resolve_entry(pool, name, folder, user_id).await?;
|
||||
|
||||
let entry_ids = vec![entry.id];
|
||||
let secrets_map = fetch_secrets_for_entries(pool, &entry_ids).await?;
|
||||
let fields = secrets_map.get(&entry.id).map(Vec::as_slice).unwrap_or(&[]);
|
||||
|
||||
let mut map = HashMap::new();
|
||||
for f in fields {
|
||||
let decrypted = crypto::decrypt_json(master_key, &f.encrypted)?;
|
||||
map.insert(f.name.clone(), decrypted);
|
||||
}
|
||||
Ok(map)
|
||||
}
|
||||
|
||||
/// Decrypt a single named field from an entry, located by its UUID.
|
||||
pub async fn get_secret_field_by_id(
|
||||
pool: &PgPool,
|
||||
entry_id: Uuid,
|
||||
field_name: &str,
|
||||
master_key: &[u8; 32],
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<Value> {
|
||||
resolve_entry_by_id(pool, entry_id, user_id)
|
||||
.await
|
||||
.map_err(|_| anyhow::Error::from(AppError::NotFoundEntry))?;
|
||||
|
||||
let entry_ids = vec![entry_id];
|
||||
let secrets_map = fetch_secrets_for_entries(pool, &entry_ids).await?;
|
||||
let fields = secrets_map.get(&entry_id).map(Vec::as_slice).unwrap_or(&[]);
|
||||
|
||||
let field = fields
|
||||
.iter()
|
||||
.find(|f| f.name == field_name)
|
||||
.ok_or_else(|| anyhow::anyhow!("Secret field '{}' not found", field_name))?;
|
||||
|
||||
crypto::decrypt_json(master_key, &field.encrypted)
|
||||
}
|
||||
|
||||
/// Decrypt all secret fields from an entry, located by its UUID.
|
||||
/// Returns a map field_name → decrypted Value.
|
||||
pub async fn get_all_secrets_by_id(
|
||||
pool: &PgPool,
|
||||
entry_id: Uuid,
|
||||
master_key: &[u8; 32],
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<HashMap<String, Value>> {
|
||||
// Validate entry exists (and that it belongs to the requesting user)
|
||||
resolve_entry_by_id(pool, entry_id, user_id)
|
||||
.await
|
||||
.map_err(|_| anyhow::Error::from(AppError::NotFoundEntry))?;
|
||||
|
||||
let entry_ids = vec![entry_id];
|
||||
let secrets_map = fetch_secrets_for_entries(pool, &entry_ids).await?;
|
||||
let fields = secrets_map.get(&entry_id).map(Vec::as_slice).unwrap_or(&[]);
|
||||
|
||||
let mut map = HashMap::new();
|
||||
for f in fields {
|
||||
let decrypted = crypto::decrypt_json(master_key, &f.encrypted)?;
|
||||
map.insert(f.name.clone(), decrypted);
|
||||
}
|
||||
Ok(map)
|
||||
}
|
||||
64
crates/secrets-core/src/service/history.rs
Normal file
64
crates/secrets-core/src/service/history.rs
Normal file
@@ -0,0 +1,64 @@
|
||||
use anyhow::Result;
|
||||
use serde_json::Value;
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::service::search::resolve_entry;
|
||||
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
pub struct HistoryEntry {
|
||||
pub version: i64,
|
||||
pub action: String,
|
||||
pub created_at: String,
|
||||
}
|
||||
|
||||
/// Return version history for the entry identified by `name`.
|
||||
/// `folder` is optional; if omitted and multiple entries share the name, an error is returned.
|
||||
pub async fn run(
|
||||
pool: &PgPool,
|
||||
name: &str,
|
||||
folder: Option<&str>,
|
||||
limit: u32,
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<Vec<HistoryEntry>> {
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct Row {
|
||||
version: i64,
|
||||
action: String,
|
||||
created_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
let entry = resolve_entry(pool, name, folder, user_id).await?;
|
||||
|
||||
let rows: Vec<Row> = sqlx::query_as(
|
||||
"SELECT DISTINCT ON (version) version, action, created_at \
|
||||
FROM entries_history \
|
||||
WHERE entry_id = $1 \
|
||||
ORDER BY version DESC, id DESC \
|
||||
LIMIT $2",
|
||||
)
|
||||
.bind(entry.id)
|
||||
.bind(limit as i64)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|r| HistoryEntry {
|
||||
version: r.version,
|
||||
action: r.action,
|
||||
created_at: r.created_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub async fn run_json(
|
||||
pool: &PgPool,
|
||||
name: &str,
|
||||
folder: Option<&str>,
|
||||
limit: u32,
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<Value> {
|
||||
let entries = run(pool, name, folder, limit, user_id).await?;
|
||||
Ok(serde_json::to_value(entries)?)
|
||||
}
|
||||
127
crates/secrets-core/src/service/import.rs
Normal file
127
crates/secrets-core/src/service/import.rs
Normal file
@@ -0,0 +1,127 @@
|
||||
use anyhow::Result;
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::models::ExportFormat;
|
||||
use crate::service::add::{AddParams, run as add_run};
|
||||
use crate::service::export::{build_meta_entries, build_secret_entries};
|
||||
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
pub struct ImportSummary {
|
||||
pub total: usize,
|
||||
pub inserted: usize,
|
||||
pub skipped: usize,
|
||||
pub failed: usize,
|
||||
pub dry_run: bool,
|
||||
}
|
||||
|
||||
pub struct ImportParams<'a> {
|
||||
pub file: &'a str,
|
||||
pub force: bool,
|
||||
pub dry_run: bool,
|
||||
pub user_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
pub async fn run(
|
||||
pool: &PgPool,
|
||||
params: ImportParams<'_>,
|
||||
master_key: &[u8; 32],
|
||||
) -> Result<ImportSummary> {
|
||||
let format = ExportFormat::from_extension(params.file)?;
|
||||
let content = std::fs::read_to_string(params.file)
|
||||
.map_err(|e| anyhow::anyhow!("Cannot read file '{}': {}", params.file, e))?;
|
||||
let data = format.deserialize(&content)?;
|
||||
|
||||
if data.version != 1 {
|
||||
anyhow::bail!(
|
||||
"Unsupported export version {}. Only version 1 is supported.",
|
||||
data.version
|
||||
);
|
||||
}
|
||||
|
||||
let total = data.entries.len();
|
||||
let mut inserted = 0usize;
|
||||
let mut skipped = 0usize;
|
||||
let mut failed = 0usize;
|
||||
|
||||
for entry in &data.entries {
|
||||
let exists: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM entries \
|
||||
WHERE folder = $1 AND name = $2 AND user_id IS NOT DISTINCT FROM $3)",
|
||||
)
|
||||
.bind(&entry.folder)
|
||||
.bind(&entry.name)
|
||||
.bind(params.user_id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
anyhow::anyhow!(
|
||||
"Failed to check entry existence for '{}': {}",
|
||||
entry.name,
|
||||
e
|
||||
)
|
||||
})?;
|
||||
|
||||
if exists && !params.force {
|
||||
return Err(anyhow::anyhow!(
|
||||
"Import aborted: conflict on '{}'",
|
||||
entry.name
|
||||
));
|
||||
}
|
||||
|
||||
if params.dry_run {
|
||||
if exists {
|
||||
skipped += 1;
|
||||
} else {
|
||||
inserted += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
let secret_entries = build_secret_entries(entry.secrets.as_ref());
|
||||
let meta_entries = build_meta_entries(&entry.metadata);
|
||||
|
||||
match add_run(
|
||||
pool,
|
||||
AddParams {
|
||||
name: &entry.name,
|
||||
folder: &entry.folder,
|
||||
entry_type: &entry.entry_type,
|
||||
notes: &entry.notes,
|
||||
tags: &entry.tags,
|
||||
meta_entries: &meta_entries,
|
||||
secret_entries: &secret_entries,
|
||||
secret_types: &Default::default(),
|
||||
link_secret_names: &[],
|
||||
user_id: params.user_id,
|
||||
},
|
||||
master_key,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
inserted += 1;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
name = entry.name,
|
||||
error = %e,
|
||||
"failed to import entry"
|
||||
);
|
||||
failed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if failed > 0 {
|
||||
return Err(anyhow::anyhow!("{} record(s) failed to import", failed));
|
||||
}
|
||||
|
||||
Ok(ImportSummary {
|
||||
total,
|
||||
inserted,
|
||||
skipped,
|
||||
failed,
|
||||
dry_run: params.dry_run,
|
||||
})
|
||||
}
|
||||
14
crates/secrets-core/src/service/mod.rs
Normal file
14
crates/secrets-core/src/service/mod.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
pub mod add;
|
||||
pub mod api_key;
|
||||
pub mod audit_log;
|
||||
pub mod delete;
|
||||
pub mod env_map;
|
||||
pub mod export;
|
||||
pub mod get_secret;
|
||||
pub mod history;
|
||||
pub mod import;
|
||||
pub mod rollback;
|
||||
pub mod search;
|
||||
pub mod update;
|
||||
pub mod user;
|
||||
pub mod util;
|
||||
452
crates/secrets-core/src/service/rollback.rs
Normal file
452
crates/secrets-core/src/service/rollback.rs
Normal file
@@ -0,0 +1,452 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use anyhow::Result;
|
||||
use serde_json::Value;
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::db;
|
||||
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
pub struct RollbackResult {
|
||||
pub name: String,
|
||||
pub folder: String,
|
||||
#[serde(rename = "type")]
|
||||
pub entry_type: String,
|
||||
pub restored_version: i64,
|
||||
}
|
||||
|
||||
/// Roll back entry `name` to `to_version` (or the most recent snapshot if None).
|
||||
/// `folder` is optional; if omitted and multiple entries share the name, an error is returned.
|
||||
pub async fn run(
|
||||
pool: &PgPool,
|
||||
name: &str,
|
||||
folder: Option<&str>,
|
||||
to_version: Option<i64>,
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<RollbackResult> {
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct EntryHistoryRow {
|
||||
folder: String,
|
||||
#[sqlx(rename = "type")]
|
||||
entry_type: String,
|
||||
version: i64,
|
||||
action: String,
|
||||
tags: Vec<String>,
|
||||
metadata: Value,
|
||||
}
|
||||
|
||||
// Disambiguate: find the unique entry_id for (name, folder).
|
||||
// Query entries_history by entry_id once we know it; first resolve via name + optional folder.
|
||||
let entry_id: Option<Uuid> = if let Some(uid) = user_id {
|
||||
if let Some(f) = folder {
|
||||
sqlx::query_scalar(
|
||||
"SELECT DISTINCT entry_id FROM entries_history \
|
||||
WHERE name = $1 AND folder = $2 AND user_id = $3 LIMIT 1",
|
||||
)
|
||||
.bind(name)
|
||||
.bind(f)
|
||||
.bind(uid)
|
||||
.fetch_optional(pool)
|
||||
.await?
|
||||
} else {
|
||||
let ids: Vec<Uuid> = sqlx::query_scalar(
|
||||
"SELECT DISTINCT entry_id FROM entries_history \
|
||||
WHERE name = $1 AND user_id = $2",
|
||||
)
|
||||
.bind(name)
|
||||
.bind(uid)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
match ids.len() {
|
||||
0 => None,
|
||||
1 => Some(ids[0]),
|
||||
_ => {
|
||||
let folders: Vec<String> = sqlx::query_scalar(
|
||||
"SELECT DISTINCT folder FROM entries_history \
|
||||
WHERE name = $1 AND user_id = $2",
|
||||
)
|
||||
.bind(name)
|
||||
.bind(uid)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
anyhow::bail!(
|
||||
"Ambiguous: entries named '{}' exist in folders: [{}]. \
|
||||
Specify 'folder' to disambiguate.",
|
||||
name,
|
||||
folders.join(", ")
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if let Some(f) = folder {
|
||||
sqlx::query_scalar(
|
||||
"SELECT DISTINCT entry_id FROM entries_history \
|
||||
WHERE name = $1 AND folder = $2 AND user_id IS NULL LIMIT 1",
|
||||
)
|
||||
.bind(name)
|
||||
.bind(f)
|
||||
.fetch_optional(pool)
|
||||
.await?
|
||||
} else {
|
||||
let ids: Vec<Uuid> = sqlx::query_scalar(
|
||||
"SELECT DISTINCT entry_id FROM entries_history \
|
||||
WHERE name = $1 AND user_id IS NULL",
|
||||
)
|
||||
.bind(name)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
match ids.len() {
|
||||
0 => None,
|
||||
1 => Some(ids[0]),
|
||||
_ => {
|
||||
let folders: Vec<String> = sqlx::query_scalar(
|
||||
"SELECT DISTINCT folder FROM entries_history \
|
||||
WHERE name = $1 AND user_id IS NULL",
|
||||
)
|
||||
.bind(name)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
anyhow::bail!(
|
||||
"Ambiguous: entries named '{}' exist in folders: [{}]. \
|
||||
Specify 'folder' to disambiguate.",
|
||||
name,
|
||||
folders.join(", ")
|
||||
)
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let entry_id = entry_id.ok_or_else(|| anyhow::anyhow!("No history found for '{}'", name))?;
|
||||
|
||||
let snap: Option<EntryHistoryRow> = if let Some(ver) = to_version {
|
||||
sqlx::query_as(
|
||||
"SELECT folder, type, version, action, tags, metadata \
|
||||
FROM entries_history \
|
||||
WHERE entry_id = $1 AND version = $2 ORDER BY id ASC LIMIT 1",
|
||||
)
|
||||
.bind(entry_id)
|
||||
.bind(ver)
|
||||
.fetch_optional(pool)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_as(
|
||||
"SELECT folder, type, version, action, tags, metadata \
|
||||
FROM entries_history \
|
||||
WHERE entry_id = $1 ORDER BY id DESC LIMIT 1",
|
||||
)
|
||||
.bind(entry_id)
|
||||
.fetch_optional(pool)
|
||||
.await?
|
||||
};
|
||||
|
||||
let snap = snap.ok_or_else(|| {
|
||||
anyhow::anyhow!(
|
||||
"No history found for '{}'{}.",
|
||||
name,
|
||||
to_version
|
||||
.map(|v| format!(" at version {}", v))
|
||||
.unwrap_or_default()
|
||||
)
|
||||
})?;
|
||||
|
||||
let snap_secret_snapshot = db::entry_secret_snapshot_from_metadata(&snap.metadata);
|
||||
let snap_metadata = db::strip_secret_snapshot_from_metadata(&snap.metadata);
|
||||
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct LiveEntry {
|
||||
id: Uuid,
|
||||
version: i64,
|
||||
folder: String,
|
||||
#[sqlx(rename = "type")]
|
||||
entry_type: String,
|
||||
tags: Vec<String>,
|
||||
metadata: Value,
|
||||
}
|
||||
|
||||
// Lock the live entry if it exists (matched by entry_id for precision).
|
||||
let live: Option<LiveEntry> = sqlx::query_as(
|
||||
"SELECT id, version, folder, type, tags, metadata FROM entries \
|
||||
WHERE id = $1 FOR UPDATE",
|
||||
)
|
||||
.bind(entry_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
|
||||
let live_entry_id = if let Some(ref lr) = live {
|
||||
let history_metadata =
|
||||
match db::metadata_with_secret_snapshot(&mut tx, lr.id, &lr.metadata).await {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "failed to build secret snapshot for entry history");
|
||||
lr.metadata.clone()
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = db::snapshot_entry_history(
|
||||
&mut tx,
|
||||
db::EntrySnapshotParams {
|
||||
entry_id: lr.id,
|
||||
user_id,
|
||||
folder: &lr.folder,
|
||||
entry_type: &lr.entry_type,
|
||||
name,
|
||||
version: lr.version,
|
||||
action: "rollback",
|
||||
tags: &lr.tags,
|
||||
metadata: &history_metadata,
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to snapshot entry before rollback");
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct LiveField {
|
||||
id: Uuid,
|
||||
name: String,
|
||||
encrypted: Vec<u8>,
|
||||
}
|
||||
let live_fields: Vec<LiveField> = sqlx::query_as(
|
||||
"SELECT s.id, s.name, s.encrypted \
|
||||
FROM entry_secrets es \
|
||||
JOIN secrets s ON s.id = es.secret_id \
|
||||
WHERE es.entry_id = $1",
|
||||
)
|
||||
.bind(lr.id)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
|
||||
for f in &live_fields {
|
||||
if let Err(e) = db::snapshot_secret_history(
|
||||
&mut tx,
|
||||
db::SecretSnapshotParams {
|
||||
secret_id: f.id,
|
||||
name: &f.name,
|
||||
encrypted: &f.encrypted,
|
||||
action: "rollback",
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to snapshot secret field before rollback");
|
||||
}
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE entries SET folder = $1, type = $2, tags = $3, metadata = $4, version = version + 1, \
|
||||
updated_at = NOW() WHERE id = $5",
|
||||
)
|
||||
.bind(&snap.folder)
|
||||
.bind(&snap.entry_type)
|
||||
.bind(&snap.tags)
|
||||
.bind(&snap_metadata)
|
||||
.bind(lr.id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
lr.id
|
||||
} else {
|
||||
if let Some(uid) = user_id {
|
||||
sqlx::query_scalar(
|
||||
"INSERT INTO entries \
|
||||
(user_id, folder, type, name, notes, tags, metadata, version, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, '', $5, $6, $7, NOW()) RETURNING id",
|
||||
)
|
||||
.bind(uid)
|
||||
.bind(&snap.folder)
|
||||
.bind(&snap.entry_type)
|
||||
.bind(name)
|
||||
.bind(&snap.tags)
|
||||
.bind(&snap_metadata)
|
||||
.bind(snap.version)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_scalar(
|
||||
"INSERT INTO entries \
|
||||
(folder, type, name, notes, tags, metadata, version, updated_at) \
|
||||
VALUES ($1, $2, $3, '', $4, $5, $6, NOW()) RETURNING id",
|
||||
)
|
||||
.bind(&snap.folder)
|
||||
.bind(&snap.entry_type)
|
||||
.bind(name)
|
||||
.bind(&snap.tags)
|
||||
.bind(&snap_metadata)
|
||||
.bind(snap.version)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(secret_snapshot) = snap_secret_snapshot {
|
||||
restore_entry_secrets(&mut tx, live_entry_id, user_id, &secret_snapshot).await?;
|
||||
}
|
||||
|
||||
crate::audit::log_tx(
|
||||
&mut tx,
|
||||
user_id,
|
||||
"rollback",
|
||||
&snap.folder,
|
||||
&snap.entry_type,
|
||||
name,
|
||||
serde_json::json!({
|
||||
"restored_version": snap.version,
|
||||
"original_action": snap.action,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(RollbackResult {
|
||||
name: name.to_string(),
|
||||
folder: snap.folder,
|
||||
entry_type: snap.entry_type,
|
||||
restored_version: snap.version,
|
||||
})
|
||||
}
|
||||
|
||||
async fn restore_entry_secrets(
|
||||
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
entry_id: Uuid,
|
||||
user_id: Option<Uuid>,
|
||||
snapshot: &[db::EntrySecretSnapshot],
|
||||
) -> Result<()> {
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct LinkedSecret {
|
||||
id: Uuid,
|
||||
name: String,
|
||||
encrypted: Vec<u8>,
|
||||
}
|
||||
|
||||
let linked: Vec<LinkedSecret> = sqlx::query_as(
|
||||
"SELECT s.id, s.name, s.encrypted \
|
||||
FROM entry_secrets es \
|
||||
JOIN secrets s ON s.id = es.secret_id \
|
||||
WHERE es.entry_id = $1",
|
||||
)
|
||||
.bind(entry_id)
|
||||
.fetch_all(&mut **tx)
|
||||
.await?;
|
||||
|
||||
let target_names: HashSet<&str> = snapshot.iter().map(|s| s.name.as_str()).collect();
|
||||
|
||||
for s in &linked {
|
||||
if target_names.contains(s.name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
if let Err(e) = db::snapshot_secret_history(
|
||||
tx,
|
||||
db::SecretSnapshotParams {
|
||||
secret_id: s.id,
|
||||
name: &s.name,
|
||||
encrypted: &s.encrypted,
|
||||
action: "rollback",
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to snapshot secret before rollback unlink");
|
||||
}
|
||||
|
||||
sqlx::query("DELETE FROM entry_secrets WHERE entry_id = $1 AND secret_id = $2")
|
||||
.bind(entry_id)
|
||||
.bind(s.id)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
|
||||
sqlx::query(
|
||||
"DELETE FROM secrets s \
|
||||
WHERE s.id = $1 \
|
||||
AND NOT EXISTS (SELECT 1 FROM entry_secrets es WHERE es.secret_id = s.id)",
|
||||
)
|
||||
.bind(s.id)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
}
|
||||
|
||||
for snap in snapshot {
|
||||
let encrypted = ::hex::decode(&snap.encrypted_hex).map_err(|e| {
|
||||
anyhow::anyhow!("invalid secret snapshot data for '{}': {}", snap.name, e)
|
||||
})?;
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct ExistingSecret {
|
||||
id: Uuid,
|
||||
encrypted: Vec<u8>,
|
||||
}
|
||||
|
||||
let existing: Option<ExistingSecret> = if let Some(uid) = user_id {
|
||||
sqlx::query_as("SELECT id, encrypted FROM secrets WHERE user_id = $1 AND name = $2")
|
||||
.bind(uid)
|
||||
.bind(&snap.name)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_as("SELECT id, encrypted FROM secrets WHERE user_id IS NULL AND name = $1")
|
||||
.bind(&snap.name)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?
|
||||
};
|
||||
|
||||
let secret_id = if let Some(ex) = existing {
|
||||
if ex.encrypted != encrypted
|
||||
&& let Err(e) = db::snapshot_secret_history(
|
||||
tx,
|
||||
db::SecretSnapshotParams {
|
||||
secret_id: ex.id,
|
||||
name: &snap.name,
|
||||
encrypted: &ex.encrypted,
|
||||
action: "rollback",
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to snapshot secret before rollback restore");
|
||||
}
|
||||
sqlx::query(
|
||||
"UPDATE secrets SET type = $1, encrypted = $2, version = version + 1, updated_at = NOW() \
|
||||
WHERE id = $3",
|
||||
)
|
||||
.bind(&snap.secret_type)
|
||||
.bind(&encrypted)
|
||||
.bind(ex.id)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
ex.id
|
||||
} else if let Some(uid) = user_id {
|
||||
sqlx::query_scalar(
|
||||
"INSERT INTO secrets (user_id, name, type, encrypted) VALUES ($1, $2, $3, $4) RETURNING id",
|
||||
)
|
||||
.bind(uid)
|
||||
.bind(&snap.name)
|
||||
.bind(&snap.secret_type)
|
||||
.bind(&encrypted)
|
||||
.fetch_one(&mut **tx)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_scalar(
|
||||
"INSERT INTO secrets (user_id, name, type, encrypted) VALUES (NULL, $1, $2, $3) RETURNING id",
|
||||
)
|
||||
.bind(&snap.name)
|
||||
.bind(&snap.secret_type)
|
||||
.bind(&encrypted)
|
||||
.fetch_one(&mut **tx)
|
||||
.await?
|
||||
};
|
||||
|
||||
sqlx::query(
|
||||
"INSERT INTO entry_secrets (entry_id, secret_id) VALUES ($1, $2) ON CONFLICT DO NOTHING",
|
||||
)
|
||||
.bind(entry_id)
|
||||
.bind(secret_id)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
399
crates/secrets-core/src/service/search.rs
Normal file
399
crates/secrets-core/src/service/search.rs
Normal file
@@ -0,0 +1,399 @@
|
||||
use anyhow::Result;
|
||||
use serde_json::Value;
|
||||
use sqlx::PgPool;
|
||||
use std::collections::HashMap;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::models::{Entry, SecretField};
|
||||
|
||||
pub const FETCH_ALL_LIMIT: u32 = 10_000;
|
||||
|
||||
/// Build an ILIKE pattern for fuzzy matching, escaping `%` and `_` literals.
|
||||
pub fn ilike_pattern(value: &str) -> String {
|
||||
format!(
|
||||
"%{}%",
|
||||
value
|
||||
.replace('\\', "\\\\")
|
||||
.replace('%', "\\%")
|
||||
.replace('_', "\\_")
|
||||
)
|
||||
}
|
||||
|
||||
pub struct SearchParams<'a> {
|
||||
pub folder: Option<&'a str>,
|
||||
pub entry_type: Option<&'a str>,
|
||||
pub name: Option<&'a str>,
|
||||
/// Fuzzy match on `entries.name` only (ILIKE with escaped `%`/`_`).
|
||||
pub name_query: Option<&'a str>,
|
||||
pub tags: &'a [String],
|
||||
pub query: Option<&'a str>,
|
||||
pub sort: &'a str,
|
||||
pub limit: u32,
|
||||
pub offset: u32,
|
||||
/// Multi-user: filter by this user_id. None = single-user / no filter.
|
||||
pub user_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
pub struct SearchResult {
|
||||
pub entries: Vec<Entry>,
|
||||
pub secret_schemas: HashMap<Uuid, Vec<SecretField>>,
|
||||
}
|
||||
|
||||
/// List `entries` rows matching params (paged, ordered per `params.sort`).
|
||||
/// Does not read the `secrets` table.
|
||||
pub async fn list_entries(pool: &PgPool, params: SearchParams<'_>) -> Result<Vec<Entry>> {
|
||||
fetch_entries_paged(pool, ¶ms).await
|
||||
}
|
||||
|
||||
/// Count `entries` rows matching the same filters as [`list_entries`] (ignores `sort` / `limit` / `offset`).
|
||||
/// Does not read the `secrets` table.
|
||||
pub async fn count_entries(pool: &PgPool, a: &SearchParams<'_>) -> Result<i64> {
|
||||
let (where_clause, _) = entry_where_clause_and_next_idx(a);
|
||||
let sql = format!("SELECT COUNT(*)::bigint FROM entries {where_clause}");
|
||||
let mut q = sqlx::query_scalar::<_, i64>(&sql);
|
||||
if let Some(uid) = a.user_id {
|
||||
q = q.bind(uid);
|
||||
}
|
||||
if let Some(v) = a.folder {
|
||||
q = q.bind(v);
|
||||
}
|
||||
if let Some(v) = a.entry_type {
|
||||
q = q.bind(v);
|
||||
}
|
||||
if let Some(v) = a.name {
|
||||
q = q.bind(v);
|
||||
}
|
||||
if let Some(v) = a.name_query {
|
||||
let pattern = ilike_pattern(v);
|
||||
q = q.bind(pattern);
|
||||
}
|
||||
for tag in a.tags {
|
||||
q = q.bind(tag);
|
||||
}
|
||||
if let Some(v) = a.query {
|
||||
let pattern = ilike_pattern(v);
|
||||
q = q.bind(pattern);
|
||||
}
|
||||
let n = q.fetch_one(pool).await?;
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Shared WHERE clause and the next `$n` index (for LIMIT/OFFSET in paged queries).
|
||||
fn entry_where_clause_and_next_idx(a: &SearchParams<'_>) -> (String, i32) {
|
||||
let mut conditions: Vec<String> = Vec::new();
|
||||
let mut idx: i32 = 1;
|
||||
|
||||
if a.user_id.is_some() {
|
||||
conditions.push(format!("user_id = ${}", idx));
|
||||
idx += 1;
|
||||
} else {
|
||||
conditions.push("user_id IS NULL".to_string());
|
||||
}
|
||||
|
||||
if a.folder.is_some() {
|
||||
conditions.push(format!("folder = ${}", idx));
|
||||
idx += 1;
|
||||
}
|
||||
if a.entry_type.is_some() {
|
||||
conditions.push(format!("type = ${}", idx));
|
||||
idx += 1;
|
||||
}
|
||||
if a.name.is_some() {
|
||||
conditions.push(format!("name = ${}", idx));
|
||||
idx += 1;
|
||||
}
|
||||
if a.name_query.is_some() {
|
||||
conditions.push(format!("name ILIKE ${} ESCAPE '\\'", idx));
|
||||
idx += 1;
|
||||
}
|
||||
if !a.tags.is_empty() {
|
||||
let placeholders: Vec<String> = a
|
||||
.tags
|
||||
.iter()
|
||||
.map(|_| {
|
||||
let p = format!("${}", idx);
|
||||
idx += 1;
|
||||
p
|
||||
})
|
||||
.collect();
|
||||
conditions.push(format!(
|
||||
"tags @> ARRAY[{}]::text[]",
|
||||
placeholders.join(", ")
|
||||
));
|
||||
}
|
||||
if a.query.is_some() {
|
||||
conditions.push(format!(
|
||||
"(name ILIKE ${i} ESCAPE '\\' OR folder ILIKE ${i} ESCAPE '\\' \
|
||||
OR type ILIKE ${i} ESCAPE '\\' OR notes ILIKE ${i} ESCAPE '\\' \
|
||||
OR metadata::text ILIKE ${i} ESCAPE '\\' \
|
||||
OR EXISTS (SELECT 1 FROM unnest(tags) t WHERE t ILIKE ${i} ESCAPE '\\'))",
|
||||
i = idx
|
||||
));
|
||||
idx += 1;
|
||||
}
|
||||
|
||||
let where_clause = if conditions.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("WHERE {}", conditions.join(" AND "))
|
||||
};
|
||||
(where_clause, idx)
|
||||
}
|
||||
|
||||
pub async fn run(pool: &PgPool, params: SearchParams<'_>) -> Result<SearchResult> {
|
||||
let entries = fetch_entries_paged(pool, ¶ms).await?;
|
||||
let entry_ids: Vec<Uuid> = entries.iter().map(|e| e.id).collect();
|
||||
let secret_schemas = if !entry_ids.is_empty() {
|
||||
fetch_secrets_for_entries(pool, &entry_ids).await?
|
||||
} else {
|
||||
HashMap::new()
|
||||
};
|
||||
Ok(SearchResult {
|
||||
entries,
|
||||
secret_schemas,
|
||||
})
|
||||
}
|
||||
|
||||
/// Fetch entries matching the given filters — returns all matching entries up to FETCH_ALL_LIMIT.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn fetch_entries(
|
||||
pool: &PgPool,
|
||||
folder: Option<&str>,
|
||||
entry_type: Option<&str>,
|
||||
name: Option<&str>,
|
||||
tags: &[String],
|
||||
query: Option<&str>,
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<Vec<Entry>> {
|
||||
let params = SearchParams {
|
||||
folder,
|
||||
entry_type,
|
||||
name,
|
||||
name_query: None,
|
||||
tags,
|
||||
query,
|
||||
sort: "name",
|
||||
limit: FETCH_ALL_LIMIT,
|
||||
offset: 0,
|
||||
user_id,
|
||||
};
|
||||
list_entries(pool, params).await
|
||||
}
|
||||
|
||||
async fn fetch_entries_paged(pool: &PgPool, a: &SearchParams<'_>) -> Result<Vec<Entry>> {
|
||||
let (where_clause, idx) = entry_where_clause_and_next_idx(a);
|
||||
|
||||
let order = match a.sort {
|
||||
"updated" => "updated_at DESC",
|
||||
"created" => "created_at DESC",
|
||||
_ => "name ASC",
|
||||
};
|
||||
|
||||
let limit_idx = idx;
|
||||
let offset_idx = idx + 1;
|
||||
|
||||
let sql = format!(
|
||||
"SELECT id, user_id, folder, type, name, notes, tags, metadata, version, \
|
||||
created_at, updated_at \
|
||||
FROM entries {where_clause} ORDER BY {order} LIMIT ${limit_idx} OFFSET ${offset_idx}"
|
||||
);
|
||||
|
||||
let mut q = sqlx::query_as::<_, EntryRaw>(&sql);
|
||||
if let Some(uid) = a.user_id {
|
||||
q = q.bind(uid);
|
||||
}
|
||||
if let Some(v) = a.folder {
|
||||
q = q.bind(v);
|
||||
}
|
||||
if let Some(v) = a.entry_type {
|
||||
q = q.bind(v);
|
||||
}
|
||||
if let Some(v) = a.name {
|
||||
q = q.bind(v);
|
||||
}
|
||||
if let Some(v) = a.name_query {
|
||||
let pattern = ilike_pattern(v);
|
||||
q = q.bind(pattern);
|
||||
}
|
||||
for tag in a.tags {
|
||||
q = q.bind(tag);
|
||||
}
|
||||
if let Some(v) = a.query {
|
||||
let pattern = ilike_pattern(v);
|
||||
q = q.bind(pattern);
|
||||
}
|
||||
q = q.bind(a.limit as i64).bind(a.offset as i64);
|
||||
|
||||
let rows = q.fetch_all(pool).await?;
|
||||
Ok(rows.into_iter().map(Entry::from).collect())
|
||||
}
|
||||
|
||||
/// Fetch all secret fields (including encrypted bytes) for a set of entry ids.
|
||||
pub async fn fetch_secrets_for_entries(
|
||||
pool: &PgPool,
|
||||
entry_ids: &[Uuid],
|
||||
) -> Result<HashMap<Uuid, Vec<SecretField>>> {
|
||||
if entry_ids.is_empty() {
|
||||
return Ok(HashMap::new());
|
||||
}
|
||||
let fields: Vec<EntrySecretRow> = sqlx::query_as(
|
||||
"SELECT es.entry_id, s.id, s.user_id, s.name, s.type, s.encrypted, s.version, s.created_at, s.updated_at \
|
||||
FROM entry_secrets es \
|
||||
JOIN secrets s ON s.id = es.secret_id \
|
||||
WHERE es.entry_id = ANY($1) \
|
||||
ORDER BY es.entry_id, es.sort_order, s.name",
|
||||
)
|
||||
.bind(entry_ids)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
|
||||
let mut map: HashMap<Uuid, Vec<SecretField>> = HashMap::new();
|
||||
for f in fields {
|
||||
let entry_id = f.entry_id;
|
||||
map.entry(entry_id).or_default().push(f.secret());
|
||||
}
|
||||
Ok(map)
|
||||
}
|
||||
|
||||
/// Resolve exactly one entry by its UUID primary key.
|
||||
///
|
||||
/// Returns an error if the entry does not exist or does not belong to the given user.
|
||||
pub async fn resolve_entry_by_id(
|
||||
pool: &PgPool,
|
||||
id: Uuid,
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<crate::models::Entry> {
|
||||
let row: Option<EntryRaw> = if let Some(uid) = user_id {
|
||||
sqlx::query_as(
|
||||
"SELECT id, user_id, folder, type, name, notes, tags, metadata, version, \
|
||||
created_at, updated_at FROM entries WHERE id = $1 AND user_id = $2",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(uid)
|
||||
.fetch_optional(pool)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_as(
|
||||
"SELECT id, user_id, folder, type, name, notes, tags, metadata, version, \
|
||||
created_at, updated_at FROM entries WHERE id = $1 AND user_id IS NULL",
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_optional(pool)
|
||||
.await?
|
||||
};
|
||||
row.map(Entry::from)
|
||||
.ok_or_else(|| anyhow::anyhow!("Entry with id '{}' not found", id))
|
||||
}
|
||||
|
||||
/// Resolve exactly one entry by name, with optional folder for disambiguation.
|
||||
///
|
||||
/// - If `folder` is provided: exact `(folder, name)` match.
|
||||
/// - If `folder` is None and exactly one entry matches: returns it.
|
||||
/// - If `folder` is None and multiple entries match: returns an error listing
|
||||
/// the folders and asking the caller to specify one.
|
||||
pub async fn resolve_entry(
|
||||
pool: &PgPool,
|
||||
name: &str,
|
||||
folder: Option<&str>,
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<crate::models::Entry> {
|
||||
let entries = fetch_entries(pool, folder, None, Some(name), &[], None, user_id).await?;
|
||||
match entries.len() {
|
||||
0 => {
|
||||
if let Some(f) = folder {
|
||||
anyhow::bail!("Not found: '{}' in folder '{}'", name, f)
|
||||
} else {
|
||||
anyhow::bail!("Not found: '{}'", name)
|
||||
}
|
||||
}
|
||||
1 => entries
|
||||
.into_iter()
|
||||
.next()
|
||||
.ok_or_else(|| anyhow::anyhow!("internal: resolve_entry result vanished")),
|
||||
_ => {
|
||||
let folders: Vec<&str> = entries.iter().map(|e| e.folder.as_str()).collect();
|
||||
anyhow::bail!(
|
||||
"Ambiguous: {} entries named '{}' found in folders: [{}]. \
|
||||
Specify 'folder' to disambiguate.",
|
||||
entries.len(),
|
||||
name,
|
||||
folders.join(", ")
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Internal raw row (because user_id is nullable in DB) ─────────────────────
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct EntryRaw {
|
||||
id: Uuid,
|
||||
user_id: Option<Uuid>,
|
||||
folder: String,
|
||||
#[sqlx(rename = "type")]
|
||||
entry_type: String,
|
||||
name: String,
|
||||
notes: String,
|
||||
tags: Vec<String>,
|
||||
metadata: Value,
|
||||
version: i64,
|
||||
created_at: chrono::DateTime<chrono::Utc>,
|
||||
updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl From<EntryRaw> for Entry {
|
||||
fn from(r: EntryRaw) -> Self {
|
||||
Entry {
|
||||
id: r.id,
|
||||
user_id: r.user_id,
|
||||
folder: r.folder,
|
||||
entry_type: r.entry_type,
|
||||
name: r.name,
|
||||
notes: r.notes,
|
||||
tags: r.tags,
|
||||
metadata: r.metadata,
|
||||
version: r.version,
|
||||
created_at: r.created_at,
|
||||
updated_at: r.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct EntrySecretRow {
|
||||
entry_id: Uuid,
|
||||
id: Uuid,
|
||||
user_id: Option<Uuid>,
|
||||
name: String,
|
||||
#[sqlx(rename = "type")]
|
||||
secret_type: String,
|
||||
encrypted: Vec<u8>,
|
||||
version: i64,
|
||||
created_at: chrono::DateTime<chrono::Utc>,
|
||||
updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl EntrySecretRow {
|
||||
fn secret(self) -> SecretField {
|
||||
SecretField {
|
||||
id: self.id,
|
||||
user_id: self.user_id,
|
||||
name: self.name,
|
||||
secret_type: self.secret_type,
|
||||
encrypted: self.encrypted,
|
||||
version: self.version,
|
||||
created_at: self.created_at,
|
||||
updated_at: self.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ilike_pattern_escapes_backslash_percent_and_underscore() {
|
||||
assert_eq!(ilike_pattern(r"hello\_100%"), r"%hello\\\_100\%%");
|
||||
}
|
||||
}
|
||||
561
crates/secrets-core/src/service/update.rs
Normal file
561
crates/secrets-core/src/service/update.rs
Normal file
@@ -0,0 +1,561 @@
|
||||
use anyhow::Result;
|
||||
use serde_json::{Map, Value};
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::crypto;
|
||||
use crate::db;
|
||||
use crate::error::{AppError, DbErrorContext};
|
||||
use crate::models::{EntryRow, EntryWriteRow};
|
||||
use crate::service::add::{
|
||||
collect_field_paths, collect_key_paths, flatten_json_fields, insert_path, parse_key_path,
|
||||
parse_kv, remove_path,
|
||||
};
|
||||
use crate::service::util::user_scope_condition;
|
||||
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
pub struct UpdateResult {
|
||||
pub name: String,
|
||||
pub folder: String,
|
||||
#[serde(rename = "type")]
|
||||
pub entry_type: String,
|
||||
pub add_tags: Vec<String>,
|
||||
pub remove_tags: Vec<String>,
|
||||
pub meta_keys: Vec<String>,
|
||||
pub remove_meta: Vec<String>,
|
||||
pub secret_keys: Vec<String>,
|
||||
pub remove_secrets: Vec<String>,
|
||||
pub linked_secrets: Vec<String>,
|
||||
pub unlinked_secrets: Vec<String>,
|
||||
}
|
||||
|
||||
pub struct UpdateParams<'a> {
|
||||
pub name: &'a str,
|
||||
/// Optional folder for disambiguation when multiple entries share the same name.
|
||||
pub folder: Option<&'a str>,
|
||||
pub notes: Option<&'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 secret_types: &'a std::collections::HashMap<String, String>,
|
||||
pub remove_secrets: &'a [String],
|
||||
pub link_secret_names: &'a [String],
|
||||
pub unlink_secret_names: &'a [String],
|
||||
pub user_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
pub async fn run(
|
||||
pool: &PgPool,
|
||||
params: UpdateParams<'_>,
|
||||
master_key: &[u8; 32],
|
||||
) -> Result<UpdateResult> {
|
||||
if params.name.chars().count() > 256 {
|
||||
anyhow::bail!("name must be at most 256 characters");
|
||||
}
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
// Fetch matching rows with FOR UPDATE; use folder when provided to resolve ambiguity.
|
||||
let mut idx = 1i32;
|
||||
let user_cond = user_scope_condition(params.user_id, &mut idx);
|
||||
let mut conditions = vec![user_cond];
|
||||
if params.folder.is_some() {
|
||||
conditions.push(format!("folder = ${}", idx));
|
||||
idx += 1;
|
||||
}
|
||||
conditions.push(format!("name = ${}", idx));
|
||||
let sql = format!(
|
||||
"SELECT id, version, folder, type, tags, metadata, notes FROM entries WHERE {} FOR UPDATE",
|
||||
conditions.join(" AND ")
|
||||
);
|
||||
let mut q = sqlx::query_as::<_, EntryRow>(&sql);
|
||||
if let Some(uid) = params.user_id {
|
||||
q = q.bind(uid);
|
||||
}
|
||||
if let Some(folder) = params.folder {
|
||||
q = q.bind(folder);
|
||||
}
|
||||
q = q.bind(params.name);
|
||||
let rows = q.fetch_all(&mut *tx).await?;
|
||||
|
||||
let row = match rows.len() {
|
||||
0 => {
|
||||
tx.rollback().await?;
|
||||
return Err(AppError::NotFoundEntry.into());
|
||||
}
|
||||
1 => rows
|
||||
.into_iter()
|
||||
.next()
|
||||
.ok_or_else(|| anyhow::anyhow!("internal: matched row vanished"))?,
|
||||
_ => {
|
||||
tx.rollback().await?;
|
||||
let folders: Vec<&str> = rows.iter().map(|r| r.folder.as_str()).collect();
|
||||
anyhow::bail!(
|
||||
"Ambiguous: {} entries named '{}' found in folders: [{}]. \
|
||||
Specify 'folder' to disambiguate.",
|
||||
rows.len(),
|
||||
params.name,
|
||||
folders.join(", ")
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
let history_metadata =
|
||||
match db::metadata_with_secret_snapshot(&mut tx, row.id, &row.metadata).await {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "failed to build secret snapshot for entry history");
|
||||
row.metadata.clone()
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = db::snapshot_entry_history(
|
||||
&mut tx,
|
||||
db::EntrySnapshotParams {
|
||||
entry_id: row.id,
|
||||
user_id: params.user_id,
|
||||
folder: &row.folder,
|
||||
entry_type: &row.entry_type,
|
||||
name: params.name,
|
||||
version: row.version,
|
||||
action: "update",
|
||||
tags: &row.tags,
|
||||
metadata: &history_metadata,
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to snapshot entry history before update");
|
||||
}
|
||||
|
||||
let mut tags: Vec<String> = row.tags.clone();
|
||||
for t in params.add_tags {
|
||||
if !tags.contains(t) {
|
||||
tags.push(t.clone());
|
||||
}
|
||||
}
|
||||
tags.retain(|t| !params.remove_tags.contains(t));
|
||||
|
||||
let mut meta_map: Map<String, Value> = match row.metadata.clone() {
|
||||
Value::Object(m) => m,
|
||||
_ => Map::new(),
|
||||
};
|
||||
for entry in params.meta_entries {
|
||||
let (path, value) = parse_kv(entry)?;
|
||||
insert_path(&mut meta_map, &path, value)?;
|
||||
}
|
||||
for key in params.remove_meta {
|
||||
let path = parse_key_path(key)?;
|
||||
remove_path(&mut meta_map, &path)?;
|
||||
}
|
||||
let metadata = Value::Object(meta_map);
|
||||
|
||||
let new_notes = params.notes.unwrap_or(&row.notes);
|
||||
|
||||
let result = sqlx::query(
|
||||
"UPDATE entries SET tags = $1, metadata = $2, notes = $3, \
|
||||
version = version + 1, updated_at = NOW() \
|
||||
WHERE id = $4 AND version = $5",
|
||||
)
|
||||
.bind(&tags)
|
||||
.bind(&metadata)
|
||||
.bind(new_notes)
|
||||
.bind(row.id)
|
||||
.bind(row.version)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
if result.rows_affected() == 0 {
|
||||
tx.rollback().await?;
|
||||
return Err(AppError::ConcurrentModification.into());
|
||||
}
|
||||
|
||||
for entry in params.secret_entries {
|
||||
let (path, field_value) = parse_kv(entry)?;
|
||||
let flat = flatten_json_fields("", &{
|
||||
let mut m = Map::new();
|
||||
insert_path(&mut m, &path, field_value)?;
|
||||
Value::Object(m)
|
||||
});
|
||||
|
||||
for (field_name, fv) in &flat {
|
||||
let encrypted = crypto::encrypt_json(master_key, fv)?;
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct ExistingField {
|
||||
id: Uuid,
|
||||
encrypted: Vec<u8>,
|
||||
}
|
||||
let ef: Option<ExistingField> = sqlx::query_as(
|
||||
"SELECT s.id, s.encrypted \
|
||||
FROM entry_secrets es \
|
||||
JOIN secrets s ON s.id = es.secret_id \
|
||||
WHERE es.entry_id = $1 AND s.name = $2",
|
||||
)
|
||||
.bind(row.id)
|
||||
.bind(field_name)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
|
||||
if let Some(ef) = &ef
|
||||
&& let Err(e) = db::snapshot_secret_history(
|
||||
&mut tx,
|
||||
db::SecretSnapshotParams {
|
||||
secret_id: ef.id,
|
||||
name: field_name,
|
||||
encrypted: &ef.encrypted,
|
||||
action: "update",
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to snapshot secret field history");
|
||||
}
|
||||
|
||||
if let Some(ef) = ef {
|
||||
sqlx::query(
|
||||
"UPDATE secrets SET encrypted = $1, version = version + 1, updated_at = NOW() WHERE id = $2",
|
||||
)
|
||||
.bind(&encrypted)
|
||||
.bind(ef.id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
} else {
|
||||
let secret_type = params
|
||||
.secret_types
|
||||
.get(field_name)
|
||||
.map(|s| s.as_str())
|
||||
.unwrap_or("text");
|
||||
let secret_id: Uuid = sqlx::query_scalar(
|
||||
"INSERT INTO secrets (user_id, name, type, encrypted) VALUES ($1, $2, $3, $4) RETURNING id",
|
||||
)
|
||||
.bind(params.user_id)
|
||||
.bind(field_name.to_string())
|
||||
.bind(secret_type)
|
||||
.bind(&encrypted)
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.map_err(|e| AppError::from_db_error(e, DbErrorContext::secret_name(field_name)))?;
|
||||
sqlx::query("INSERT INTO entry_secrets (entry_id, secret_id) VALUES ($1, $2)")
|
||||
.bind(row.id)
|
||||
.bind(secret_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for key in params.remove_secrets {
|
||||
let path = parse_key_path(key)?;
|
||||
let field_name = path.join(".");
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct FieldToDelete {
|
||||
id: Uuid,
|
||||
encrypted: Vec<u8>,
|
||||
}
|
||||
let field: Option<FieldToDelete> = sqlx::query_as(
|
||||
"SELECT s.id, s.encrypted \
|
||||
FROM entry_secrets es \
|
||||
JOIN secrets s ON s.id = es.secret_id \
|
||||
WHERE es.entry_id = $1 AND s.name = $2",
|
||||
)
|
||||
.bind(row.id)
|
||||
.bind(&field_name)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
|
||||
if let Some(f) = field {
|
||||
if let Err(e) = db::snapshot_secret_history(
|
||||
&mut tx,
|
||||
db::SecretSnapshotParams {
|
||||
secret_id: f.id,
|
||||
name: &field_name,
|
||||
encrypted: &f.encrypted,
|
||||
action: "delete",
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to snapshot secret field history before delete");
|
||||
}
|
||||
sqlx::query("DELETE FROM entry_secrets WHERE entry_id = $1 AND secret_id = $2")
|
||||
.bind(row.id)
|
||||
.bind(f.id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"DELETE FROM secrets s \
|
||||
WHERE s.id = $1 \
|
||||
AND NOT EXISTS (SELECT 1 FROM entry_secrets es WHERE es.secret_id = s.id)",
|
||||
)
|
||||
.bind(f.id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
|
||||
// Link existing secrets by name
|
||||
let mut linked_secrets = Vec::new();
|
||||
for link_name in params.link_secret_names {
|
||||
let link_name = link_name.trim();
|
||||
if link_name.is_empty() {
|
||||
anyhow::bail!("link_secret_names contains an empty name");
|
||||
}
|
||||
let secret_ids: Vec<Uuid> = if let Some(uid) = params.user_id {
|
||||
sqlx::query_scalar("SELECT id FROM secrets WHERE user_id = $1 AND name = $2")
|
||||
.bind(uid)
|
||||
.bind(link_name)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_scalar("SELECT id FROM secrets WHERE user_id IS NULL AND name = $1")
|
||||
.bind(link_name)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?
|
||||
};
|
||||
|
||||
match secret_ids.len() {
|
||||
0 => anyhow::bail!("Not found: secret named '{}'", link_name),
|
||||
1 => {
|
||||
sqlx::query(
|
||||
"INSERT INTO entry_secrets (entry_id, secret_id) VALUES ($1, $2) ON CONFLICT DO NOTHING",
|
||||
)
|
||||
.bind(row.id)
|
||||
.bind(secret_ids[0])
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
linked_secrets.push(link_name.to_string());
|
||||
}
|
||||
n => anyhow::bail!(
|
||||
"Ambiguous: {} secrets named '{}' found. Please deduplicate names first.",
|
||||
n,
|
||||
link_name
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// Unlink secrets by name
|
||||
let mut unlinked_secrets = Vec::new();
|
||||
for unlink_name in params.unlink_secret_names {
|
||||
let unlink_name = unlink_name.trim();
|
||||
if unlink_name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct SecretToUnlink {
|
||||
id: Uuid,
|
||||
encrypted: Vec<u8>,
|
||||
}
|
||||
let secret: Option<SecretToUnlink> = sqlx::query_as(
|
||||
"SELECT s.id, s.encrypted \
|
||||
FROM entry_secrets es \
|
||||
JOIN secrets s ON s.id = es.secret_id \
|
||||
WHERE es.entry_id = $1 AND s.name = $2",
|
||||
)
|
||||
.bind(row.id)
|
||||
.bind(unlink_name)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
|
||||
if let Some(s) = secret {
|
||||
if let Err(e) = db::snapshot_secret_history(
|
||||
&mut tx,
|
||||
db::SecretSnapshotParams {
|
||||
secret_id: s.id,
|
||||
name: unlink_name,
|
||||
encrypted: &s.encrypted,
|
||||
action: "delete",
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to snapshot secret field history before unlink");
|
||||
}
|
||||
sqlx::query("DELETE FROM entry_secrets WHERE entry_id = $1 AND secret_id = $2")
|
||||
.bind(row.id)
|
||||
.bind(s.id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"DELETE FROM secrets s \
|
||||
WHERE s.id = $1 \
|
||||
AND NOT EXISTS (SELECT 1 FROM entry_secrets es WHERE es.secret_id = s.id)",
|
||||
)
|
||||
.bind(s.id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
unlinked_secrets.push(unlink_name.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let meta_keys = collect_key_paths(params.meta_entries)?;
|
||||
let remove_meta_keys = collect_field_paths(params.remove_meta)?;
|
||||
let secret_keys = collect_key_paths(params.secret_entries)?;
|
||||
let remove_secret_keys = collect_field_paths(params.remove_secrets)?;
|
||||
|
||||
crate::audit::log_tx(
|
||||
&mut tx,
|
||||
params.user_id,
|
||||
"update",
|
||||
&row.folder,
|
||||
&row.entry_type,
|
||||
params.name,
|
||||
serde_json::json!({
|
||||
"add_tags": params.add_tags,
|
||||
"remove_tags": params.remove_tags,
|
||||
"meta_keys": meta_keys,
|
||||
"remove_meta": remove_meta_keys,
|
||||
"secret_keys": secret_keys,
|
||||
"remove_secrets": remove_secret_keys,
|
||||
"linked_secrets": linked_secrets,
|
||||
"unlinked_secrets": unlinked_secrets,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(UpdateResult {
|
||||
name: params.name.to_string(),
|
||||
folder: row.folder.clone(),
|
||||
entry_type: row.entry_type.clone(),
|
||||
add_tags: params.add_tags.to_vec(),
|
||||
remove_tags: params.remove_tags.to_vec(),
|
||||
meta_keys,
|
||||
remove_meta: remove_meta_keys,
|
||||
secret_keys,
|
||||
remove_secrets: remove_secret_keys,
|
||||
linked_secrets,
|
||||
unlinked_secrets,
|
||||
})
|
||||
}
|
||||
|
||||
/// Update non-sensitive entry columns by primary key (multi-tenant: `user_id` must match).
|
||||
/// Does not read or modify `secrets` rows.
|
||||
pub struct UpdateEntryFieldsByIdParams<'a> {
|
||||
pub folder: &'a str,
|
||||
pub entry_type: &'a str,
|
||||
pub name: &'a str,
|
||||
pub notes: &'a str,
|
||||
pub tags: &'a [String],
|
||||
pub metadata: &'a serde_json::Value,
|
||||
}
|
||||
|
||||
pub async fn update_fields_by_id(
|
||||
pool: &PgPool,
|
||||
entry_id: Uuid,
|
||||
user_id: Uuid,
|
||||
params: UpdateEntryFieldsByIdParams<'_>,
|
||||
) -> Result<()> {
|
||||
if params.folder.chars().count() > 128 {
|
||||
anyhow::bail!("folder must be at most 128 characters");
|
||||
}
|
||||
if params.entry_type.chars().count() > 64 {
|
||||
anyhow::bail!("type must be at most 64 characters");
|
||||
}
|
||||
if params.name.chars().count() > 256 {
|
||||
anyhow::bail!("name must be at most 256 characters");
|
||||
}
|
||||
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
let row: Option<EntryWriteRow> = sqlx::query_as(
|
||||
"SELECT id, version, folder, type, name, tags, metadata, notes FROM entries \
|
||||
WHERE id = $1 AND user_id = $2 FOR UPDATE",
|
||||
)
|
||||
.bind(entry_id)
|
||||
.bind(user_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
|
||||
let row = match row {
|
||||
Some(r) => r,
|
||||
None => {
|
||||
tx.rollback().await?;
|
||||
return Err(AppError::NotFoundEntry.into());
|
||||
}
|
||||
};
|
||||
|
||||
let history_metadata =
|
||||
match db::metadata_with_secret_snapshot(&mut tx, row.id, &row.metadata).await {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "failed to build secret snapshot for entry history");
|
||||
row.metadata.clone()
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = db::snapshot_entry_history(
|
||||
&mut tx,
|
||||
db::EntrySnapshotParams {
|
||||
entry_id: row.id,
|
||||
user_id: Some(user_id),
|
||||
folder: &row.folder,
|
||||
entry_type: &row.entry_type,
|
||||
name: &row.name,
|
||||
version: row.version,
|
||||
action: "update",
|
||||
tags: &row.tags,
|
||||
metadata: &history_metadata,
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to snapshot entry history before web update");
|
||||
}
|
||||
|
||||
let entry_type = params.entry_type.trim();
|
||||
|
||||
let res = sqlx::query(
|
||||
"UPDATE entries SET folder = $1, type = $2, name = $3, notes = $4, tags = $5, metadata = $6, \
|
||||
version = version + 1, updated_at = NOW() \
|
||||
WHERE id = $7 AND version = $8",
|
||||
)
|
||||
.bind(params.folder)
|
||||
.bind(entry_type)
|
||||
.bind(params.name)
|
||||
.bind(params.notes)
|
||||
.bind(params.tags)
|
||||
.bind(params.metadata)
|
||||
.bind(row.id)
|
||||
.bind(row.version)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
if let sqlx::Error::Database(ref d) = e
|
||||
&& d.code().as_deref() == Some("23505")
|
||||
{
|
||||
return AppError::ConflictEntryName {
|
||||
folder: params.folder.to_string(),
|
||||
name: params.name.to_string(),
|
||||
};
|
||||
}
|
||||
AppError::Internal(e.into())
|
||||
})?;
|
||||
|
||||
if res.rows_affected() == 0 {
|
||||
tx.rollback().await?;
|
||||
return Err(AppError::ConcurrentModification.into());
|
||||
}
|
||||
|
||||
crate::audit::log_tx(
|
||||
&mut tx,
|
||||
Some(user_id),
|
||||
"update",
|
||||
params.folder,
|
||||
entry_type,
|
||||
params.name,
|
||||
serde_json::json!({
|
||||
"source": "web",
|
||||
"entry_id": entry_id,
|
||||
"fields": ["folder", "type", "name", "notes", "tags", "metadata"],
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
349
crates/secrets-core/src/service/user.rs
Normal file
349
crates/secrets-core/src/service/user.rs
Normal file
@@ -0,0 +1,349 @@
|
||||
use anyhow::Result;
|
||||
use serde_json::Value;
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::models::{OauthAccount, User};
|
||||
|
||||
pub struct OAuthProfile {
|
||||
pub provider: String,
|
||||
pub provider_id: String,
|
||||
pub email: Option<String>,
|
||||
pub name: Option<String>,
|
||||
pub avatar_url: Option<String>,
|
||||
}
|
||||
|
||||
/// Find or create a user from an OAuth profile.
|
||||
/// Returns (user, is_new) where is_new indicates first-time registration.
|
||||
pub async fn find_or_create_user(pool: &PgPool, profile: OAuthProfile) -> Result<(User, bool)> {
|
||||
// Use a transaction with FOR UPDATE to prevent TOCTOU race conditions
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
// Check if this OAuth account already exists (with row lock)
|
||||
let existing: Option<OauthAccount> = sqlx::query_as(
|
||||
"SELECT id, user_id, provider, provider_id, email, name, avatar_url, created_at \
|
||||
FROM oauth_accounts WHERE provider = $1 AND provider_id = $2 FOR UPDATE",
|
||||
)
|
||||
.bind(&profile.provider)
|
||||
.bind(&profile.provider_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
|
||||
if let Some(oa) = existing {
|
||||
let user: User = sqlx::query_as(
|
||||
"SELECT id, email, name, avatar_url, key_salt, key_check, key_params, api_key, key_version, created_at, updated_at \
|
||||
FROM users WHERE id = $1",
|
||||
)
|
||||
.bind(oa.user_id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
return Ok((user, false));
|
||||
}
|
||||
|
||||
// New user — create records (no key yet; user sets passphrase on dashboard)
|
||||
let display_name = profile
|
||||
.name
|
||||
.clone()
|
||||
.unwrap_or_else(|| profile.email.clone().unwrap_or_else(|| "User".to_string()));
|
||||
|
||||
let user: User = sqlx::query_as(
|
||||
"INSERT INTO users (email, name, avatar_url) \
|
||||
VALUES ($1, $2, $3) \
|
||||
RETURNING id, email, name, avatar_url, key_salt, key_check, key_params, api_key, key_version, created_at, updated_at",
|
||||
)
|
||||
.bind(&profile.email)
|
||||
.bind(&display_name)
|
||||
.bind(&profile.avatar_url)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
|
||||
sqlx::query(
|
||||
"INSERT INTO oauth_accounts (user_id, provider, provider_id, email, name, avatar_url) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
)
|
||||
.bind(user.id)
|
||||
.bind(&profile.provider)
|
||||
.bind(&profile.provider_id)
|
||||
.bind(&profile.email)
|
||||
.bind(&profile.name)
|
||||
.bind(&profile.avatar_url)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
tx.commit().await?;
|
||||
|
||||
Ok((user, true))
|
||||
}
|
||||
|
||||
/// Re-encrypt all of a user's secrets from `old_key` to `new_key` and update the key metadata.
|
||||
///
|
||||
/// Runs entirely inside a single database transaction: if any secret fails to re-encrypt
|
||||
/// the whole operation is rolled back, leaving the database unchanged.
|
||||
pub async fn change_user_key(
|
||||
pool: &PgPool,
|
||||
user_id: Uuid,
|
||||
old_key: &[u8; 32],
|
||||
new_key: &[u8; 32],
|
||||
new_salt: &[u8],
|
||||
new_key_check: &[u8],
|
||||
new_key_params: &Value,
|
||||
) -> Result<()> {
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
let secrets: Vec<(uuid::Uuid, Vec<u8>)> =
|
||||
sqlx::query_as("SELECT id, encrypted FROM secrets WHERE user_id = $1 FOR UPDATE")
|
||||
.bind(user_id)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
|
||||
for (id, encrypted) in &secrets {
|
||||
let plaintext = crate::crypto::decrypt(old_key, encrypted)?;
|
||||
let new_encrypted = crate::crypto::encrypt(new_key, &plaintext)?;
|
||||
sqlx::query("UPDATE secrets SET encrypted = $1, updated_at = NOW() WHERE id = $2")
|
||||
.bind(&new_encrypted)
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE users SET key_salt = $1, key_check = $2, key_params = $3, \
|
||||
key_version = key_version + 1, updated_at = NOW() \
|
||||
WHERE id = $4",
|
||||
)
|
||||
.bind(new_salt)
|
||||
.bind(new_key_check)
|
||||
.bind(new_key_params)
|
||||
.bind(user_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Store the PBKDF2 salt, key_check, and params for a user's passphrase setup.
|
||||
pub async fn update_user_key_setup(
|
||||
pool: &PgPool,
|
||||
user_id: Uuid,
|
||||
key_salt: &[u8],
|
||||
key_check: &[u8],
|
||||
key_params: &Value,
|
||||
) -> Result<()> {
|
||||
sqlx::query(
|
||||
"UPDATE users SET key_salt = $1, key_check = $2, key_params = $3, updated_at = NOW() \
|
||||
WHERE id = $4",
|
||||
)
|
||||
.bind(key_salt)
|
||||
.bind(key_check)
|
||||
.bind(key_params)
|
||||
.bind(user_id)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Fetch a user by ID.
|
||||
pub async fn get_user_by_id(pool: &PgPool, user_id: Uuid) -> Result<Option<User>> {
|
||||
let user = sqlx::query_as(
|
||||
"SELECT id, email, name, avatar_url, key_salt, key_check, key_params, api_key, key_version, created_at, updated_at \
|
||||
FROM users WHERE id = $1",
|
||||
)
|
||||
.bind(user_id)
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
Ok(user)
|
||||
}
|
||||
|
||||
/// List all OAuth accounts linked to a user.
|
||||
pub async fn list_oauth_accounts(pool: &PgPool, user_id: Uuid) -> Result<Vec<OauthAccount>> {
|
||||
let accounts = sqlx::query_as(
|
||||
"SELECT id, user_id, provider, provider_id, email, name, avatar_url, created_at \
|
||||
FROM oauth_accounts WHERE user_id = $1 ORDER BY created_at",
|
||||
)
|
||||
.bind(user_id)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
Ok(accounts)
|
||||
}
|
||||
|
||||
/// Bind an additional OAuth account to an existing user.
|
||||
pub async fn bind_oauth_account(
|
||||
pool: &PgPool,
|
||||
user_id: Uuid,
|
||||
profile: OAuthProfile,
|
||||
) -> Result<OauthAccount> {
|
||||
// Use a transaction with FOR UPDATE to prevent TOCTOU race conditions
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
// Check if this provider_id is already linked to someone else (with row lock)
|
||||
let conflict: Option<(Uuid,)> = sqlx::query_as(
|
||||
"SELECT user_id FROM oauth_accounts WHERE provider = $1 AND provider_id = $2 FOR UPDATE",
|
||||
)
|
||||
.bind(&profile.provider)
|
||||
.bind(&profile.provider_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
|
||||
if let Some((existing_user_id,)) = conflict {
|
||||
if existing_user_id != user_id {
|
||||
anyhow::bail!(
|
||||
"This {} account is already linked to a different user",
|
||||
profile.provider
|
||||
);
|
||||
}
|
||||
anyhow::bail!(
|
||||
"This {} account is already linked to your account",
|
||||
profile.provider
|
||||
);
|
||||
}
|
||||
|
||||
let existing_provider_for_user: Option<(String,)> = sqlx::query_as(
|
||||
"SELECT provider_id FROM oauth_accounts WHERE user_id = $1 AND provider = $2 FOR UPDATE",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(&profile.provider)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
|
||||
if existing_provider_for_user.is_some() {
|
||||
anyhow::bail!(
|
||||
"You already linked a {} account. Unlink the other provider instead of binding multiple {} accounts.",
|
||||
profile.provider,
|
||||
profile.provider
|
||||
);
|
||||
}
|
||||
|
||||
let account: OauthAccount = sqlx::query_as(
|
||||
"INSERT INTO oauth_accounts (user_id, provider, provider_id, email, name, avatar_url) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6) \
|
||||
RETURNING id, user_id, provider, provider_id, email, name, avatar_url, created_at",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(&profile.provider)
|
||||
.bind(&profile.provider_id)
|
||||
.bind(&profile.email)
|
||||
.bind(&profile.name)
|
||||
.bind(&profile.avatar_url)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
|
||||
tx.commit().await?;
|
||||
Ok(account)
|
||||
}
|
||||
|
||||
/// Unbind an OAuth account. Ensures at least one remains and blocks unlinking the current login provider.
|
||||
pub async fn unbind_oauth_account(
|
||||
pool: &PgPool,
|
||||
user_id: Uuid,
|
||||
provider: &str,
|
||||
current_login_provider: Option<&str>,
|
||||
) -> Result<()> {
|
||||
if current_login_provider == Some(provider) {
|
||||
anyhow::bail!(
|
||||
"Cannot unlink the {} account you are currently using to sign in",
|
||||
provider
|
||||
);
|
||||
}
|
||||
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
let locked_accounts: Vec<(String,)> =
|
||||
sqlx::query_as("SELECT provider FROM oauth_accounts WHERE user_id = $1 FOR UPDATE")
|
||||
.bind(user_id)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
let count = locked_accounts.len();
|
||||
|
||||
if count <= 1 {
|
||||
anyhow::bail!("Cannot unbind the last OAuth account. Please link another account first.");
|
||||
}
|
||||
|
||||
sqlx::query("DELETE FROM oauth_accounts WHERE user_id = $1 AND provider = $2")
|
||||
.bind(user_id)
|
||||
.bind(provider)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
async fn maybe_test_pool() -> Option<PgPool> {
|
||||
let database_url = match std::env::var("SECRETS_DATABASE_URL") {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
eprintln!("skip user service tests: SECRETS_DATABASE_URL not set");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let pool = match sqlx::PgPool::connect(&database_url).await {
|
||||
Ok(pool) => pool,
|
||||
Err(e) => {
|
||||
eprintln!("skip user service tests: cannot connect to database: {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if let Err(e) = crate::db::migrate(&pool).await {
|
||||
eprintln!("skip user service tests: migrate failed: {e}");
|
||||
return None;
|
||||
}
|
||||
Some(pool)
|
||||
}
|
||||
|
||||
async fn cleanup_user_rows(pool: &PgPool, user_id: Uuid) -> Result<()> {
|
||||
sqlx::query("DELETE FROM oauth_accounts WHERE user_id = $1")
|
||||
.bind(user_id)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM users WHERE id = $1")
|
||||
.bind(user_id)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unbind_oauth_account_removes_only_requested_provider() -> Result<()> {
|
||||
let Some(pool) = maybe_test_pool().await else {
|
||||
return Ok(());
|
||||
};
|
||||
let user_id = Uuid::from_u128(rand::random());
|
||||
|
||||
cleanup_user_rows(&pool, user_id).await?;
|
||||
|
||||
sqlx::query("INSERT INTO users (id, name) VALUES ($1, '')")
|
||||
.bind(user_id)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO oauth_accounts (user_id, provider, provider_id, email, name, avatar_url) \
|
||||
VALUES ($1, 'google', $2, NULL, NULL, NULL), \
|
||||
($1, 'github', $3, NULL, NULL, NULL)",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(format!("google-{user_id}"))
|
||||
.bind(format!("github-{user_id}"))
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
|
||||
unbind_oauth_account(&pool, user_id, "github", Some("google")).await?;
|
||||
|
||||
let remaining: Vec<(String,)> = sqlx::query_as(
|
||||
"SELECT provider FROM oauth_accounts WHERE user_id = $1 ORDER BY provider",
|
||||
)
|
||||
.bind(user_id)
|
||||
.fetch_all(&pool)
|
||||
.await?;
|
||||
assert_eq!(remaining, vec![("google".to_string(),)]);
|
||||
|
||||
cleanup_user_rows(&pool, user_id).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
27
crates/secrets-core/src/service/util.rs
Normal file
27
crates/secrets-core/src/service/util.rs
Normal file
@@ -0,0 +1,27 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Returns a WHERE condition fragment for user scope and advances `idx` if `user_id` is Some.
|
||||
///
|
||||
/// - `Some(uid)` → `"user_id = $N"` with idx incremented.
|
||||
/// - `None` → `"user_id IS NULL"` with idx unchanged.
|
||||
///
|
||||
/// # Usage
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut idx = 1i32;
|
||||
/// let user_cond = user_scope_condition(user_id, &mut idx);
|
||||
/// // idx is now 2 if user_id is Some, still 1 if None
|
||||
/// let sql = format!("SELECT ... FROM entries WHERE {user_cond} AND name = ${idx}");
|
||||
/// let mut q = sqlx::query_as::<_, Row>(&sql);
|
||||
/// if let Some(uid) = user_id { q = q.bind(uid); }
|
||||
/// q = q.bind(name);
|
||||
/// ```
|
||||
pub fn user_scope_condition(user_id: Option<Uuid>, idx: &mut i32) -> String {
|
||||
if user_id.is_some() {
|
||||
let s = format!("user_id = ${}", *idx);
|
||||
*idx += 1;
|
||||
s
|
||||
} else {
|
||||
"user_id IS NULL".to_string()
|
||||
}
|
||||
}
|
||||
4
crates/secrets-core/src/taxonomy.rs
Normal file
4
crates/secrets-core/src/taxonomy.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
/// Canonical secret type options for UI dropdowns.
|
||||
pub const SECRET_TYPE_OPTIONS: &[&str] = &[
|
||||
"text", "password", "token", "api-key", "ssh-key", "url", "phone", "id-card",
|
||||
];
|
||||
47
crates/secrets-mcp/Cargo.toml
Normal file
47
crates/secrets-mcp/Cargo.toml
Normal file
@@ -0,0 +1,47 @@
|
||||
[package]
|
||||
name = "secrets-mcp"
|
||||
version = "0.5.10"
|
||||
edition.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "secrets-mcp"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
secrets-core = { path = "../secrets-core" }
|
||||
|
||||
# MCP
|
||||
rmcp = { version = "1", features = ["server", "macros", "transport-streamable-http-server", "schemars"] }
|
||||
|
||||
# Web framework
|
||||
axum = "0.8"
|
||||
axum-extra = { version = "0.10", features = ["typed-header"] }
|
||||
tower = "0.5"
|
||||
tower-http = { version = "0.6", features = ["cors", "trace", "limit"] }
|
||||
tower-sessions = "0.14"
|
||||
tower-sessions-sqlx-store-chrono = { version = "0.14", features = ["postgres"] }
|
||||
governor = { version = "0.10", features = ["std", "jitter"] }
|
||||
time = "0.3"
|
||||
|
||||
# OAuth (manual token exchange via reqwest)
|
||||
reqwest.workspace = true
|
||||
|
||||
# Templating - render templates manually to avoid integration crate issues
|
||||
askama = "0.13"
|
||||
|
||||
# Common
|
||||
anyhow.workspace = true
|
||||
chrono.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
rand.workspace = true
|
||||
sqlx.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
uuid.workspace = true
|
||||
dotenvy.workspace = true
|
||||
urlencoding = "2"
|
||||
schemars = "1"
|
||||
http = "1"
|
||||
url = "2"
|
||||
97
crates/secrets-mcp/src/auth.rs
Normal file
97
crates/secrets-mcp/src/auth.rs
Normal file
@@ -0,0 +1,97 @@
|
||||
use axum::{
|
||||
extract::{Request, State},
|
||||
http::StatusCode,
|
||||
middleware::Next,
|
||||
response::Response,
|
||||
};
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use secrets_core::service::api_key::validate_api_key;
|
||||
|
||||
use crate::client_ip;
|
||||
|
||||
/// Injected into request extensions after Bearer token validation.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AuthUser {
|
||||
pub user_id: Uuid,
|
||||
}
|
||||
|
||||
/// Axum middleware that validates Bearer API keys for the /mcp route.
|
||||
/// Passes all non-MCP paths through without authentication.
|
||||
pub async fn bearer_auth_middleware(
|
||||
State(pool): State<PgPool>,
|
||||
req: Request,
|
||||
next: Next,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let path = req.uri().path();
|
||||
let method = req.method().as_str();
|
||||
let client_ip = client_ip::extract_client_ip(&req);
|
||||
|
||||
// Only authenticate /mcp paths
|
||||
if !path.starts_with("/mcp") {
|
||||
return Ok(next.run(req).await);
|
||||
}
|
||||
|
||||
// Allow OPTIONS (CORS preflight) through
|
||||
if req.method() == axum::http::Method::OPTIONS {
|
||||
return Ok(next.run(req).await);
|
||||
}
|
||||
|
||||
let auth_header = req
|
||||
.headers()
|
||||
.get(axum::http::header::AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok());
|
||||
|
||||
let raw_key = match auth_header {
|
||||
Some(h) if h.starts_with("Bearer ") => h.trim_start_matches("Bearer ").trim(),
|
||||
Some(_) => {
|
||||
tracing::warn!(
|
||||
method,
|
||||
path,
|
||||
%client_ip,
|
||||
"invalid Authorization header format on /mcp (expected Bearer …)"
|
||||
);
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
None => {
|
||||
tracing::warn!(
|
||||
method,
|
||||
path,
|
||||
%client_ip,
|
||||
"missing Authorization header on /mcp"
|
||||
);
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
};
|
||||
|
||||
match validate_api_key(&pool, raw_key).await {
|
||||
Ok(Some(user_id)) => {
|
||||
tracing::debug!(?user_id, "api key authenticated");
|
||||
let mut req = req;
|
||||
req.extensions_mut().insert(AuthUser { user_id });
|
||||
Ok(next.run(req).await)
|
||||
}
|
||||
Ok(None) => {
|
||||
tracing::warn!(
|
||||
method,
|
||||
path,
|
||||
%client_ip,
|
||||
key_prefix = %&raw_key.chars().take(12).collect::<String>(),
|
||||
key_len = raw_key.len(),
|
||||
"invalid api key (not found in database — e.g. revoked key or DB was reset; update MCP client Bearer token)"
|
||||
);
|
||||
Err(StatusCode::UNAUTHORIZED)
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
method,
|
||||
path,
|
||||
%client_ip,
|
||||
error = %e,
|
||||
"api key validation error"
|
||||
);
|
||||
Err(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
}
|
||||
}
|
||||
}
|
||||
85
crates/secrets-mcp/src/client_ip.rs
Normal file
85
crates/secrets-mcp/src/client_ip.rs
Normal file
@@ -0,0 +1,85 @@
|
||||
use axum::extract::Request;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
|
||||
/// Extract the client IP from a request.
|
||||
///
|
||||
/// When the `TRUST_PROXY` environment variable is set to `1` or `true`, the
|
||||
/// `X-Forwarded-For` and `X-Real-IP` headers are consulted first, which is
|
||||
/// appropriate when the service runs behind a trusted reverse proxy (e.g.
|
||||
/// Caddy). Otherwise — or if those headers are absent/empty — the direct TCP
|
||||
/// connection address from `ConnectInfo` is used.
|
||||
///
|
||||
/// **Important**: only enable `TRUST_PROXY` when the application is guaranteed
|
||||
/// to receive traffic exclusively through a controlled reverse proxy. Enabling
|
||||
/// it on a directly-exposed port allows clients to spoof their IP address and
|
||||
/// bypass per-IP rate limiting.
|
||||
pub fn extract_client_ip(req: &Request) -> String {
|
||||
if trust_proxy_enabled() {
|
||||
if let Some(ip) = forwarded_for_ip(req.headers()) {
|
||||
return ip;
|
||||
}
|
||||
if let Some(ip) = real_ip(req.headers()) {
|
||||
return ip;
|
||||
}
|
||||
}
|
||||
|
||||
connect_info_ip(req).unwrap_or_else(|| "unknown".to_string())
|
||||
}
|
||||
|
||||
/// Extract the client IP from individual header map and socket address components.
|
||||
///
|
||||
/// This variant is used by handlers that receive headers and connect info as
|
||||
/// separate axum extractor parameters (e.g. OAuth callback handlers).
|
||||
/// The same `TRUST_PROXY` logic applies.
|
||||
pub fn extract_client_ip_parts(
|
||||
headers: &axum::http::HeaderMap,
|
||||
addr: std::net::SocketAddr,
|
||||
) -> String {
|
||||
if trust_proxy_enabled() {
|
||||
if let Some(ip) = forwarded_for_ip(headers) {
|
||||
return ip;
|
||||
}
|
||||
if let Some(ip) = real_ip(headers) {
|
||||
return ip;
|
||||
}
|
||||
}
|
||||
addr.ip().to_string()
|
||||
}
|
||||
|
||||
fn trust_proxy_enabled() -> bool {
|
||||
static CACHE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*CACHE.get_or_init(|| {
|
||||
matches!(
|
||||
std::env::var("TRUST_PROXY").as_deref(),
|
||||
Ok("1") | Ok("true") | Ok("yes")
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn forwarded_for_ip(headers: &axum::http::HeaderMap) -> Option<String> {
|
||||
let value = headers.get("x-forwarded-for")?.to_str().ok()?;
|
||||
let first = value.split(',').next()?.trim();
|
||||
if first.is_empty() {
|
||||
None
|
||||
} else {
|
||||
validate_ip(first)
|
||||
}
|
||||
}
|
||||
|
||||
fn real_ip(headers: &axum::http::HeaderMap) -> Option<String> {
|
||||
let value = headers.get("x-real-ip")?.to_str().ok()?;
|
||||
let ip = value.trim();
|
||||
if ip.is_empty() { None } else { validate_ip(ip) }
|
||||
}
|
||||
|
||||
/// Validate that a string is a valid IP address.
|
||||
/// Returns Some(ip) if valid, None otherwise.
|
||||
fn validate_ip(s: &str) -> Option<String> {
|
||||
s.parse::<IpAddr>().ok().map(|ip| ip.to_string())
|
||||
}
|
||||
|
||||
fn connect_info_ip(req: &Request) -> Option<String> {
|
||||
req.extensions()
|
||||
.get::<axum::extract::ConnectInfo<SocketAddr>>()
|
||||
.map(|c| c.0.ip().to_string())
|
||||
}
|
||||
54
crates/secrets-mcp/src/error.rs
Normal file
54
crates/secrets-mcp/src/error.rs
Normal file
@@ -0,0 +1,54 @@
|
||||
use secrets_core::error::AppError;
|
||||
|
||||
/// Map a structured `AppError` to an MCP protocol error.
|
||||
///
|
||||
/// This replaces the previous pattern of swallowing all errors into `-32603`.
|
||||
pub fn app_error_to_mcp(err: &AppError) -> rmcp::ErrorData {
|
||||
match err {
|
||||
AppError::ConflictSecretName { secret_name } => rmcp::ErrorData::invalid_request(
|
||||
format!(
|
||||
"A secret with the name '{secret_name}' already exists for your account. \
|
||||
Secret names must be unique per user."
|
||||
),
|
||||
None,
|
||||
),
|
||||
AppError::ConflictEntryName { folder, name } => rmcp::ErrorData::invalid_request(
|
||||
format!(
|
||||
"An entry with folder='{folder}' and name='{name}' already exists. \
|
||||
The combination of folder and name must be unique."
|
||||
),
|
||||
None,
|
||||
),
|
||||
AppError::NotFoundEntry => rmcp::ErrorData::invalid_request(
|
||||
"Entry not found. Use secrets_find to discover existing entries.",
|
||||
None,
|
||||
),
|
||||
AppError::NotFoundUser => rmcp::ErrorData::invalid_request("User not found.", None),
|
||||
AppError::NotFoundSecret => rmcp::ErrorData::invalid_request("Secret not found.", None),
|
||||
AppError::AuthenticationFailed => rmcp::ErrorData::invalid_request(
|
||||
"Authentication failed. Please check your API key or login credentials.",
|
||||
None,
|
||||
),
|
||||
AppError::Unauthorized => rmcp::ErrorData::invalid_request(
|
||||
"Unauthorized: you do not have permission to access this resource.",
|
||||
None,
|
||||
),
|
||||
AppError::Validation { message } => rmcp::ErrorData::invalid_request(message.clone(), None),
|
||||
AppError::ConcurrentModification => rmcp::ErrorData::invalid_request(
|
||||
"The entry was modified by another request. Please refresh and try again.",
|
||||
None,
|
||||
),
|
||||
AppError::DecryptionFailed => rmcp::ErrorData::invalid_request(
|
||||
"Decryption failed — the encryption key may be incorrect or does not match the data.",
|
||||
None,
|
||||
),
|
||||
AppError::EncryptionKeyNotSet => rmcp::ErrorData::invalid_request(
|
||||
"Encryption key not set. You must set a passphrase before using this feature.",
|
||||
None,
|
||||
),
|
||||
AppError::Internal(_) => rmcp::ErrorData::internal_error(
|
||||
"Request failed due to a server error. Check service logs if you need details.",
|
||||
None,
|
||||
),
|
||||
}
|
||||
}
|
||||
381
crates/secrets-mcp/src/logging.rs
Normal file
381
crates/secrets-mcp/src/logging.rs
Normal file
@@ -0,0 +1,381 @@
|
||||
use std::time::Instant;
|
||||
|
||||
use axum::{
|
||||
body::{Body, Bytes, to_bytes},
|
||||
extract::Request,
|
||||
http::{
|
||||
HeaderMap, Method, StatusCode,
|
||||
header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, USER_AGENT},
|
||||
},
|
||||
middleware::Next,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
|
||||
use crate::auth::AuthUser;
|
||||
|
||||
/// Axum middleware that logs structured info for every HTTP request.
|
||||
///
|
||||
/// All requests: method, path, status, latency_ms, client_ip, user_agent.
|
||||
/// POST /mcp requests: additionally parses JSON-RPC body for jsonrpc_method,
|
||||
/// tool_name, jsonrpc_id, mcp_session, batch_size, tool_args (non-sensitive
|
||||
/// arguments only), plus masked auth_key / enc_key fingerprints and user_id
|
||||
/// for diagnosing header forwarding issues.
|
||||
///
|
||||
/// Sensitive headers (Authorization, X-Encryption-Key) are never logged in
|
||||
/// full — only short fingerprints are emitted.
|
||||
pub async fn request_logging_middleware(req: Request, next: Next) -> Response {
|
||||
let method = req.method().clone();
|
||||
let path = req.uri().path().to_string();
|
||||
let ip = client_ip(&req);
|
||||
let ua = header_str(req.headers(), USER_AGENT);
|
||||
let content_len = header_str(req.headers(), CONTENT_LENGTH).and_then(|v| v.parse::<u64>().ok());
|
||||
let mcp_session = req
|
||||
.headers()
|
||||
.get("mcp-session-id")
|
||||
.or_else(|| req.headers().get("x-mcp-session"))
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(|s| s.to_string());
|
||||
|
||||
// Capture header fingerprints before consuming the request.
|
||||
let auth_key = mask_bearer(req.headers());
|
||||
let enc_key = mask_enc_key(req.headers());
|
||||
|
||||
let is_mcp_post = path.starts_with("/mcp") && method == Method::POST;
|
||||
let is_json = header_str(req.headers(), CONTENT_TYPE)
|
||||
.map(|ct| ct.contains("application/json"))
|
||||
.unwrap_or(false);
|
||||
|
||||
let start = Instant::now();
|
||||
|
||||
// For MCP JSON-RPC POST requests, buffer body to extract JSON-RPC metadata.
|
||||
// We cap at 512 KiB to avoid buffering large payloads.
|
||||
if is_mcp_post && is_json {
|
||||
let cap = content_len.unwrap_or(0);
|
||||
if cap <= 512 * 1024 {
|
||||
let (parts, body) = req.into_parts();
|
||||
// user_id is available after auth middleware has run (injected into extensions).
|
||||
let user_id = parts
|
||||
.extensions
|
||||
.get::<AuthUser>()
|
||||
.map(|a| a.user_id.to_string());
|
||||
match to_bytes(body, 512 * 1024).await {
|
||||
Ok(bytes) => {
|
||||
let rpc = parse_jsonrpc_meta(&bytes);
|
||||
let req = Request::from_parts(parts, Body::from(bytes));
|
||||
let resp = next.run(req).await;
|
||||
let status = resp.status().as_u16();
|
||||
let elapsed = start.elapsed().as_millis();
|
||||
log_mcp_request(
|
||||
&method,
|
||||
&path,
|
||||
status,
|
||||
elapsed,
|
||||
ip.as_deref(),
|
||||
ua.as_deref(),
|
||||
content_len,
|
||||
mcp_session.as_deref(),
|
||||
auth_key.as_deref(),
|
||||
&enc_key,
|
||||
user_id.as_deref(),
|
||||
&rpc,
|
||||
);
|
||||
return resp;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(path, error = %e, "failed to buffer MCP request body for logging");
|
||||
let elapsed = start.elapsed().as_millis();
|
||||
tracing::info!(
|
||||
method = method.as_str(),
|
||||
path,
|
||||
status = StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
|
||||
elapsed_ms = elapsed,
|
||||
client_ip = ip.as_deref(),
|
||||
ua = ua.as_deref(),
|
||||
content_length = content_len,
|
||||
mcp_session = mcp_session.as_deref(),
|
||||
auth_key = auth_key.as_deref(),
|
||||
enc_key = enc_key.as_str(),
|
||||
user_id = user_id.as_deref(),
|
||||
"mcp request",
|
||||
);
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"failed to read request body",
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let resp = next.run(req).await;
|
||||
let status = resp.status().as_u16();
|
||||
let elapsed = start.elapsed().as_millis();
|
||||
|
||||
// Known client probe patterns that legitimately 404 — downgrade to debug to
|
||||
// avoid noise in production logs. These are:
|
||||
// • GET /.well-known/* — OAuth/OIDC discovery by MCP clients (RFC 8414 / RFC 9728)
|
||||
// • GET /mcp → 404 — old SSE-transport compatibility probe by clients
|
||||
let is_expected_probe_404 = status == 404
|
||||
&& (path.starts_with("/.well-known/")
|
||||
|| (method == Method::GET && path.starts_with("/mcp")));
|
||||
|
||||
if is_expected_probe_404 {
|
||||
tracing::debug!(
|
||||
method = method.as_str(),
|
||||
path,
|
||||
status,
|
||||
elapsed_ms = elapsed,
|
||||
client_ip = ip.as_deref(),
|
||||
ua = ua.as_deref(),
|
||||
"probe request (not found — expected)",
|
||||
);
|
||||
} else {
|
||||
log_http_request(
|
||||
&method,
|
||||
&path,
|
||||
status,
|
||||
elapsed,
|
||||
ip.as_deref(),
|
||||
ua.as_deref(),
|
||||
content_len,
|
||||
);
|
||||
}
|
||||
|
||||
resp
|
||||
}
|
||||
|
||||
// ── Logging helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
fn log_http_request(
|
||||
method: &Method,
|
||||
path: &str,
|
||||
status: u16,
|
||||
elapsed_ms: u128,
|
||||
client_ip: Option<&str>,
|
||||
ua: Option<&str>,
|
||||
content_length: Option<u64>,
|
||||
) {
|
||||
tracing::info!(
|
||||
method = method.as_str(),
|
||||
path,
|
||||
status,
|
||||
elapsed_ms,
|
||||
client_ip,
|
||||
ua,
|
||||
content_length,
|
||||
"http request",
|
||||
);
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn log_mcp_request(
|
||||
method: &Method,
|
||||
path: &str,
|
||||
status: u16,
|
||||
elapsed_ms: u128,
|
||||
client_ip: Option<&str>,
|
||||
ua: Option<&str>,
|
||||
content_length: Option<u64>,
|
||||
mcp_session: Option<&str>,
|
||||
auth_key: Option<&str>,
|
||||
enc_key: &str,
|
||||
user_id: Option<&str>,
|
||||
rpc: &JsonRpcMeta,
|
||||
) {
|
||||
tracing::info!(
|
||||
method = method.as_str(),
|
||||
path,
|
||||
status,
|
||||
elapsed_ms,
|
||||
client_ip,
|
||||
ua,
|
||||
content_length,
|
||||
mcp_session,
|
||||
jsonrpc = rpc.rpc_method.as_deref(),
|
||||
tool = rpc.tool_name.as_deref(),
|
||||
jsonrpc_id = rpc.request_id.as_deref(),
|
||||
batch_size = rpc.batch_size,
|
||||
tool_args = rpc.tool_args.as_deref(),
|
||||
auth_key,
|
||||
enc_key,
|
||||
user_id,
|
||||
"mcp request",
|
||||
);
|
||||
}
|
||||
|
||||
// ── Sensitive header masking ──────────────────────────────────────────────────
|
||||
|
||||
/// Mask a Bearer token: emit only the first 12 characters followed by `…`.
|
||||
/// Returns `None` if the Authorization header is absent or not a Bearer token.
|
||||
/// Example: `sk_90c88844e4e5…`
|
||||
fn mask_bearer(headers: &HeaderMap) -> Option<String> {
|
||||
let val = headers.get(AUTHORIZATION)?.to_str().ok()?;
|
||||
let token = val.strip_prefix("Bearer ")?.trim();
|
||||
if token.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if token.len() > 12 {
|
||||
Some(format!("{}…", &token[..12]))
|
||||
} else {
|
||||
Some(token.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Fingerprint the X-Encryption-Key header.
|
||||
///
|
||||
/// Emits first 4 chars, last 4 chars, and raw byte length, e.g. `146b…5516(64)`.
|
||||
/// Returns `"absent"` when the header is missing. Reveals enough to confirm
|
||||
/// which key arrived and whether it was truncated or padded, without revealing
|
||||
/// the full value.
|
||||
fn mask_enc_key(headers: &HeaderMap) -> String {
|
||||
match headers
|
||||
.get("x-encryption-key")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
{
|
||||
Some(val) => {
|
||||
let raw_len = val.len();
|
||||
let t = val.trim();
|
||||
let len = t.len();
|
||||
if len >= 8 {
|
||||
let prefix = &t[..4];
|
||||
let suffix = &t[len - 4..];
|
||||
if raw_len != len {
|
||||
// Trailing/leading whitespace detected — extra diagnostic.
|
||||
format!("{prefix}…{suffix}({len}, raw={raw_len})")
|
||||
} else {
|
||||
format!("{prefix}…{suffix}({len})")
|
||||
}
|
||||
} else {
|
||||
format!("…({len})")
|
||||
}
|
||||
}
|
||||
None => "absent".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
// ── JSON-RPC body parsing ─────────────────────────────────────────────────────
|
||||
|
||||
/// Safe (non-sensitive) argument keys that may be included verbatim in logs.
|
||||
/// Keys NOT in this list (e.g. `secrets`, `secrets_obj`, `meta_obj`,
|
||||
/// `encryption_key`) are silently dropped.
|
||||
const SAFE_ARG_KEYS: &[&str] = &[
|
||||
"id",
|
||||
"name",
|
||||
"name_query",
|
||||
"folder",
|
||||
"type",
|
||||
"entry_type",
|
||||
"field",
|
||||
"query",
|
||||
"tags",
|
||||
"limit",
|
||||
"offset",
|
||||
"format",
|
||||
"dry_run",
|
||||
"prefix",
|
||||
];
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct JsonRpcMeta {
|
||||
request_id: Option<String>,
|
||||
rpc_method: Option<String>,
|
||||
tool_name: Option<String>,
|
||||
batch_size: Option<usize>,
|
||||
/// Non-sensitive tool call arguments for diagnostic logging.
|
||||
tool_args: Option<String>,
|
||||
}
|
||||
|
||||
fn parse_jsonrpc_meta(bytes: &Bytes) -> JsonRpcMeta {
|
||||
let Ok(value) = serde_json::from_slice::<serde_json::Value>(bytes) else {
|
||||
return JsonRpcMeta::default();
|
||||
};
|
||||
|
||||
if let Some(arr) = value.as_array() {
|
||||
// Batch request: summarise method(s) from first element only
|
||||
let first = arr.first().map(parse_single).unwrap_or_default();
|
||||
return JsonRpcMeta {
|
||||
batch_size: Some(arr.len()),
|
||||
..first
|
||||
};
|
||||
}
|
||||
|
||||
parse_single(&value)
|
||||
}
|
||||
|
||||
fn parse_single(value: &serde_json::Value) -> JsonRpcMeta {
|
||||
let request_id = value.get("id").and_then(json_to_string);
|
||||
let rpc_method = value
|
||||
.get("method")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
let tool_name = value
|
||||
.pointer("/params/name")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
let tool_args = extract_tool_args(value);
|
||||
|
||||
JsonRpcMeta {
|
||||
request_id,
|
||||
rpc_method,
|
||||
tool_name,
|
||||
batch_size: None,
|
||||
tool_args,
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract a compact summary of non-sensitive tool arguments for logging.
|
||||
/// Only keys listed in `SAFE_ARG_KEYS` are included.
|
||||
fn extract_tool_args(value: &serde_json::Value) -> Option<String> {
|
||||
let args = value.pointer("/params/arguments")?;
|
||||
let obj = args.as_object()?;
|
||||
let pairs: Vec<String> = obj
|
||||
.iter()
|
||||
.filter(|(k, v)| SAFE_ARG_KEYS.contains(&k.as_str()) && !v.is_null())
|
||||
.map(|(k, v)| format!("{}={}", k, summarize_value(v)))
|
||||
.collect();
|
||||
if pairs.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(pairs.join(" "))
|
||||
}
|
||||
}
|
||||
|
||||
/// Produce a short, log-safe representation of a JSON value.
|
||||
fn summarize_value(v: &serde_json::Value) -> String {
|
||||
match v {
|
||||
serde_json::Value::String(s) => {
|
||||
if s.len() > 64 {
|
||||
format!("\"{}…\"", &s[..64])
|
||||
} else {
|
||||
format!("\"{s}\"")
|
||||
}
|
||||
}
|
||||
serde_json::Value::Array(arr) => format!("[…{}]", arr.len()),
|
||||
serde_json::Value::Object(_) => "{…}".to_string(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn json_to_string(value: &serde_json::Value) -> Option<String> {
|
||||
match value {
|
||||
serde_json::Value::Null => None,
|
||||
serde_json::Value::String(s) => Some(s.clone()),
|
||||
serde_json::Value::Number(n) => Some(n.to_string()),
|
||||
serde_json::Value::Bool(b) => Some(b.to_string()),
|
||||
other => Some(other.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
// ── Header helpers ────────────────────────────────────────────────────────────
|
||||
|
||||
fn header_str(headers: &HeaderMap, name: impl axum::http::header::AsHeaderName) -> Option<String> {
|
||||
headers
|
||||
.get(name)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(|s| s.to_string())
|
||||
}
|
||||
|
||||
fn client_ip(req: &Request) -> Option<String> {
|
||||
crate::client_ip::extract_client_ip(req).into()
|
||||
}
|
||||
345
crates/secrets-mcp/src/main.rs
Normal file
345
crates/secrets-mcp/src/main.rs
Normal file
@@ -0,0 +1,345 @@
|
||||
mod auth;
|
||||
mod client_ip;
|
||||
mod error;
|
||||
mod logging;
|
||||
mod oauth;
|
||||
mod rate_limit;
|
||||
mod tools;
|
||||
mod validation;
|
||||
mod web;
|
||||
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use axum::Router;
|
||||
use rmcp::transport::streamable_http_server::{
|
||||
StreamableHttpService, session::local::LocalSessionManager,
|
||||
};
|
||||
use sqlx::PgPool;
|
||||
use tower_http::cors::{Any, CorsLayer};
|
||||
use tower_sessions::cookie::SameSite;
|
||||
use tower_sessions::session_store::ExpiredDeletion;
|
||||
use tower_sessions::{Expiry, SessionManagerLayer};
|
||||
use tower_sessions_sqlx_store_chrono::PostgresStore;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use tracing_subscriber::fmt::time::FormatTime;
|
||||
|
||||
use secrets_core::config::resolve_db_config;
|
||||
use secrets_core::db::{create_pool, migrate};
|
||||
|
||||
use crate::oauth::OAuthConfig;
|
||||
use crate::tools::SecretsService;
|
||||
|
||||
/// Shared application state injected into web routes and middleware.
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub pool: PgPool,
|
||||
pub google_config: Option<OAuthConfig>,
|
||||
pub base_url: String,
|
||||
pub http_client: reqwest::Client,
|
||||
}
|
||||
|
||||
fn load_env_var(name: &str) -> Option<String> {
|
||||
std::env::var(name).ok().filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
/// Pretty-print bind address in logs (`127.0.0.1` → `localhost`); actual socket bind unchanged.
|
||||
fn listen_addr_log_display(bind_addr: &str) -> String {
|
||||
bind_addr
|
||||
.strip_prefix("127.0.0.1:")
|
||||
.map(|port| format!("localhost:{port}"))
|
||||
.unwrap_or_else(|| bind_addr.to_string())
|
||||
}
|
||||
|
||||
fn load_oauth_config(prefix: &str, base_url: &str, path: &str) -> Option<OAuthConfig> {
|
||||
let client_id = load_env_var(&format!("{}_CLIENT_ID", prefix))?;
|
||||
let client_secret = load_env_var(&format!("{}_CLIENT_SECRET", prefix))?;
|
||||
Some(OAuthConfig {
|
||||
client_id,
|
||||
client_secret,
|
||||
redirect_uri: format!("{}{}", base_url, path),
|
||||
})
|
||||
}
|
||||
|
||||
/// Log line timestamps in the process local timezone (honors `TZ` / system zone).
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct LocalRfc3339Time;
|
||||
|
||||
impl FormatTime for LocalRfc3339Time {
|
||||
fn format_time(&self, w: &mut tracing_subscriber::fmt::format::Writer<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
w,
|
||||
"{}",
|
||||
chrono::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, false)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
// Load .env if present
|
||||
let _ = dotenvy::dotenv();
|
||||
|
||||
tracing_subscriber::fmt()
|
||||
.with_timer(LocalRfc3339Time)
|
||||
.with_env_filter(
|
||||
EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| "secrets_mcp=info,tower_http=info".into()),
|
||||
)
|
||||
.init();
|
||||
|
||||
// ── Database ──────────────────────────────────────────────────────────────
|
||||
let db_config = resolve_db_config("")
|
||||
.context("Database not configured. Set SECRETS_DATABASE_URL environment variable.")?;
|
||||
let pool = create_pool(&db_config)
|
||||
.await
|
||||
.context("failed to connect to database")?;
|
||||
migrate(&pool)
|
||||
.await
|
||||
.context("failed to run database migrations")?;
|
||||
tracing::info!("Database connected and migrated");
|
||||
|
||||
// ── Configuration ─────────────────────────────────────────────────────────
|
||||
let base_url = load_env_var("BASE_URL").unwrap_or_else(|| "http://localhost:9315".to_string());
|
||||
let bind_addr =
|
||||
load_env_var("SECRETS_MCP_BIND").unwrap_or_else(|| "127.0.0.1:9315".to_string());
|
||||
|
||||
// ── OAuth providers ───────────────────────────────────────────────────────
|
||||
let google_config = load_oauth_config("GOOGLE", &base_url, "/auth/google/callback");
|
||||
|
||||
if google_config.is_none() {
|
||||
tracing::warn!(
|
||||
"No OAuth providers configured. Set GOOGLE_CLIENT_ID/GOOGLE_CLIENT_SECRET to enable login."
|
||||
);
|
||||
}
|
||||
|
||||
// ── Session store (PostgreSQL-backed) ─────────────────────────────────────
|
||||
let session_store = PostgresStore::new(pool.clone());
|
||||
session_store
|
||||
.migrate()
|
||||
.await
|
||||
.context("failed to run session table migration")?;
|
||||
// Prune expired rows every hour; task is aborted when the server shuts down.
|
||||
let session_cleanup = tokio::spawn(
|
||||
session_store
|
||||
.clone()
|
||||
.continuously_delete_expired(tokio::time::Duration::from_secs(3600)),
|
||||
);
|
||||
// Strict would drop the session cookie on redirect from Google → our origin (cross-site nav).
|
||||
let session_layer = SessionManagerLayer::new(session_store)
|
||||
.with_secure(base_url.starts_with("https://"))
|
||||
.with_same_site(SameSite::Lax)
|
||||
.with_expiry(Expiry::OnInactivity(time::Duration::days(14)));
|
||||
|
||||
// ── App state ─────────────────────────────────────────────────────────────
|
||||
let app_state = AppState {
|
||||
pool: pool.clone(),
|
||||
google_config,
|
||||
base_url: base_url.clone(),
|
||||
http_client: reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(15))
|
||||
.build()
|
||||
.context("failed to build HTTP client")?,
|
||||
};
|
||||
|
||||
// ── MCP service ───────────────────────────────────────────────────────────
|
||||
let pool_for_mcp = pool.clone();
|
||||
|
||||
let mcp_service = StreamableHttpService::new(
|
||||
move || {
|
||||
let p = pool_for_mcp.clone();
|
||||
Ok(SecretsService::new(p))
|
||||
},
|
||||
LocalSessionManager::default().into(),
|
||||
Default::default(),
|
||||
);
|
||||
|
||||
// ── Router ────────────────────────────────────────────────────────────────
|
||||
// CORS: restrict origins in production, allow all in development
|
||||
let is_production = matches!(
|
||||
load_env_var("SECRETS_ENV")
|
||||
.as_deref()
|
||||
.map(|s| s.to_ascii_lowercase())
|
||||
.as_deref(),
|
||||
Some("prod" | "production")
|
||||
);
|
||||
|
||||
let cors = build_cors_layer(&base_url, is_production);
|
||||
|
||||
// Rate limiting
|
||||
let rate_limit_state = rate_limit::RateLimitState::new();
|
||||
let rate_limit_cleanup = rate_limit::spawn_cleanup_task(rate_limit_state.ip_limiter.clone());
|
||||
|
||||
let router = Router::new()
|
||||
.merge(web::web_router())
|
||||
.nest_service("/mcp", mcp_service)
|
||||
.layer(axum::middleware::from_fn(
|
||||
logging::request_logging_middleware,
|
||||
))
|
||||
.layer(axum::middleware::from_fn_with_state(
|
||||
pool,
|
||||
auth::bearer_auth_middleware,
|
||||
))
|
||||
.layer(axum::middleware::from_fn_with_state(
|
||||
rate_limit_state.clone(),
|
||||
rate_limit::rate_limit_middleware,
|
||||
))
|
||||
.layer(session_layer)
|
||||
.layer(cors)
|
||||
.layer(tower_http::limit::RequestBodyLimitLayer::new(
|
||||
10 * 1024 * 1024,
|
||||
))
|
||||
.with_state(app_state);
|
||||
|
||||
// ── Start server ──────────────────────────────────────────────────────────
|
||||
let listener = tokio::net::TcpListener::bind(&bind_addr)
|
||||
.await
|
||||
.with_context(|| format!("failed to bind to {}", bind_addr))?;
|
||||
|
||||
tracing::info!(
|
||||
"Secrets MCP Server listening on http://{}",
|
||||
listen_addr_log_display(&bind_addr)
|
||||
);
|
||||
tracing::info!("MCP endpoint: {}/mcp", base_url);
|
||||
|
||||
axum::serve(
|
||||
listener,
|
||||
router.into_make_service_with_connect_info::<SocketAddr>(),
|
||||
)
|
||||
.with_graceful_shutdown(shutdown_signal())
|
||||
.await
|
||||
.context("server error")?;
|
||||
|
||||
session_cleanup.abort();
|
||||
rate_limit_cleanup.abort();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn shutdown_signal() {
|
||||
let ctrl_c = tokio::signal::ctrl_c();
|
||||
|
||||
#[cfg(unix)]
|
||||
let terminate = async {
|
||||
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
|
||||
.expect("failed to install SIGTERM handler")
|
||||
.recv()
|
||||
.await;
|
||||
};
|
||||
|
||||
#[cfg(not(unix))]
|
||||
let terminate = std::future::pending::<()>();
|
||||
|
||||
tokio::select! {
|
||||
_ = ctrl_c => {},
|
||||
_ = terminate => {},
|
||||
}
|
||||
|
||||
tracing::info!("Shutting down gracefully...");
|
||||
}
|
||||
|
||||
/// Production CORS allowed headers.
|
||||
///
|
||||
/// When adding a new custom header to the MCP or Web API, this list must be
|
||||
/// updated accordingly — otherwise browsers will block the request during
|
||||
/// the CORS preflight check.
|
||||
fn production_allowed_headers() -> [axum::http::HeaderName; 5] {
|
||||
[
|
||||
axum::http::header::AUTHORIZATION,
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
axum::http::HeaderName::from_static("x-encryption-key"),
|
||||
axum::http::HeaderName::from_static("mcp-session-id"),
|
||||
axum::http::HeaderName::from_static("x-mcp-session"),
|
||||
]
|
||||
}
|
||||
|
||||
/// Production CORS allowed methods.
|
||||
///
|
||||
/// Keep this list explicit because tower-http rejects
|
||||
/// `allow_credentials(true)` together with `allow_methods(Any)`.
|
||||
fn production_allowed_methods() -> [axum::http::Method; 5] {
|
||||
[
|
||||
axum::http::Method::GET,
|
||||
axum::http::Method::POST,
|
||||
axum::http::Method::PATCH,
|
||||
axum::http::Method::DELETE,
|
||||
axum::http::Method::OPTIONS,
|
||||
]
|
||||
}
|
||||
|
||||
/// Build the CORS layer for the application.
|
||||
///
|
||||
/// In production mode the origin is restricted to the BASE_URL origin
|
||||
/// (scheme://host:port, path stripped) and credentials are allowed.
|
||||
/// `allow_headers` and `allow_methods` use explicit whitelists to avoid the
|
||||
/// tower-http restriction on `allow_credentials(true)` + wildcards.
|
||||
///
|
||||
/// In development mode all origins, methods and headers are allowed.
|
||||
fn build_cors_layer(base_url: &str, is_production: bool) -> CorsLayer {
|
||||
if is_production {
|
||||
let allowed_origin = if let Ok(parsed) = base_url.parse::<url::Url>() {
|
||||
let origin = parsed.origin().ascii_serialization();
|
||||
origin
|
||||
.parse::<axum::http::HeaderValue>()
|
||||
.unwrap_or_else(|_| panic!("invalid BASE_URL origin: {}", origin))
|
||||
} else {
|
||||
base_url
|
||||
.parse::<axum::http::HeaderValue>()
|
||||
.unwrap_or_else(|_| panic!("invalid BASE_URL: {}", base_url))
|
||||
};
|
||||
CorsLayer::new()
|
||||
.allow_origin(allowed_origin)
|
||||
.allow_methods(production_allowed_methods())
|
||||
.allow_headers(production_allowed_headers())
|
||||
.allow_credentials(true)
|
||||
} else {
|
||||
CorsLayer::new()
|
||||
.allow_origin(Any)
|
||||
.allow_methods(Any)
|
||||
.allow_headers(Any)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn production_cors_does_not_panic() {
|
||||
let layer = build_cors_layer("https://secrets.example.com/app", true);
|
||||
let _ = layer;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_cors_headers_include_all_required() {
|
||||
let headers = production_allowed_headers();
|
||||
let names: Vec<&str> = headers.iter().map(|h| h.as_str()).collect();
|
||||
assert!(names.contains(&"authorization"));
|
||||
assert!(names.contains(&"content-type"));
|
||||
assert!(names.contains(&"x-encryption-key"));
|
||||
assert!(names.contains(&"mcp-session-id"));
|
||||
assert!(names.contains(&"x-mcp-session"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_cors_methods_include_all_required() {
|
||||
let methods = production_allowed_methods();
|
||||
assert!(methods.contains(&axum::http::Method::GET));
|
||||
assert!(methods.contains(&axum::http::Method::POST));
|
||||
assert!(methods.contains(&axum::http::Method::PATCH));
|
||||
assert!(methods.contains(&axum::http::Method::DELETE));
|
||||
assert!(methods.contains(&axum::http::Method::OPTIONS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_cors_normalizes_base_url_with_path() {
|
||||
let url = url::Url::parse("https://secrets.example.com/secrets/app").unwrap();
|
||||
let origin = url.origin().ascii_serialization();
|
||||
assert_eq!(origin, "https://secrets.example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn development_cors_allows_everything() {
|
||||
let layer = build_cors_layer("http://localhost:9315", false);
|
||||
let _ = layer;
|
||||
}
|
||||
}
|
||||
66
crates/secrets-mcp/src/oauth/google.rs
Normal file
66
crates/secrets-mcp/src/oauth/google.rs
Normal file
@@ -0,0 +1,66 @@
|
||||
use anyhow::{Context, Result};
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::{OAuthConfig, OAuthUserInfo};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct TokenResponse {
|
||||
access_token: String,
|
||||
#[allow(dead_code)]
|
||||
token_type: String,
|
||||
#[allow(dead_code)]
|
||||
id_token: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct UserInfo {
|
||||
sub: String,
|
||||
email: Option<String>,
|
||||
name: Option<String>,
|
||||
picture: Option<String>,
|
||||
}
|
||||
|
||||
/// Exchange authorization code for tokens and fetch user profile.
|
||||
pub async fn exchange_code(
|
||||
client: &reqwest::Client,
|
||||
config: &OAuthConfig,
|
||||
code: &str,
|
||||
) -> Result<OAuthUserInfo> {
|
||||
let token_resp: TokenResponse = client
|
||||
.post("https://oauth2.googleapis.com/token")
|
||||
.form(&[
|
||||
("code", code),
|
||||
("client_id", &config.client_id),
|
||||
("client_secret", &config.client_secret),
|
||||
("redirect_uri", &config.redirect_uri),
|
||||
("grant_type", "authorization_code"),
|
||||
])
|
||||
.send()
|
||||
.await
|
||||
.context("failed to exchange Google code")?
|
||||
.error_for_status()
|
||||
.context("Google token endpoint error")?
|
||||
.json()
|
||||
.await
|
||||
.context("failed to parse Google token response")?;
|
||||
|
||||
let user: UserInfo = client
|
||||
.get("https://openidconnect.googleapis.com/v1/userinfo")
|
||||
.bearer_auth(&token_resp.access_token)
|
||||
.send()
|
||||
.await
|
||||
.context("failed to fetch Google userinfo")?
|
||||
.error_for_status()
|
||||
.context("Google userinfo endpoint error")?
|
||||
.json()
|
||||
.await
|
||||
.context("failed to parse Google userinfo")?;
|
||||
|
||||
Ok(OAuthUserInfo {
|
||||
provider: "google".to_string(),
|
||||
provider_id: user.sub,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
avatar_url: user.picture,
|
||||
})
|
||||
}
|
||||
45
crates/secrets-mcp/src/oauth/mod.rs
Normal file
45
crates/secrets-mcp/src/oauth/mod.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
pub mod google;
|
||||
pub mod wechat; // not yet implemented — placeholder for future WeChat integration
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Normalized OAuth user profile from any provider.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct OAuthUserInfo {
|
||||
pub provider: String,
|
||||
pub provider_id: String,
|
||||
pub email: Option<String>,
|
||||
pub name: Option<String>,
|
||||
pub avatar_url: Option<String>,
|
||||
}
|
||||
|
||||
/// OAuth provider configuration.
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct OAuthConfig {
|
||||
pub client_id: String,
|
||||
pub client_secret: String,
|
||||
pub redirect_uri: String,
|
||||
}
|
||||
|
||||
/// Build the Google authorization URL.
|
||||
pub fn google_auth_url(config: &OAuthConfig, state: &str) -> String {
|
||||
format!(
|
||||
"https://accounts.google.com/o/oauth2/v2/auth\
|
||||
?client_id={}\
|
||||
&redirect_uri={}\
|
||||
&response_type=code\
|
||||
&scope=openid%20email%20profile\
|
||||
&state={}\
|
||||
&access_type=offline",
|
||||
urlencoding::encode(&config.client_id),
|
||||
urlencoding::encode(&config.redirect_uri),
|
||||
urlencoding::encode(state),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn random_state() -> String {
|
||||
use rand::RngExt;
|
||||
let mut bytes = [0u8; 16];
|
||||
rand::rng().fill(&mut bytes);
|
||||
secrets_core::crypto::hex::encode_hex(&bytes)
|
||||
}
|
||||
18
crates/secrets-mcp/src/oauth/wechat.rs
Normal file
18
crates/secrets-mcp/src/oauth/wechat.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
use super::{OAuthConfig, OAuthUserInfo};
|
||||
/// WeChat OAuth — not yet implemented.
|
||||
///
|
||||
/// This module is a placeholder for future WeChat Open Platform integration.
|
||||
/// When ready, implement `exchange_code` following the non-standard WeChat OAuth 2.0 flow:
|
||||
/// - Token exchange uses a GET request (not POST)
|
||||
/// - Preferred user identifier is `unionid` (cross-app), falling back to `openid`
|
||||
/// - Docs: https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html
|
||||
use anyhow::{Result, bail};
|
||||
|
||||
#[allow(dead_code)] // Placeholder — implement when WeChat login is needed.
|
||||
pub async fn exchange_code(
|
||||
_client: &reqwest::Client,
|
||||
_config: &OAuthConfig,
|
||||
_code: &str,
|
||||
) -> Result<OAuthUserInfo> {
|
||||
bail!("WeChat login is not yet implemented")
|
||||
}
|
||||
160
crates/secrets-mcp/src/rate_limit.rs
Normal file
160
crates/secrets-mcp/src/rate_limit.rs
Normal file
@@ -0,0 +1,160 @@
|
||||
use std::num::NonZeroU32;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::{
|
||||
extract::{Request, State},
|
||||
http::{HeaderMap, HeaderValue, StatusCode},
|
||||
middleware::Next,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use governor::{
|
||||
Quota, RateLimiter,
|
||||
clock::{Clock, DefaultClock},
|
||||
state::{InMemoryState, NotKeyed, keyed::DashMapStateStore},
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::client_ip;
|
||||
|
||||
/// Per-IP rate limiter (keyed by client IP string)
|
||||
type IpRateLimiter = RateLimiter<String, DashMapStateStore<String>, DefaultClock>;
|
||||
|
||||
/// Global rate limiter (not keyed)
|
||||
type GlobalRateLimiter = RateLimiter<NotKeyed, InMemoryState, DefaultClock>;
|
||||
|
||||
/// Parse a u32 env value into NonZeroU32, logging a warning and falling back
|
||||
/// to the default if the value is zero.
|
||||
fn nz_or_log(value: u32, default: u32, name: &str) -> NonZeroU32 {
|
||||
NonZeroU32::new(value).unwrap_or_else(|| {
|
||||
tracing::warn!(
|
||||
configured = value,
|
||||
default,
|
||||
"{name} must be non-zero, using default"
|
||||
);
|
||||
NonZeroU32::new(default).unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RateLimitState {
|
||||
pub ip_limiter: Arc<IpRateLimiter>,
|
||||
pub global_limiter: Arc<GlobalRateLimiter>,
|
||||
}
|
||||
|
||||
impl RateLimitState {
|
||||
/// Create a new RateLimitState with default limits.
|
||||
///
|
||||
/// Default limits (can be overridden via environment variables):
|
||||
/// - Global: 100 req/s, burst 200
|
||||
/// - Per-IP: 20 req/s, burst 40
|
||||
pub fn new() -> Self {
|
||||
let global_rate = std::env::var("RATE_LIMIT_GLOBAL_PER_SECOND")
|
||||
.ok()
|
||||
.and_then(|v| v.parse::<u32>().ok())
|
||||
.unwrap_or(100);
|
||||
|
||||
let global_burst = std::env::var("RATE_LIMIT_GLOBAL_BURST")
|
||||
.ok()
|
||||
.and_then(|v| v.parse::<u32>().ok())
|
||||
.unwrap_or(200);
|
||||
|
||||
let ip_rate = std::env::var("RATE_LIMIT_IP_PER_SECOND")
|
||||
.ok()
|
||||
.and_then(|v| v.parse::<u32>().ok())
|
||||
.unwrap_or(20);
|
||||
|
||||
let ip_burst = std::env::var("RATE_LIMIT_IP_BURST")
|
||||
.ok()
|
||||
.and_then(|v| v.parse::<u32>().ok())
|
||||
.unwrap_or(40);
|
||||
|
||||
let global_rate_nz = nz_or_log(global_rate, 100, "RATE_LIMIT_GLOBAL_PER_SECOND");
|
||||
let global_burst_nz = nz_or_log(global_burst, 200, "RATE_LIMIT_GLOBAL_BURST");
|
||||
let ip_rate_nz = nz_or_log(ip_rate, 20, "RATE_LIMIT_IP_PER_SECOND");
|
||||
let ip_burst_nz = nz_or_log(ip_burst, 40, "RATE_LIMIT_IP_BURST");
|
||||
|
||||
let global_quota = Quota::per_second(global_rate_nz).allow_burst(global_burst_nz);
|
||||
let ip_quota = Quota::per_second(ip_rate_nz).allow_burst(ip_burst_nz);
|
||||
|
||||
tracing::info!(
|
||||
global_rate = global_rate_nz.get(),
|
||||
global_burst = global_burst_nz.get(),
|
||||
ip_rate = ip_rate_nz.get(),
|
||||
ip_burst = ip_burst_nz.get(),
|
||||
"rate limiter initialized"
|
||||
);
|
||||
|
||||
Self {
|
||||
global_limiter: Arc::new(RateLimiter::direct(global_quota)),
|
||||
ip_limiter: Arc::new(RateLimiter::dashmap(ip_quota)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rate limiting middleware function.
|
||||
///
|
||||
/// Checks both global and per-IP rate limits before allowing the request through.
|
||||
/// Returns 429 Too Many Requests if either limit is exceeded.
|
||||
pub async fn rate_limit_middleware(
|
||||
State(rl): State<RateLimitState>,
|
||||
req: Request,
|
||||
next: Next,
|
||||
) -> Result<Response, Response> {
|
||||
// Check global rate limit first
|
||||
if let Err(negative) = rl.global_limiter.check() {
|
||||
let retry_after = negative.wait_time_from(DefaultClock::default().now());
|
||||
tracing::warn!(
|
||||
retry_after_secs = retry_after.as_secs(),
|
||||
"global rate limit exceeded"
|
||||
);
|
||||
return Err(too_many_requests_response(Some(retry_after)));
|
||||
}
|
||||
|
||||
// Check per-IP rate limit
|
||||
let key = client_ip::extract_client_ip(&req);
|
||||
if let Err(negative) = rl.ip_limiter.check_key(&key) {
|
||||
let retry_after = negative.wait_time_from(DefaultClock::default().now());
|
||||
tracing::warn!(
|
||||
client_ip = %key,
|
||||
retry_after_secs = retry_after.as_secs(),
|
||||
"per-IP rate limit exceeded"
|
||||
);
|
||||
return Err(too_many_requests_response(Some(retry_after)));
|
||||
}
|
||||
|
||||
Ok(next.run(req).await)
|
||||
}
|
||||
|
||||
/// Start a background task to clean up expired rate limiter entries.
|
||||
///
|
||||
/// This should be called once during application startup.
|
||||
/// The task runs every 60 seconds and will be aborted on shutdown.
|
||||
pub fn spawn_cleanup_task(ip_limiter: Arc<IpRateLimiter>) -> tokio::task::JoinHandle<()> {
|
||||
tokio::spawn(async move {
|
||||
let mut interval = tokio::time::interval(Duration::from_secs(60));
|
||||
loop {
|
||||
interval.tick().await;
|
||||
ip_limiter.retain_recent();
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Create a 429 Too Many Requests response.
|
||||
fn too_many_requests_response(retry_after: Option<Duration>) -> Response {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("Content-Type", HeaderValue::from_static("application/json"));
|
||||
|
||||
if let Some(duration) = retry_after {
|
||||
let secs = duration.as_secs().max(1);
|
||||
if let Ok(value) = HeaderValue::from_str(&secs.to_string()) {
|
||||
headers.insert("Retry-After", value);
|
||||
}
|
||||
}
|
||||
|
||||
let body = json!({
|
||||
"error": "Too many requests, please try again later"
|
||||
});
|
||||
|
||||
(StatusCode::TOO_MANY_REQUESTS, headers, body.to_string()).into_response()
|
||||
}
|
||||
1802
crates/secrets-mcp/src/tools.rs
Normal file
1802
crates/secrets-mcp/src/tools.rs
Normal file
File diff suppressed because it is too large
Load Diff
149
crates/secrets-mcp/src/validation.rs
Normal file
149
crates/secrets-mcp/src/validation.rs
Normal file
@@ -0,0 +1,149 @@
|
||||
/// Validation constants for input field lengths.
|
||||
pub const MAX_NAME_LENGTH: usize = 256;
|
||||
pub const MAX_FOLDER_LENGTH: usize = 128;
|
||||
pub const MAX_ENTRY_TYPE_LENGTH: usize = 64;
|
||||
pub const MAX_NOTES_LENGTH: usize = 10000;
|
||||
pub const MAX_TAG_LENGTH: usize = 64;
|
||||
pub const MAX_TAG_COUNT: usize = 50;
|
||||
pub const MAX_META_KEY_LENGTH: usize = 128;
|
||||
pub const MAX_META_VALUE_LENGTH: usize = 4096;
|
||||
pub const MAX_META_COUNT: usize = 100;
|
||||
|
||||
/// Validate input field lengths for MCP tools.
|
||||
///
|
||||
/// Returns an error if any field exceeds its maximum length.
|
||||
pub fn validate_input_lengths(
|
||||
name: &str,
|
||||
folder: Option<&str>,
|
||||
entry_type: Option<&str>,
|
||||
notes: Option<&str>,
|
||||
) -> Result<(), rmcp::ErrorData> {
|
||||
if name.chars().count() > MAX_NAME_LENGTH {
|
||||
return Err(rmcp::ErrorData::invalid_params(
|
||||
format!("name must be at most {} characters", MAX_NAME_LENGTH),
|
||||
None,
|
||||
));
|
||||
}
|
||||
if let Some(folder) = folder
|
||||
&& folder.chars().count() > MAX_FOLDER_LENGTH
|
||||
{
|
||||
return Err(rmcp::ErrorData::invalid_params(
|
||||
format!("folder must be at most {} characters", MAX_FOLDER_LENGTH),
|
||||
None,
|
||||
));
|
||||
}
|
||||
if let Some(entry_type) = entry_type
|
||||
&& entry_type.chars().count() > MAX_ENTRY_TYPE_LENGTH
|
||||
{
|
||||
return Err(rmcp::ErrorData::invalid_params(
|
||||
format!("type must be at most {} characters", MAX_ENTRY_TYPE_LENGTH),
|
||||
None,
|
||||
));
|
||||
}
|
||||
if let Some(notes) = notes
|
||||
&& notes.chars().count() > MAX_NOTES_LENGTH
|
||||
{
|
||||
return Err(rmcp::ErrorData::invalid_params(
|
||||
format!("notes must be at most {} characters", MAX_NOTES_LENGTH),
|
||||
None,
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate the tags list.
|
||||
///
|
||||
/// Checks total count and per-tag character length.
|
||||
pub fn validate_tags(tags: &[String]) -> Result<(), rmcp::ErrorData> {
|
||||
if tags.len() > MAX_TAG_COUNT {
|
||||
return Err(rmcp::ErrorData::invalid_params(
|
||||
format!("at most {} tags are allowed", MAX_TAG_COUNT),
|
||||
None,
|
||||
));
|
||||
}
|
||||
for tag in tags {
|
||||
if tag.chars().count() > MAX_TAG_LENGTH {
|
||||
return Err(rmcp::ErrorData::invalid_params(
|
||||
format!(
|
||||
"tag '{}' exceeds the maximum length of {} characters",
|
||||
tag, MAX_TAG_LENGTH
|
||||
),
|
||||
None,
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate metadata KV strings (key=value / key:=json format).
|
||||
///
|
||||
/// Checks total count and per-key/per-value character lengths.
|
||||
/// This is a best-effort check on the raw KV strings before parsing;
|
||||
/// keys containing `:` path separators are checked as a whole.
|
||||
pub fn validate_meta_entries(entries: &[String]) -> Result<(), rmcp::ErrorData> {
|
||||
if entries.len() > MAX_META_COUNT {
|
||||
return Err(rmcp::ErrorData::invalid_params(
|
||||
format!("at most {} metadata entries are allowed", MAX_META_COUNT),
|
||||
None,
|
||||
));
|
||||
}
|
||||
for entry in entries {
|
||||
// key:=json — check both key and JSON value length
|
||||
if let Some((key, value)) = entry.split_once(":=") {
|
||||
if key.chars().count() > MAX_META_KEY_LENGTH {
|
||||
return Err(rmcp::ErrorData::invalid_params(
|
||||
format!(
|
||||
"metadata key '{}' exceeds the maximum length of {} characters",
|
||||
key, MAX_META_KEY_LENGTH
|
||||
),
|
||||
None,
|
||||
));
|
||||
}
|
||||
if value.chars().count() > MAX_META_VALUE_LENGTH {
|
||||
return Err(rmcp::ErrorData::invalid_params(
|
||||
format!(
|
||||
"metadata JSON value for key '{}' exceeds the maximum length of {} characters",
|
||||
key, MAX_META_VALUE_LENGTH
|
||||
),
|
||||
None,
|
||||
));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// key=value or key@path
|
||||
if let Some((key, value)) = entry.split_once('=') {
|
||||
if key.chars().count() > MAX_META_KEY_LENGTH {
|
||||
return Err(rmcp::ErrorData::invalid_params(
|
||||
format!(
|
||||
"metadata key '{}' exceeds the maximum length of {} characters",
|
||||
key, MAX_META_KEY_LENGTH
|
||||
),
|
||||
None,
|
||||
));
|
||||
}
|
||||
if value.chars().count() > MAX_META_VALUE_LENGTH {
|
||||
return Err(rmcp::ErrorData::invalid_params(
|
||||
format!(
|
||||
"metadata value for key '{}' exceeds the maximum length of {} characters",
|
||||
key, MAX_META_VALUE_LENGTH
|
||||
),
|
||||
None,
|
||||
));
|
||||
}
|
||||
} else {
|
||||
// Fallback: entry without = or := — check total length
|
||||
let max_total = MAX_META_KEY_LENGTH + MAX_META_VALUE_LENGTH;
|
||||
if entry.chars().count() > max_total {
|
||||
let preview = entry.chars().take(50).collect::<String>();
|
||||
return Err(rmcp::ErrorData::invalid_params(
|
||||
format!(
|
||||
"metadata entry '{}' exceeds the maximum length of {} characters",
|
||||
preview, max_total
|
||||
),
|
||||
None,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
307
crates/secrets-mcp/src/web/account.rs
Normal file
307
crates/secrets-mcp/src/web/account.rs
Normal file
@@ -0,0 +1,307 @@
|
||||
use askama::Template;
|
||||
use axum::{Json, extract::State, http::StatusCode, response::Response};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tower_sessions::Session;
|
||||
|
||||
use secrets_core::crypto::hex;
|
||||
use secrets_core::service::{
|
||||
api_key::{ensure_api_key, regenerate_api_key},
|
||||
user::{change_user_key, get_user_by_id, update_user_key_setup},
|
||||
};
|
||||
|
||||
use crate::AppState;
|
||||
|
||||
use super::{SESSION_KEY_VERSION, current_user_id, render_template, require_valid_user};
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "dashboard.html")]
|
||||
struct DashboardTemplate {
|
||||
user_name: String,
|
||||
user_email: String,
|
||||
has_passphrase: bool,
|
||||
base_url: String,
|
||||
version: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(super) struct KeySaltResponse {
|
||||
has_passphrase: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
salt: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
key_check: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
params: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(super) struct KeySetupRequest {
|
||||
/// Hex-encoded 32-byte random salt
|
||||
salt: String,
|
||||
/// Hex-encoded AES-256-GCM encryption of "secrets-mcp-key-check" with the derived key
|
||||
key_check: String,
|
||||
/// Key derivation parameters, e.g. {"alg":"pbkdf2-sha256","iterations":600000}
|
||||
params: serde_json::Value,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(super) struct KeySetupResponse {
|
||||
ok: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(super) struct KeyChangeRequest {
|
||||
/// Old derived key as 64-char hex — used to decrypt existing secrets
|
||||
old_key: String,
|
||||
/// New derived key as 64-char hex — used to re-encrypt secrets
|
||||
new_key: String,
|
||||
/// New 32-byte hex salt
|
||||
salt: String,
|
||||
/// New key_check: AES-256-GCM of KEY_CHECK_PLAINTEXT with the new key (hex)
|
||||
key_check: String,
|
||||
/// New key derivation parameters
|
||||
params: serde_json::Value,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(super) struct ApiKeyResponse {
|
||||
api_key: String,
|
||||
}
|
||||
|
||||
pub(super) async fn dashboard(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let user = match require_valid_user(&state.pool, &session, "dashboard").await {
|
||||
Ok(u) => u,
|
||||
Err(r) => return Ok(r),
|
||||
};
|
||||
|
||||
let tmpl = DashboardTemplate {
|
||||
user_name: user.name.clone(),
|
||||
user_email: user.email.clone().unwrap_or_default(),
|
||||
has_passphrase: user.key_salt.is_some(),
|
||||
base_url: state.base_url.clone(),
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
};
|
||||
|
||||
render_template(tmpl)
|
||||
}
|
||||
|
||||
pub(super) async fn api_key_salt(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
) -> Result<Json<KeySaltResponse>, StatusCode> {
|
||||
let user_id = current_user_id(&session)
|
||||
.await
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
let user = get_user_by_id(&state.pool, user_id)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, %user_id, "failed to load user for key-salt API");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
if user.key_salt.is_none() {
|
||||
return Ok(Json(KeySaltResponse {
|
||||
has_passphrase: false,
|
||||
salt: None,
|
||||
key_check: None,
|
||||
params: None,
|
||||
}));
|
||||
}
|
||||
|
||||
Ok(Json(KeySaltResponse {
|
||||
has_passphrase: true,
|
||||
salt: user.key_salt.as_deref().map(hex::encode_hex),
|
||||
key_check: user.key_check.as_deref().map(hex::encode_hex),
|
||||
params: user.key_params,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) async fn api_key_setup(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
Json(body): Json<KeySetupRequest>,
|
||||
) -> Result<Json<KeySetupResponse>, StatusCode> {
|
||||
let user_id = current_user_id(&session)
|
||||
.await
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
// Guard: if a passphrase is already configured, reject and direct to /api/key-change
|
||||
let user = get_user_by_id(&state.pool, user_id)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, %user_id, "failed to load user for key-setup guard");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
if user.key_salt.is_some() {
|
||||
tracing::warn!(%user_id, "key-setup called but passphrase already configured; use /api/key-change");
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
|
||||
let salt = hex::decode_hex(&body.salt).map_err(|e| {
|
||||
tracing::warn!(error = %e, "invalid hex in key-setup salt");
|
||||
StatusCode::BAD_REQUEST
|
||||
})?;
|
||||
let key_check = hex::decode_hex(&body.key_check).map_err(|e| {
|
||||
tracing::warn!(error = %e, "invalid hex in key-setup key_check");
|
||||
StatusCode::BAD_REQUEST
|
||||
})?;
|
||||
|
||||
if salt.len() != 32 {
|
||||
tracing::warn!(salt_len = salt.len(), "key-setup salt must be 32 bytes");
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
update_user_key_setup(&state.pool, user_id, &salt, &key_check, &body.params)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to update key setup");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
Ok(Json(KeySetupResponse { ok: true }))
|
||||
}
|
||||
|
||||
// ── Change passphrase (re-encrypts all secrets) ───────────────────────────────
|
||||
|
||||
pub(super) async fn api_key_change(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
Json(body): Json<KeyChangeRequest>,
|
||||
) -> Result<Json<KeySetupResponse>, StatusCode> {
|
||||
let user_id = current_user_id(&session)
|
||||
.await
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
let user = get_user_by_id(&state.pool, user_id)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, %user_id, "failed to load user for key-change");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
// Must have an existing passphrase to change
|
||||
let existing_key_check = user.key_check.ok_or_else(|| {
|
||||
tracing::warn!(%user_id, "key-change called but no passphrase configured; use /api/key-setup");
|
||||
StatusCode::BAD_REQUEST
|
||||
})?;
|
||||
|
||||
// Validate and decode old key
|
||||
let old_key_bytes = secrets_core::crypto::extract_key_from_hex(&body.old_key).map_err(|e| {
|
||||
tracing::warn!(error = %e, "invalid old_key hex in key-change");
|
||||
StatusCode::BAD_REQUEST
|
||||
})?;
|
||||
|
||||
// Verify old_key against the stored key_check
|
||||
let plaintext = secrets_core::crypto::decrypt(&old_key_bytes, &existing_key_check).map_err(|_| {
|
||||
tracing::warn!(%user_id, "key-change rejected: old_key does not match stored key_check");
|
||||
StatusCode::UNAUTHORIZED
|
||||
})?;
|
||||
if plaintext != b"secrets-mcp-key-check" {
|
||||
tracing::warn!(%user_id, "key-change rejected: decrypted key_check content mismatch");
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
// Validate and decode new key
|
||||
let new_key_bytes = secrets_core::crypto::extract_key_from_hex(&body.new_key).map_err(|e| {
|
||||
tracing::warn!(error = %e, "invalid new_key hex in key-change");
|
||||
StatusCode::BAD_REQUEST
|
||||
})?;
|
||||
|
||||
// Decode new salt and key_check
|
||||
let new_salt = hex::decode_hex(&body.salt).map_err(|e| {
|
||||
tracing::warn!(error = %e, "invalid hex in key-change salt");
|
||||
StatusCode::BAD_REQUEST
|
||||
})?;
|
||||
if new_salt.len() != 32 {
|
||||
tracing::warn!(
|
||||
salt_len = new_salt.len(),
|
||||
"key-change salt must be 32 bytes"
|
||||
);
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
let new_key_check = hex::decode_hex(&body.key_check).map_err(|e| {
|
||||
tracing::warn!(error = %e, "invalid hex in key-change key_check");
|
||||
StatusCode::BAD_REQUEST
|
||||
})?;
|
||||
|
||||
change_user_key(
|
||||
&state.pool,
|
||||
user_id,
|
||||
&old_key_bytes,
|
||||
&new_key_bytes,
|
||||
&new_salt,
|
||||
&new_key_check,
|
||||
&body.params,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, %user_id, "failed to change user key");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
// Refresh the session's key_version so the current session is not immediately
|
||||
// invalidated by require_valid_user on the next page load.
|
||||
match get_user_by_id(&state.pool, user_id).await {
|
||||
Ok(Some(updated_user)) => {
|
||||
if let Err(e) = session
|
||||
.insert(SESSION_KEY_VERSION, updated_user.key_version)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, %user_id, "failed to update key_version in session after key change");
|
||||
}
|
||||
}
|
||||
Ok(None) => {
|
||||
tracing::warn!(%user_id, "user not found after key change; session not updated");
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, %user_id, "failed to reload user after key change; session not updated");
|
||||
}
|
||||
}
|
||||
|
||||
tracing::info!(%user_id, secrets_count = "(see service log)", "passphrase changed and secrets re-encrypted");
|
||||
Ok(Json(KeySetupResponse { ok: true }))
|
||||
}
|
||||
|
||||
// ── API Key management ────────────────────────────────────────────────────────
|
||||
|
||||
pub(super) async fn api_apikey_get(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
) -> Result<Json<ApiKeyResponse>, StatusCode> {
|
||||
let user_id = current_user_id(&session)
|
||||
.await
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
let api_key = ensure_api_key(&state.pool, user_id).await.map_err(|e| {
|
||||
tracing::error!(error = %e, %user_id, "ensure_api_key failed");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
Ok(Json(ApiKeyResponse { api_key }))
|
||||
}
|
||||
|
||||
pub(super) async fn api_apikey_regenerate(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
) -> Result<Json<ApiKeyResponse>, StatusCode> {
|
||||
let user_id = current_user_id(&session)
|
||||
.await
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
let api_key = regenerate_api_key(&state.pool, user_id)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, %user_id, "regenerate_api_key failed");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
Ok(Json(ApiKeyResponse { api_key }))
|
||||
}
|
||||
73
crates/secrets-mcp/src/web/assets.rs
Normal file
73
crates/secrets-mcp/src/web/assets.rs
Normal file
@@ -0,0 +1,73 @@
|
||||
use axum::{
|
||||
body::Body,
|
||||
extract::State,
|
||||
http::{StatusCode, header},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
|
||||
use crate::AppState;
|
||||
|
||||
pub(super) fn text_asset_response(content: &'static str, content_type: &'static str) -> Response {
|
||||
Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(header::CONTENT_TYPE, content_type)
|
||||
.header(header::CACHE_CONTROL, "public, max-age=86400")
|
||||
.body(Body::from(content))
|
||||
.expect("text asset response")
|
||||
}
|
||||
|
||||
pub(super) async fn robots_txt() -> Response {
|
||||
text_asset_response(
|
||||
include_str!("../../static/robots.txt"),
|
||||
"text/plain; charset=utf-8",
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) async fn llms_txt() -> Response {
|
||||
text_asset_response(
|
||||
include_str!("../../static/llms.txt"),
|
||||
"text/markdown; charset=utf-8",
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) async fn ai_txt() -> Response {
|
||||
llms_txt().await
|
||||
}
|
||||
|
||||
pub(super) async fn i18n_js() -> Response {
|
||||
text_asset_response(
|
||||
include_str!("../../templates/i18n.js"),
|
||||
"application/javascript; charset=utf-8",
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) async fn favicon_svg() -> Response {
|
||||
Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(header::CONTENT_TYPE, "image/svg+xml")
|
||||
.header(header::CACHE_CONTROL, "public, max-age=86400")
|
||||
.body(Body::from(include_str!("../../static/favicon.svg")))
|
||||
.expect("favicon response")
|
||||
}
|
||||
|
||||
/// RFC 9728 — OAuth 2.0 Protected Resource Metadata.
|
||||
///
|
||||
/// Advertises that this server accepts Bearer tokens in the `Authorization`
|
||||
/// header. We deliberately omit `authorization_servers` because this service
|
||||
/// issues its own API keys (no external OAuth AS is involved). MCP clients
|
||||
/// that probe this endpoint will see the resource identifier and stop looking
|
||||
/// for a delegated OAuth flow.
|
||||
pub(super) async fn oauth_protected_resource_metadata(
|
||||
State(state): State<AppState>,
|
||||
) -> impl IntoResponse {
|
||||
let body = serde_json::json!({
|
||||
"resource": state.base_url,
|
||||
"bearer_methods_supported": ["header"],
|
||||
"resource_documentation": format!("{}/dashboard", state.base_url),
|
||||
});
|
||||
(
|
||||
StatusCode::OK,
|
||||
[(header::CONTENT_TYPE, "application/json")],
|
||||
axum::Json(body),
|
||||
)
|
||||
}
|
||||
104
crates/secrets-mcp/src/web/audit.rs
Normal file
104
crates/secrets-mcp/src/web/audit.rs
Normal file
@@ -0,0 +1,104 @@
|
||||
use askama::Template;
|
||||
use axum::{
|
||||
extract::{Query, State},
|
||||
http::StatusCode,
|
||||
response::Response,
|
||||
};
|
||||
use chrono::SecondsFormat;
|
||||
use serde::Deserialize;
|
||||
use tower_sessions::Session;
|
||||
|
||||
use crate::AppState;
|
||||
|
||||
use super::{AUDIT_PAGE_LIMIT, paginate, render_template, require_valid_user};
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "audit.html")]
|
||||
struct AuditPageTemplate {
|
||||
user_name: String,
|
||||
user_email: String,
|
||||
entries: Vec<AuditEntryView>,
|
||||
current_page: u32,
|
||||
total_pages: u32,
|
||||
total_count: i64,
|
||||
version: &'static str,
|
||||
}
|
||||
|
||||
struct AuditEntryView {
|
||||
/// RFC3339 UTC for `<time datetime>`; rendered as browser-local in audit.html.
|
||||
created_at_iso: String,
|
||||
action: String,
|
||||
target: String,
|
||||
detail: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(super) struct AuditQuery {
|
||||
page: Option<u32>,
|
||||
}
|
||||
|
||||
fn format_audit_target(folder: &str, entry_type: &str, name: &str) -> String {
|
||||
// Auth events (folder="auth") use entry_type/name as provider-scoped target.
|
||||
if folder == "auth" {
|
||||
format!("{}/{}", entry_type, name)
|
||||
} else if !folder.is_empty() && !entry_type.is_empty() {
|
||||
format!("[{}/{}] {}", folder, entry_type, name)
|
||||
} else if !folder.is_empty() {
|
||||
format!("[{}] {}", folder, name)
|
||||
} else {
|
||||
name.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn audit_page(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
Query(aq): Query<AuditQuery>,
|
||||
) -> Result<Response, StatusCode> {
|
||||
use secrets_core::service::audit_log::{count_for_user, list_for_user};
|
||||
|
||||
let user = match require_valid_user(&state.pool, &session, "audit_page").await {
|
||||
Ok(u) => u,
|
||||
Err(r) => return Ok(r),
|
||||
};
|
||||
let user_id = user.id;
|
||||
|
||||
let page = aq.page.unwrap_or(1).max(1);
|
||||
|
||||
let total_count = count_for_user(&state.pool, user_id).await.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to count audit log for user");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let (current_page, total_pages, offset) = paginate(page, total_count, AUDIT_PAGE_LIMIT as u32);
|
||||
let actual_offset = i64::from(offset);
|
||||
|
||||
let rows = list_for_user(&state.pool, user_id, AUDIT_PAGE_LIMIT, actual_offset)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to load audit log for user");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let entries = rows
|
||||
.into_iter()
|
||||
.map(|row| AuditEntryView {
|
||||
created_at_iso: row.created_at.to_rfc3339_opts(SecondsFormat::Secs, true),
|
||||
action: row.action,
|
||||
target: format_audit_target(&row.folder, &row.entry_type, &row.name),
|
||||
detail: serde_json::to_string_pretty(&row.detail).unwrap_or_else(|_| "{}".to_string()),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let tmpl = AuditPageTemplate {
|
||||
user_name: user.name.clone(),
|
||||
user_email: user.email.clone().unwrap_or_default(),
|
||||
entries,
|
||||
current_page,
|
||||
total_pages,
|
||||
total_count,
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
};
|
||||
|
||||
render_template(tmpl)
|
||||
}
|
||||
360
crates/secrets-mcp/src/web/auth.rs
Normal file
360
crates/secrets-mcp/src/web/auth.rs
Normal file
@@ -0,0 +1,360 @@
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use askama::Template;
|
||||
use axum::{
|
||||
extract::{ConnectInfo, Path, Query, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Redirect, Response},
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use tower_sessions::Session;
|
||||
|
||||
use secrets_core::audit::log_login;
|
||||
use secrets_core::service::user::{
|
||||
OAuthProfile, bind_oauth_account, find_or_create_user, unbind_oauth_account,
|
||||
};
|
||||
|
||||
use crate::AppState;
|
||||
use crate::oauth::{OAuthConfig, OAuthUserInfo, google_auth_url, random_state};
|
||||
|
||||
use super::{
|
||||
SESSION_KEY_VERSION, SESSION_LOGIN_PROVIDER, SESSION_OAUTH_BIND_MODE, SESSION_OAUTH_STATE,
|
||||
SESSION_USER_ID, current_user_id, google_cfg, render_template, request_user_agent,
|
||||
};
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "login.html")]
|
||||
struct LoginTemplate {
|
||||
has_google: bool,
|
||||
base_url: String,
|
||||
version: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "home.html")]
|
||||
struct HomeTemplate {
|
||||
is_logged_in: bool,
|
||||
base_url: String,
|
||||
version: &'static str,
|
||||
}
|
||||
|
||||
// ── Home page (public) ───────────────────────────────────────────────────────
|
||||
|
||||
pub(super) async fn home_page(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let is_logged_in = current_user_id(&session).await.is_some();
|
||||
let tmpl = HomeTemplate {
|
||||
is_logged_in,
|
||||
base_url: state.base_url.clone(),
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
};
|
||||
render_template(tmpl)
|
||||
}
|
||||
|
||||
// ── Login page ────────────────────────────────────────────────────────────────
|
||||
|
||||
pub(super) async fn login_page(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
) -> Result<Response, StatusCode> {
|
||||
if let Some(_uid) = current_user_id(&session).await {
|
||||
return Ok(Redirect::to("/dashboard").into_response());
|
||||
}
|
||||
|
||||
let tmpl = LoginTemplate {
|
||||
has_google: state.google_config.is_some(),
|
||||
base_url: state.base_url.clone(),
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
};
|
||||
render_template(tmpl)
|
||||
}
|
||||
|
||||
// ── Google OAuth ──────────────────────────────────────────────────────────────
|
||||
|
||||
pub(super) async fn auth_google(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let config = google_cfg(&state).ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
|
||||
let oauth_state = random_state();
|
||||
session
|
||||
.insert(SESSION_OAUTH_STATE, &oauth_state)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to insert oauth_state into session");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let url = google_auth_url(config, &oauth_state);
|
||||
Ok(Redirect::to(&url).into_response())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(super) struct OAuthCallbackQuery {
|
||||
code: Option<String>,
|
||||
state: Option<String>,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) async fn auth_google_callback(
|
||||
State(state): State<AppState>,
|
||||
connect_info: ConnectInfo<SocketAddr>,
|
||||
headers: HeaderMap,
|
||||
session: Session,
|
||||
Query(params): Query<OAuthCallbackQuery>,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let client_ip = Some(crate::client_ip::extract_client_ip_parts(
|
||||
&headers,
|
||||
connect_info.0,
|
||||
));
|
||||
let user_agent = request_user_agent(&headers);
|
||||
handle_oauth_callback(
|
||||
&state,
|
||||
&session,
|
||||
params,
|
||||
"google",
|
||||
client_ip.as_deref(),
|
||||
user_agent.as_deref(),
|
||||
|s, cfg, code| {
|
||||
Box::pin(crate::oauth::google::exchange_code(
|
||||
&s.http_client,
|
||||
cfg,
|
||||
code,
|
||||
))
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
// ── Shared OAuth callback handler ─────────────────────────────────────────────
|
||||
|
||||
async fn handle_oauth_callback<F>(
|
||||
state: &AppState,
|
||||
session: &Session,
|
||||
params: OAuthCallbackQuery,
|
||||
provider: &str,
|
||||
client_ip: Option<&str>,
|
||||
user_agent: Option<&str>,
|
||||
exchange_fn: F,
|
||||
) -> Result<Response, StatusCode>
|
||||
where
|
||||
F: for<'a> Fn(
|
||||
&'a AppState,
|
||||
&'a OAuthConfig,
|
||||
&'a str,
|
||||
) -> std::pin::Pin<
|
||||
Box<dyn std::future::Future<Output = anyhow::Result<OAuthUserInfo>> + Send + 'a>,
|
||||
>,
|
||||
{
|
||||
if let Some(err) = params.error {
|
||||
tracing::warn!(provider, error = %err, "OAuth error");
|
||||
return Ok(Redirect::to("/login?error=oauth_error").into_response());
|
||||
}
|
||||
|
||||
let Some(code) = params.code else {
|
||||
tracing::warn!(provider, "OAuth callback missing code");
|
||||
return Ok(Redirect::to("/login?error=oauth_missing_code").into_response());
|
||||
};
|
||||
let Some(returned_state) = params.state.as_deref() else {
|
||||
tracing::warn!(provider, "OAuth callback missing state");
|
||||
return Ok(Redirect::to("/login?error=oauth_missing_state").into_response());
|
||||
};
|
||||
|
||||
let expected_state: Option<String> = session.get(SESSION_OAUTH_STATE).await.map_err(|e| {
|
||||
tracing::error!(provider, error = %e, "failed to read oauth_state from session");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
if expected_state.as_deref() != Some(returned_state) {
|
||||
tracing::warn!(
|
||||
provider,
|
||||
expected_present = expected_state.is_some(),
|
||||
"OAuth state mismatch (empty session often means SameSite=Strict or server restart)"
|
||||
);
|
||||
return Ok(Redirect::to("/login?error=oauth_state").into_response());
|
||||
}
|
||||
if let Err(e) = session.remove::<String>(SESSION_OAUTH_STATE).await {
|
||||
tracing::warn!(provider, error = %e, "failed to remove oauth_state from session");
|
||||
}
|
||||
|
||||
let config = match provider {
|
||||
"google" => state
|
||||
.google_config
|
||||
.as_ref()
|
||||
.ok_or(StatusCode::SERVICE_UNAVAILABLE)?,
|
||||
_ => return Err(StatusCode::BAD_REQUEST),
|
||||
};
|
||||
|
||||
let user_info = exchange_fn(state, config, code.as_str())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(provider, error = %e, "failed to exchange OAuth code");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let bind_mode: bool = match session.get::<bool>(SESSION_OAUTH_BIND_MODE).await {
|
||||
Ok(v) => v.unwrap_or(false),
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
provider,
|
||||
error = %e,
|
||||
"failed to read oauth_bind_mode from session"
|
||||
);
|
||||
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
};
|
||||
|
||||
if bind_mode {
|
||||
let user_id = current_user_id(session)
|
||||
.await
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
if let Err(e) = session.remove::<bool>(SESSION_OAUTH_BIND_MODE).await {
|
||||
tracing::warn!(provider, error = %e, "failed to remove oauth_bind_mode from session after bind");
|
||||
}
|
||||
|
||||
let profile = OAuthProfile {
|
||||
provider: user_info.provider,
|
||||
provider_id: user_info.provider_id,
|
||||
email: user_info.email,
|
||||
name: user_info.name,
|
||||
avatar_url: user_info.avatar_url,
|
||||
};
|
||||
|
||||
bind_oauth_account(&state.pool, user_id, profile)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to bind OAuth account");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
return Ok(Redirect::to("/dashboard?bound=1").into_response());
|
||||
}
|
||||
|
||||
let profile = OAuthProfile {
|
||||
provider: user_info.provider,
|
||||
provider_id: user_info.provider_id,
|
||||
email: user_info.email,
|
||||
name: user_info.name,
|
||||
avatar_url: user_info.avatar_url,
|
||||
};
|
||||
|
||||
let (user, _is_new) = find_or_create_user(&state.pool, profile)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to find or create user");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
session
|
||||
.insert(SESSION_USER_ID, user.id.to_string())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(
|
||||
error = %e,
|
||||
user_id = %user.id,
|
||||
"failed to insert user_id into session after OAuth"
|
||||
);
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
session
|
||||
.insert(SESSION_LOGIN_PROVIDER, &provider)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(
|
||||
provider,
|
||||
error = %e,
|
||||
"failed to insert login_provider into session after OAuth"
|
||||
);
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
if let Err(e) = session.insert(SESSION_KEY_VERSION, user.key_version).await {
|
||||
tracing::warn!(error = %e, user_id = %user.id, "failed to insert key_version into session after OAuth");
|
||||
}
|
||||
|
||||
log_login(
|
||||
&state.pool,
|
||||
"oauth",
|
||||
provider,
|
||||
user.id,
|
||||
client_ip,
|
||||
user_agent,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(Redirect::to("/dashboard").into_response())
|
||||
}
|
||||
|
||||
// ── Logout ────────────────────────────────────────────────────────────────────
|
||||
|
||||
pub(super) async fn auth_logout(session: Session) -> impl IntoResponse {
|
||||
if let Err(e) = session.flush().await {
|
||||
tracing::warn!(error = %e, "failed to flush session on logout");
|
||||
}
|
||||
Redirect::to("/")
|
||||
}
|
||||
|
||||
// ── Account bind/unbind ───────────────────────────────────────────────────────
|
||||
|
||||
pub(super) async fn account_bind_google(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let _ = current_user_id(&session)
|
||||
.await
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
session
|
||||
.insert(SESSION_OAUTH_BIND_MODE, true)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to insert oauth_bind_mode into session");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let config = google_cfg(&state).ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let oauth_state = random_state();
|
||||
if let Err(e) = session.insert(SESSION_OAUTH_STATE, &oauth_state).await {
|
||||
tracing::error!(error = %e, "failed to insert oauth_state for account bind flow");
|
||||
if let Err(rm) = session.remove::<bool>(SESSION_OAUTH_BIND_MODE).await {
|
||||
tracing::warn!(error = %rm, "failed to roll back oauth_bind_mode after oauth_state insert failure");
|
||||
}
|
||||
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
let url = google_auth_url(config, &oauth_state);
|
||||
Ok(Redirect::to(&url).into_response())
|
||||
}
|
||||
|
||||
pub(super) async fn account_unbind(
|
||||
State(state): State<AppState>,
|
||||
Path(provider): Path<String>,
|
||||
session: Session,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let user_id = current_user_id(&session)
|
||||
.await
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
let current_login_provider = session
|
||||
.get::<String>(SESSION_LOGIN_PROVIDER)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to read login_provider from session");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
unbind_oauth_account(
|
||||
&state.pool,
|
||||
user_id,
|
||||
&provider,
|
||||
current_login_provider.as_deref(),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!(error = %e, "failed to unbind oauth account");
|
||||
StatusCode::BAD_REQUEST
|
||||
})?;
|
||||
|
||||
Ok(Redirect::to("/dashboard?unbound=1").into_response())
|
||||
}
|
||||
948
crates/secrets-mcp/src/web/entries.rs
Normal file
948
crates/secrets-mcp/src/web/entries.rs
Normal file
@@ -0,0 +1,948 @@
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Path, Query, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::Response,
|
||||
};
|
||||
use chrono::SecondsFormat;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
use tower_sessions::Session;
|
||||
use uuid::Uuid;
|
||||
|
||||
use secrets_core::error::AppError;
|
||||
use secrets_core::service::{
|
||||
delete::delete_by_id,
|
||||
get_secret::get_all_secrets_by_id,
|
||||
search::{SearchParams, count_entries, fetch_secrets_for_entries, ilike_pattern, list_entries},
|
||||
update::{UpdateEntryFieldsByIdParams, update_fields_by_id},
|
||||
};
|
||||
|
||||
use crate::AppState;
|
||||
|
||||
use super::{
|
||||
ENTRIES_PAGE_LIMIT, UiLang, current_user_id, paginate, render_template, request_ui_lang,
|
||||
require_valid_user, tr,
|
||||
};
|
||||
|
||||
// ── Template types ────────────────────────────────────────────────────────────
|
||||
|
||||
use askama::Template;
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "entries.html")]
|
||||
struct EntriesPageTemplate {
|
||||
user_name: String,
|
||||
user_email: String,
|
||||
entries: Vec<EntryListItemView>,
|
||||
folder_tabs: Vec<FolderTabView>,
|
||||
type_options: Vec<String>,
|
||||
secret_type_options_json: String,
|
||||
filter_folder: String,
|
||||
filter_name: String,
|
||||
filter_type: String,
|
||||
current_page: u32,
|
||||
total_pages: u32,
|
||||
total_count: i64,
|
||||
version: &'static str,
|
||||
}
|
||||
|
||||
/// Non-sensitive entry fields; `secrets` lists field names/types only (no ciphertext).
|
||||
struct EntryListItemView {
|
||||
id: String,
|
||||
folder: String,
|
||||
entry_type: String,
|
||||
name: String,
|
||||
notes: String,
|
||||
tags: String,
|
||||
/// Compact JSON for `data-entry-metadata` (dialog editor).
|
||||
metadata_json: String,
|
||||
/// Secret field summaries for table + dialog chips.
|
||||
secrets: Vec<SecretSummaryView>,
|
||||
/// JSON array of `{ id, name, secret_type }` for dialog secret chips.
|
||||
secrets_json: String,
|
||||
/// RFC3339 UTC; shown in edit dialog.
|
||||
updated_at_iso: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct SecretSummaryView {
|
||||
id: String,
|
||||
name: String,
|
||||
secret_type: String,
|
||||
}
|
||||
|
||||
struct FolderTabView {
|
||||
name: String,
|
||||
count: i64,
|
||||
href: String,
|
||||
active: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(super) struct EntriesQuery {
|
||||
folder: Option<String>,
|
||||
name: Option<String>,
|
||||
/// URL query key is `type` (maps to DB column `entries.type`).
|
||||
#[serde(rename = "type")]
|
||||
entry_type: Option<String>,
|
||||
page: Option<u32>,
|
||||
}
|
||||
|
||||
// ── Entry mutation error helpers ──────────────────────────────────────────────
|
||||
|
||||
type EntryApiError = (StatusCode, Json<serde_json::Value>);
|
||||
|
||||
fn map_entry_mutation_err(e: anyhow::Error, lang: UiLang) -> EntryApiError {
|
||||
if let Some(app_err) = e.downcast_ref::<AppError>() {
|
||||
return map_app_error(app_err, lang);
|
||||
}
|
||||
|
||||
// Fallback for legacy string-based errors and raw sqlx errors
|
||||
let msg = e.to_string();
|
||||
if msg.contains("already exists") {
|
||||
return (
|
||||
StatusCode::CONFLICT,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "该账号下已存在相同 folder + name 的条目", "此帳號下已存在相同 folder + name 的條目", "An entry with the same folder + name already exists for this account") }),
|
||||
),
|
||||
);
|
||||
}
|
||||
if msg.contains("must be at most") {
|
||||
return (StatusCode::BAD_REQUEST, Json(json!({ "error": msg })));
|
||||
}
|
||||
tracing::error!(error = %e, "entry mutation failed");
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "操作失败,请稍后重试", "操作失敗,請稍後重試", "Operation failed, please try again later") }),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fn map_app_error(err: &AppError, lang: UiLang) -> EntryApiError {
|
||||
match err {
|
||||
AppError::ConflictEntryName { .. } | AppError::ConflictSecretName { .. } => (
|
||||
StatusCode::CONFLICT,
|
||||
Json(json!({ "error": err.to_string() })),
|
||||
),
|
||||
AppError::NotFoundEntry | AppError::NotFoundUser | AppError::NotFoundSecret => (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "资源不存在或无权访问", "資源不存在或無權存取", "Resource not found or no access") }),
|
||||
),
|
||||
),
|
||||
AppError::AuthenticationFailed | AppError::Unauthorized => (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "认证失败或无权访问", "認證失敗或無權存取", "Authentication failed or unauthorized") }),
|
||||
),
|
||||
),
|
||||
AppError::Validation { message } => {
|
||||
(StatusCode::BAD_REQUEST, Json(json!({ "error": message })))
|
||||
}
|
||||
AppError::ConcurrentModification => (
|
||||
StatusCode::CONFLICT,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "条目已被修改,请刷新后重试", "條目已被修改,請重新整理後重試", "Entry was modified, please refresh and try again") }),
|
||||
),
|
||||
),
|
||||
AppError::DecryptionFailed => (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "解密失败,请检查密码短语", "解密失敗,請檢查密碼短語", "Decryption failed — please check your passphrase") }),
|
||||
),
|
||||
),
|
||||
AppError::EncryptionKeyNotSet => (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "请先设置密码短语后再使用此功能", "請先設定密碼短語再使用此功能", "Please set a passphrase before using this feature") }),
|
||||
),
|
||||
),
|
||||
AppError::Internal(_) => {
|
||||
tracing::error!(error = %err, "internal error in entry mutation");
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "操作失败,请稍后重试", "操作失敗,請稍後重試", "Operation failed, please try again later") }),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Handlers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
pub(super) async fn entries_page(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
Query(q): Query<EntriesQuery>,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let user = match require_valid_user(&state.pool, &session, "entries_page").await {
|
||||
Ok(u) => u,
|
||||
Err(r) => return Ok(r),
|
||||
};
|
||||
let user_id = user.id;
|
||||
|
||||
let folder_filter = q
|
||||
.folder
|
||||
.as_ref()
|
||||
.map(|s| s.trim())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| s.to_string());
|
||||
let type_filter = q
|
||||
.entry_type
|
||||
.as_ref()
|
||||
.map(|s| s.trim())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| s.to_string());
|
||||
let name_filter = q
|
||||
.name
|
||||
.as_ref()
|
||||
.map(|s| s.trim())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| s.to_string());
|
||||
let page = q.page.unwrap_or(1).max(1);
|
||||
let count_params = SearchParams {
|
||||
folder: folder_filter.as_deref(),
|
||||
entry_type: type_filter.as_deref(),
|
||||
name: None,
|
||||
name_query: name_filter.as_deref(),
|
||||
tags: &[],
|
||||
query: None,
|
||||
sort: "updated",
|
||||
limit: ENTRIES_PAGE_LIMIT,
|
||||
offset: 0,
|
||||
user_id: Some(user_id),
|
||||
};
|
||||
|
||||
// Build folder query before joining so the SQL string lives long enough.
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct FolderCountRow {
|
||||
folder: String,
|
||||
count: i64,
|
||||
}
|
||||
let mut folder_sql =
|
||||
"SELECT folder, COUNT(*)::bigint AS count FROM entries WHERE user_id = $1".to_string();
|
||||
let mut bind_idx = 2;
|
||||
if type_filter.is_some() {
|
||||
folder_sql.push_str(&format!(" AND type = ${bind_idx}"));
|
||||
bind_idx += 1;
|
||||
}
|
||||
if name_filter.is_some() {
|
||||
folder_sql.push_str(&format!(" AND name ILIKE ${bind_idx} ESCAPE '\\'"));
|
||||
bind_idx += 1;
|
||||
}
|
||||
let _ = bind_idx;
|
||||
folder_sql.push_str(" GROUP BY folder ORDER BY folder");
|
||||
let mut folder_query = sqlx::query_as::<_, FolderCountRow>(&folder_sql).bind(user_id);
|
||||
if let Some(t) = type_filter.as_deref() {
|
||||
folder_query = folder_query.bind(t);
|
||||
}
|
||||
if let Some(n) = name_filter.as_deref() {
|
||||
folder_query = folder_query.bind(ilike_pattern(n));
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct TypeOptionRow {
|
||||
#[sqlx(rename = "type")]
|
||||
entry_type: String,
|
||||
}
|
||||
|
||||
// Phase 1: count, folder tabs, and type options are mutually independent — run in parallel.
|
||||
let (total_count, folder_rows_res, type_options_res) = tokio::join!(
|
||||
async {
|
||||
count_entries(&state.pool, &count_params)
|
||||
.await
|
||||
.inspect_err(
|
||||
|e| tracing::warn!(error = %e, "count_entries failed for web entries page"),
|
||||
)
|
||||
.unwrap_or(0)
|
||||
},
|
||||
folder_query.fetch_all(&state.pool),
|
||||
sqlx::query_as::<_, TypeOptionRow>(
|
||||
"SELECT DISTINCT type FROM entries WHERE user_id = $1 ORDER BY type",
|
||||
)
|
||||
.bind(user_id)
|
||||
.fetch_all(&state.pool),
|
||||
);
|
||||
let folder_rows = folder_rows_res.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to load folder tabs for web");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
let mut type_options: Vec<String> = type_options_res
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to load type options for web");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?
|
||||
.into_iter()
|
||||
.map(|r| r.entry_type)
|
||||
.filter(|t| !t.is_empty())
|
||||
.collect();
|
||||
|
||||
// Phase 2: paginate using count, then fetch entries for the page.
|
||||
let (current_page, total_pages, offset) = paginate(page, total_count, ENTRIES_PAGE_LIMIT);
|
||||
let list_params = SearchParams {
|
||||
offset,
|
||||
..count_params
|
||||
};
|
||||
let rows = list_entries(&state.pool, list_params).await.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to load entries list for web");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
let entry_ids: Vec<Uuid> = rows.iter().map(|e| e.id).collect();
|
||||
let secret_schemas = fetch_secrets_for_entries(&state.pool, &entry_ids)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to load secret schema list for web");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
if let Some(current) = type_filter.as_ref()
|
||||
&& !current.is_empty()
|
||||
&& !type_options.iter().any(|t| t == current)
|
||||
{
|
||||
type_options.push(current.clone());
|
||||
type_options.sort_unstable();
|
||||
}
|
||||
|
||||
fn entries_href(
|
||||
folder: Option<&str>,
|
||||
entry_type: Option<&str>,
|
||||
name: Option<&str>,
|
||||
page: Option<u32>,
|
||||
) -> String {
|
||||
let mut pairs: Vec<String> = Vec::new();
|
||||
if let Some(f) = folder
|
||||
&& !f.is_empty()
|
||||
{
|
||||
pairs.push(format!("folder={}", urlencoding::encode(f)));
|
||||
}
|
||||
if let Some(t) = entry_type
|
||||
&& !t.is_empty()
|
||||
{
|
||||
pairs.push(format!("type={}", urlencoding::encode(t)));
|
||||
}
|
||||
if let Some(n) = name
|
||||
&& !n.is_empty()
|
||||
{
|
||||
pairs.push(format!("name={}", urlencoding::encode(n)));
|
||||
}
|
||||
if let Some(p) = page {
|
||||
pairs.push(format!("page={}", p));
|
||||
}
|
||||
if pairs.is_empty() {
|
||||
"/entries".to_string()
|
||||
} else {
|
||||
format!("/entries?{}", pairs.join("&"))
|
||||
}
|
||||
}
|
||||
|
||||
let all_count: i64 = folder_rows.iter().map(|r| r.count).sum();
|
||||
let mut folder_tabs: Vec<FolderTabView> = Vec::with_capacity(folder_rows.len() + 1);
|
||||
folder_tabs.push(FolderTabView {
|
||||
name: "全部".to_string(),
|
||||
count: all_count,
|
||||
href: entries_href(
|
||||
None,
|
||||
type_filter.as_deref(),
|
||||
name_filter.as_deref(),
|
||||
Some(1),
|
||||
),
|
||||
active: folder_filter.is_none(),
|
||||
});
|
||||
for r in folder_rows {
|
||||
let name = r.folder;
|
||||
folder_tabs.push(FolderTabView {
|
||||
href: entries_href(
|
||||
Some(&name),
|
||||
type_filter.as_deref(),
|
||||
name_filter.as_deref(),
|
||||
Some(1),
|
||||
),
|
||||
active: folder_filter.as_deref() == Some(name.as_str()),
|
||||
name,
|
||||
count: r.count,
|
||||
});
|
||||
}
|
||||
|
||||
let entries = rows
|
||||
.into_iter()
|
||||
.map(|e| {
|
||||
let secrets: Vec<SecretSummaryView> = secret_schemas
|
||||
.get(&e.id)
|
||||
.map(|fields| {
|
||||
fields
|
||||
.iter()
|
||||
.map(|f| SecretSummaryView {
|
||||
id: f.id.to_string(),
|
||||
name: f.name.clone(),
|
||||
secret_type: f.secret_type.clone(),
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let secrets_json = serde_json::to_string(&secrets).unwrap_or_else(|_| "[]".to_string());
|
||||
let metadata_json =
|
||||
serde_json::to_string(&e.metadata).unwrap_or_else(|_| "{}".to_string());
|
||||
EntryListItemView {
|
||||
id: e.id.to_string(),
|
||||
folder: e.folder,
|
||||
entry_type: e.entry_type,
|
||||
name: e.name,
|
||||
notes: e.notes,
|
||||
tags: e.tags.join(", "),
|
||||
metadata_json,
|
||||
secrets,
|
||||
secrets_json,
|
||||
updated_at_iso: e.updated_at.to_rfc3339_opts(SecondsFormat::Secs, true),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let tmpl = EntriesPageTemplate {
|
||||
user_name: user.name.clone(),
|
||||
user_email: user.email.clone().unwrap_or_default(),
|
||||
entries,
|
||||
folder_tabs,
|
||||
type_options,
|
||||
secret_type_options_json: serde_json::to_string(
|
||||
&secrets_core::taxonomy::SECRET_TYPE_OPTIONS
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.unwrap_or_default(),
|
||||
filter_folder: folder_filter.unwrap_or_default(),
|
||||
filter_name: name_filter.unwrap_or_default(),
|
||||
filter_type: type_filter.unwrap_or_default(),
|
||||
current_page,
|
||||
total_pages,
|
||||
total_count,
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
};
|
||||
|
||||
render_template(tmpl)
|
||||
}
|
||||
|
||||
// ── Entry management (Web UI, non-sensitive fields only) ───────────────────────
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(super) struct EntryPatchBody {
|
||||
folder: String,
|
||||
#[serde(rename = "type")]
|
||||
entry_type: String,
|
||||
name: String,
|
||||
notes: String,
|
||||
tags: Vec<String>,
|
||||
metadata: serde_json::Value,
|
||||
}
|
||||
|
||||
pub(super) async fn api_entry_patch(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
headers: HeaderMap,
|
||||
Path(entry_id): Path<Uuid>,
|
||||
Json(body): Json<EntryPatchBody>,
|
||||
) -> Result<Json<serde_json::Value>, EntryApiError> {
|
||||
let lang = request_ui_lang(&headers);
|
||||
let user_id = current_user_id(&session).await.ok_or((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(json!({ "error": tr(lang, "未登录", "尚未登入", "Not logged in") })),
|
||||
))?;
|
||||
|
||||
let folder = body.folder.trim();
|
||||
let entry_type = body.entry_type.trim();
|
||||
let name = body.name.trim();
|
||||
let notes = body.notes.trim();
|
||||
|
||||
if name.is_empty() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "name 不能为空", "name 不能為空", "name cannot be empty") }),
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let tags: Vec<String> = body
|
||||
.tags
|
||||
.into_iter()
|
||||
.map(|t| t.trim().to_string())
|
||||
.filter(|t| !t.is_empty())
|
||||
.collect();
|
||||
|
||||
if !body.metadata.is_object() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "metadata 必须是 JSON 对象", "metadata 必須是 JSON 物件", "metadata must be a JSON object") }),
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
update_fields_by_id(
|
||||
&state.pool,
|
||||
entry_id,
|
||||
user_id,
|
||||
UpdateEntryFieldsByIdParams {
|
||||
folder,
|
||||
entry_type,
|
||||
name,
|
||||
notes,
|
||||
tags: &tags,
|
||||
metadata: &body.metadata,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|e| map_entry_mutation_err(e, lang))?;
|
||||
|
||||
Ok(Json(json!({ "ok": true })))
|
||||
}
|
||||
|
||||
pub(super) async fn api_entry_delete(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
headers: HeaderMap,
|
||||
Path(entry_id): Path<Uuid>,
|
||||
) -> Result<Json<serde_json::Value>, EntryApiError> {
|
||||
let lang = request_ui_lang(&headers);
|
||||
let user_id = current_user_id(&session).await.ok_or((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(json!({ "error": tr(lang, "未登录", "尚未登入", "Not logged in") })),
|
||||
))?;
|
||||
|
||||
delete_by_id(&state.pool, entry_id, user_id)
|
||||
.await
|
||||
.map_err(|e| map_entry_mutation_err(e, lang))?;
|
||||
|
||||
Ok(Json(json!({
|
||||
"ok": true,
|
||||
})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(super) struct SecretCheckNameQuery {
|
||||
name: String,
|
||||
exclude_secret_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(super) struct SecretCheckNameResponse {
|
||||
ok: bool,
|
||||
available: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) async fn api_secret_check_name(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
headers: HeaderMap,
|
||||
Query(params): Query<SecretCheckNameQuery>,
|
||||
) -> Result<Json<SecretCheckNameResponse>, EntryApiError> {
|
||||
let lang = request_ui_lang(&headers);
|
||||
let user_id = current_user_id(&session).await.ok_or((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(json!({ "error": tr(lang, "未登录", "尚未登入", "Not logged in") })),
|
||||
))?;
|
||||
|
||||
let name = params.name.trim();
|
||||
if name.is_empty() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "secret name 不能为空", "secret name 不能為空", "secret name cannot be empty") }),
|
||||
),
|
||||
));
|
||||
}
|
||||
if name.chars().count() > 256 {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "secret name 长度不能超过 256 个字符", "secret name 長度不能超過 256 個字元", "secret name must be at most 256 characters") }),
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let count: i64 = if let Some(exclude_id) = params.exclude_secret_id {
|
||||
sqlx::query_scalar::<_, i64>(
|
||||
"SELECT COUNT(*) FROM secrets WHERE user_id = $1 AND name = $2 AND id != $3",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(name)
|
||||
.bind(exclude_id)
|
||||
.fetch_one(&state.pool)
|
||||
.await
|
||||
} else {
|
||||
sqlx::query_scalar::<_, i64>(
|
||||
"SELECT COUNT(*) FROM secrets WHERE user_id = $1 AND name = $2",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(name)
|
||||
.fetch_one(&state.pool)
|
||||
.await
|
||||
}.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to check secret name availability");
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "操作失败,请稍后重试", "操作失敗,請稍後重試", "Operation failed, please try again later") }),
|
||||
),
|
||||
)
|
||||
})?;
|
||||
|
||||
let available = count == 0;
|
||||
let error = if available {
|
||||
None
|
||||
} else {
|
||||
Some(
|
||||
tr(
|
||||
lang,
|
||||
"该用户下已存在相同 name 的密文",
|
||||
"該用戶下已存在相同 name 的密文",
|
||||
"A secret with the same name already exists for this user",
|
||||
)
|
||||
.to_string(),
|
||||
)
|
||||
};
|
||||
|
||||
Ok(Json(SecretCheckNameResponse {
|
||||
ok: true,
|
||||
available,
|
||||
error,
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(super) struct SecretPatchBody {
|
||||
name: Option<String>,
|
||||
#[serde(rename = "type")]
|
||||
secret_type: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) async fn api_secret_patch(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
headers: HeaderMap,
|
||||
Path(secret_id): Path<Uuid>,
|
||||
Json(body): Json<SecretPatchBody>,
|
||||
) -> Result<Json<serde_json::Value>, EntryApiError> {
|
||||
#[derive(Serialize, sqlx::FromRow)]
|
||||
struct LinkedEntryAuditRow {
|
||||
folder: String,
|
||||
#[sqlx(rename = "type")]
|
||||
entry_type: String,
|
||||
name: String,
|
||||
}
|
||||
|
||||
let lang = request_ui_lang(&headers);
|
||||
let user_id = current_user_id(&session).await.ok_or((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(json!({ "error": tr(lang, "未登录", "尚未登入", "Not logged in") })),
|
||||
))?;
|
||||
|
||||
let name = body.name.as_ref().map(|s| s.trim());
|
||||
let secret_type = body.secret_type.as_ref().map(|s| s.trim());
|
||||
|
||||
if let Some(n) = name {
|
||||
if n.is_empty() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "secret name 不能为空", "secret name 不能為空", "secret name cannot be empty") }),
|
||||
),
|
||||
));
|
||||
}
|
||||
if n.chars().count() > 256 {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "secret name 长度不能超过 256 个字符", "secret name 長度不能超過 256 個字元", "secret name must be at most 256 characters") }),
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(t) = secret_type {
|
||||
if t.is_empty() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "secret type 不能为空", "secret type 不能為空", "secret type cannot be empty") }),
|
||||
),
|
||||
));
|
||||
}
|
||||
if t.chars().count() > 64 {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "secret type 长度不能超过 64 个字符", "secret type 長度不能超過 64 個字元", "secret type must be at most 64 characters") }),
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if name.is_none() && secret_type.is_none() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "至少需要提供 name 或 type 之一", "至少需要提供 name 或 type 之一", "At least one of name or type is required") }),
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let mut tx = state
|
||||
.pool
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|e| map_entry_mutation_err(e.into(), lang))?;
|
||||
|
||||
let secret_row: Option<(String, String)> =
|
||||
sqlx::query_as("SELECT name, type FROM secrets WHERE id = $1 AND user_id = $2 FOR UPDATE")
|
||||
.bind(secret_id)
|
||||
.bind(user_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await
|
||||
.map_err(|e| map_entry_mutation_err(e.into(), lang))?;
|
||||
|
||||
let Some((old_name, old_type)) = secret_row else {
|
||||
let _ = tx.rollback().await;
|
||||
return Err((
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "密文不存在或无权访问", "密文不存在或無權存取", "Secret not found or no access") }),
|
||||
),
|
||||
));
|
||||
};
|
||||
|
||||
let linked_entries: Vec<LinkedEntryAuditRow> = sqlx::query_as(
|
||||
"SELECT e.folder, e.type, e.name \
|
||||
FROM entry_secrets es \
|
||||
JOIN entries e ON e.id = es.entry_id \
|
||||
WHERE es.secret_id = $1 AND e.user_id = $2 \
|
||||
ORDER BY e.folder, e.type, e.name",
|
||||
)
|
||||
.bind(secret_id)
|
||||
.bind(user_id)
|
||||
.fetch_all(&mut *tx)
|
||||
.await
|
||||
.map_err(|e| map_entry_mutation_err(e.into(), lang))?;
|
||||
|
||||
let new_name = name.unwrap_or(&old_name).to_string();
|
||||
let new_type = secret_type.unwrap_or(&old_type).to_string();
|
||||
|
||||
let result = sqlx::query(
|
||||
"UPDATE secrets SET name = $1, type = $2, version = version + 1, updated_at = NOW() \
|
||||
WHERE id = $3",
|
||||
)
|
||||
.bind(&new_name)
|
||||
.bind(&new_type)
|
||||
.bind(secret_id)
|
||||
.execute(&mut *tx)
|
||||
.await;
|
||||
|
||||
if let Err(e) = result {
|
||||
if let Some(db_err) = e.as_database_error()
|
||||
&& db_err.code() == Some("23505".into())
|
||||
{
|
||||
let _ = tx.rollback().await;
|
||||
return Err(map_app_error(
|
||||
&AppError::ConflictSecretName {
|
||||
secret_name: new_name.clone(),
|
||||
},
|
||||
lang,
|
||||
));
|
||||
}
|
||||
let _ = tx.rollback().await;
|
||||
return Err(map_entry_mutation_err(e.into(), lang));
|
||||
}
|
||||
|
||||
secrets_core::audit::log_tx(
|
||||
&mut tx,
|
||||
Some(user_id),
|
||||
"rename_secret",
|
||||
"",
|
||||
"",
|
||||
&old_name,
|
||||
json!({
|
||||
"source": "web",
|
||||
"secret_id": secret_id,
|
||||
"old_name": old_name,
|
||||
"new_name": new_name,
|
||||
"old_type": old_type,
|
||||
"new_type": new_type,
|
||||
"linked_entries": linked_entries,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|e| map_entry_mutation_err(e.into(), lang))?;
|
||||
|
||||
Ok(Json(json!({ "ok": true })))
|
||||
}
|
||||
|
||||
pub(super) async fn api_entry_secret_unlink(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
headers: HeaderMap,
|
||||
Path((entry_id, secret_id)): Path<(Uuid, Uuid)>,
|
||||
) -> Result<Json<serde_json::Value>, EntryApiError> {
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct EntryAuditRow {
|
||||
folder: String,
|
||||
#[sqlx(rename = "type")]
|
||||
entry_type: String,
|
||||
name: String,
|
||||
}
|
||||
|
||||
let lang = request_ui_lang(&headers);
|
||||
let user_id = current_user_id(&session).await.ok_or((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(json!({ "error": tr(lang, "未登录", "尚未登入", "Not logged in") })),
|
||||
))?;
|
||||
|
||||
let mut tx = state
|
||||
.pool
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|e| map_entry_mutation_err(e.into(), lang))?;
|
||||
|
||||
let entry_row: Option<EntryAuditRow> =
|
||||
sqlx::query_as("SELECT folder, type, name FROM entries WHERE id = $1 AND user_id = $2")
|
||||
.bind(entry_id)
|
||||
.bind(user_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await
|
||||
.map_err(|e| map_entry_mutation_err(e.into(), lang))?;
|
||||
|
||||
let Some(entry_row) = entry_row else {
|
||||
let _ = tx.rollback().await;
|
||||
return Err((
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(
|
||||
json!({ "error": tr(lang, "条目不存在或无权访问", "條目不存在或無權存取", "Entry not found or no access") }),
|
||||
),
|
||||
));
|
||||
};
|
||||
|
||||
let deleted = sqlx::query("DELETE FROM entry_secrets WHERE entry_id = $1 AND secret_id = $2")
|
||||
.bind(entry_id)
|
||||
.bind(secret_id)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(|e| map_entry_mutation_err(e.into(), lang))?
|
||||
.rows_affected();
|
||||
|
||||
if deleted == 0 {
|
||||
let _ = tx.rollback().await;
|
||||
return Err((
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(json!({ "error": tr(lang, "关联不存在", "關聯不存在", "Relation not found") })),
|
||||
));
|
||||
}
|
||||
|
||||
let secret_deleted = sqlx::query(
|
||||
"DELETE FROM secrets s \
|
||||
WHERE s.id = $1 \
|
||||
AND NOT EXISTS (SELECT 1 FROM entry_secrets es WHERE es.secret_id = s.id)",
|
||||
)
|
||||
.bind(secret_id)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(|e| map_entry_mutation_err(e.into(), lang))?
|
||||
.rows_affected()
|
||||
> 0;
|
||||
|
||||
secrets_core::audit::log_tx(
|
||||
&mut tx,
|
||||
Some(user_id),
|
||||
"unlink_secret",
|
||||
&entry_row.folder,
|
||||
&entry_row.entry_type,
|
||||
&entry_row.name,
|
||||
json!({
|
||||
"source": "web",
|
||||
"entry_id": entry_id,
|
||||
"secret_id": secret_id,
|
||||
"deleted_secret": secret_deleted,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|e| map_entry_mutation_err(e.into(), lang))?;
|
||||
|
||||
Ok(Json(json!({
|
||||
"ok": true,
|
||||
"deleted_relation": true,
|
||||
"deleted_secret": secret_deleted,
|
||||
})))
|
||||
}
|
||||
|
||||
// ── Decrypt entry secrets (Web UI) ───────────────────────────────────────────
|
||||
|
||||
pub(super) async fn api_entry_secrets_decrypt(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
headers: HeaderMap,
|
||||
Path(entry_id): Path<Uuid>,
|
||||
) -> Result<Json<serde_json::Value>, EntryApiError> {
|
||||
let lang = request_ui_lang(&headers);
|
||||
let user_id = current_user_id(&session).await.ok_or((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(json!({ "error": tr(lang, "未登录", "尚未登入", "Not logged in") })),
|
||||
))?;
|
||||
|
||||
let enc_key_hex = headers
|
||||
.get("x-encryption-key")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.ok_or_else(|| {
|
||||
(
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(json!({ "error": tr(lang, "缺少 X-Encryption-Key 请求头", "缺少 X-Encryption-Key 請求標頭", "Missing X-Encryption-Key header") })),
|
||||
)
|
||||
})?;
|
||||
|
||||
let master_key =
|
||||
secrets_core::crypto::extract_key_from_hex(enc_key_hex).map_err(|_| {
|
||||
(
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(json!({ "error": tr(lang, "X-Encryption-Key 格式无效", "X-Encryption-Key 格式無效", "Invalid X-Encryption-Key format") })),
|
||||
)
|
||||
})?;
|
||||
|
||||
let secrets =
|
||||
get_all_secrets_by_id(&state.pool, entry_id, &master_key, Some(user_id))
|
||||
.await
|
||||
.map_err(|e| {
|
||||
if let Some(app_err) = e.downcast_ref::<AppError>() {
|
||||
return match app_err {
|
||||
AppError::DecryptionFailed => (
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
Json(json!({ "error": tr(lang, "解密失败,请确认密码短语正确", "解密失敗,請確認密碼短語正確", "Decryption failed, please verify your passphrase") })),
|
||||
),
|
||||
AppError::NotFoundEntry | AppError::NotFoundUser | AppError::NotFoundSecret => (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(json!({ "error": tr(lang, "条目不存在或无权访问", "條目不存在或無權存取", "Entry not found or no access") })),
|
||||
),
|
||||
_ => {
|
||||
tracing::error!(error = %e, %entry_id, "decrypt entry secrets failed");
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(json!({ "error": tr(lang, "操作失败,请稍后重试", "操作失敗,請稍後重試", "Operation failed, please try again later") })),
|
||||
)
|
||||
}
|
||||
};
|
||||
}
|
||||
tracing::error!(error = %e, %entry_id, "decrypt entry secrets failed");
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(json!({ "error": tr(lang, "操作失败,请稍后重试", "操作失敗,請稍後重試", "Operation failed, please try again later") })),
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(Json(json!({ "ok": true, "secrets": secrets })))
|
||||
}
|
||||
306
crates/secrets-mcp/src/web/mod.rs
Normal file
306
crates/secrets-mcp/src/web/mod.rs
Normal file
@@ -0,0 +1,306 @@
|
||||
use askama::Template;
|
||||
use axum::{
|
||||
Router,
|
||||
http::{HeaderMap, StatusCode, header},
|
||||
response::{Html, IntoResponse, Redirect, Response},
|
||||
routing::{get, patch, post},
|
||||
};
|
||||
use tower_sessions::Session;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::AppState;
|
||||
use crate::oauth::OAuthConfig;
|
||||
|
||||
mod account;
|
||||
mod assets;
|
||||
mod audit;
|
||||
mod auth;
|
||||
mod entries;
|
||||
|
||||
// ── Session keys ──────────────────────────────────────────────────────────────
|
||||
|
||||
const SESSION_USER_ID: &str = "user_id";
|
||||
const SESSION_OAUTH_STATE: &str = "oauth_state";
|
||||
const SESSION_OAUTH_BIND_MODE: &str = "oauth_bind_mode";
|
||||
const SESSION_LOGIN_PROVIDER: &str = "login_provider";
|
||||
const SESSION_KEY_VERSION: &str = "key_version";
|
||||
|
||||
// ── Page limits ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// Cap for HTML list (avoids loading unbounded rows into memory).
|
||||
const ENTRIES_PAGE_LIMIT: u32 = 50;
|
||||
const AUDIT_PAGE_LIMIT: i64 = 10;
|
||||
|
||||
// ── UI language ───────────────────────────────────────────────────────────────
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum UiLang {
|
||||
ZhCn,
|
||||
ZhTw,
|
||||
En,
|
||||
}
|
||||
|
||||
fn request_ui_lang(headers: &HeaderMap) -> UiLang {
|
||||
let Some(raw) = headers
|
||||
.get(header::ACCEPT_LANGUAGE)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
else {
|
||||
return UiLang::ZhCn;
|
||||
};
|
||||
let lower = raw.to_ascii_lowercase();
|
||||
if lower.contains("zh-tw") || lower.contains("zh-hk") || lower.contains("zh-hant") {
|
||||
UiLang::ZhTw
|
||||
} else if lower.contains("zh") {
|
||||
UiLang::ZhCn
|
||||
} else if lower.contains("en") {
|
||||
UiLang::En
|
||||
} else {
|
||||
UiLang::ZhCn
|
||||
}
|
||||
}
|
||||
|
||||
fn tr(lang: UiLang, zh_cn: &'static str, zh_tw: &'static str, en: &'static str) -> &'static str {
|
||||
match lang {
|
||||
UiLang::ZhCn => zh_cn,
|
||||
UiLang::ZhTw => zh_tw,
|
||||
UiLang::En => en,
|
||||
}
|
||||
}
|
||||
|
||||
// ── App state helpers ─────────────────────────────────────────────────────────
|
||||
|
||||
fn google_cfg(state: &AppState) -> Option<&OAuthConfig> {
|
||||
state.google_config.as_ref()
|
||||
}
|
||||
|
||||
async fn current_user_id(session: &Session) -> Option<Uuid> {
|
||||
match session.get::<String>(SESSION_USER_ID).await {
|
||||
Ok(opt) => match opt {
|
||||
Some(s) => match Uuid::parse_str(&s) {
|
||||
Ok(id) => Some(id),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, user_id_str = %s, "invalid user_id UUID in session");
|
||||
None
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
},
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "failed to read user_id from session");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Load and validate the current user from session and DB.
|
||||
///
|
||||
/// Returns the user if the session is valid. Flushes the session and returns
|
||||
/// `Err(Redirect::to("/login"))` when:
|
||||
/// - the session has no `user_id`,
|
||||
/// - the user no longer exists in the database, or
|
||||
/// - the stored `key_version` does not match the DB value (passphrase changed on
|
||||
/// another device since this session was created).
|
||||
async fn require_valid_user(
|
||||
pool: &sqlx::PgPool,
|
||||
session: &Session,
|
||||
context: &str,
|
||||
) -> Result<secrets_core::models::User, Response> {
|
||||
let Some(user_id) = current_user_id(session).await else {
|
||||
return Err(Redirect::to("/login").into_response());
|
||||
};
|
||||
|
||||
let user = match secrets_core::service::user::get_user_by_id(pool, user_id).await {
|
||||
Err(e) => {
|
||||
tracing::error!(error = %e, %user_id, context, "failed to load user");
|
||||
return Err(StatusCode::INTERNAL_SERVER_ERROR.into_response());
|
||||
}
|
||||
Ok(None) => {
|
||||
if let Err(e) = session.flush().await {
|
||||
tracing::warn!(error = %e, "failed to flush stale session");
|
||||
}
|
||||
return Err(Redirect::to("/login").into_response());
|
||||
}
|
||||
Ok(Some(u)) => u,
|
||||
};
|
||||
|
||||
let session_kv: Option<i64> = match session.get::<i64>(SESSION_KEY_VERSION).await {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "failed to read key_version from session; treating as missing");
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(kv) = session_kv
|
||||
&& kv != user.key_version
|
||||
{
|
||||
tracing::info!(%user_id, session_kv = kv, db_kv = user.key_version, "key_version mismatch; invalidating session");
|
||||
if let Err(e) = session.flush().await {
|
||||
tracing::warn!(error = %e, "failed to flush outdated session");
|
||||
}
|
||||
return Err(Redirect::to("/login").into_response());
|
||||
}
|
||||
|
||||
Ok(user)
|
||||
}
|
||||
|
||||
fn request_user_agent(headers: &HeaderMap) -> Option<String> {
|
||||
headers
|
||||
.get(header::USER_AGENT)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
fn paginate(page: u32, total_count: i64, page_size: u32) -> (u32, u32, u32) {
|
||||
let page_size = page_size.max(1);
|
||||
let safe_total_count = u32::try_from(total_count.max(0)).unwrap_or(u32::MAX);
|
||||
let total_pages = safe_total_count.div_ceil(page_size).max(1);
|
||||
let current_page = page.max(1).min(total_pages);
|
||||
let offset = (current_page - 1).saturating_mul(page_size);
|
||||
(current_page, total_pages, offset)
|
||||
}
|
||||
|
||||
fn render_template<T: Template>(tmpl: T) -> Result<Response, StatusCode> {
|
||||
let html = tmpl.render().map_err(|e| {
|
||||
tracing::error!(error = %e, "template render error");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
Ok(Html(html).into_response())
|
||||
}
|
||||
|
||||
// ── Routes ────────────────────────────────────────────────────────────────────
|
||||
|
||||
pub fn web_router() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/robots.txt", get(assets::robots_txt))
|
||||
.route("/llms.txt", get(assets::llms_txt))
|
||||
.route("/ai.txt", get(assets::ai_txt))
|
||||
.route("/static/i18n.js", get(assets::i18n_js))
|
||||
.route("/favicon.svg", get(assets::favicon_svg))
|
||||
.route(
|
||||
"/favicon.ico",
|
||||
get(|| async { Redirect::permanent("/favicon.svg") }),
|
||||
)
|
||||
.route(
|
||||
"/.well-known/oauth-protected-resource",
|
||||
get(assets::oauth_protected_resource_metadata),
|
||||
)
|
||||
.route("/", get(auth::home_page))
|
||||
.route("/login", get(auth::login_page))
|
||||
.route("/auth/google", get(auth::auth_google))
|
||||
.route("/auth/google/callback", get(auth::auth_google_callback))
|
||||
.route("/auth/logout", post(auth::auth_logout))
|
||||
.route("/dashboard", get(account::dashboard))
|
||||
.route("/entries", get(entries::entries_page))
|
||||
.route("/audit", get(audit::audit_page))
|
||||
.route("/account/bind/google", get(auth::account_bind_google))
|
||||
.route("/account/unbind/{provider}", post(auth::account_unbind))
|
||||
.route("/api/key-salt", get(account::api_key_salt))
|
||||
.route("/api/key-setup", post(account::api_key_setup))
|
||||
.route("/api/key-change", post(account::api_key_change))
|
||||
.route("/api/apikey", get(account::api_apikey_get))
|
||||
.route(
|
||||
"/api/apikey/regenerate",
|
||||
post(account::api_apikey_regenerate),
|
||||
)
|
||||
.route(
|
||||
"/api/entries/{id}",
|
||||
patch(entries::api_entry_patch).delete(entries::api_entry_delete),
|
||||
)
|
||||
.route(
|
||||
"/api/entries/{entry_id}/secrets/{secret_id}",
|
||||
axum::routing::delete(entries::api_entry_secret_unlink),
|
||||
)
|
||||
.route(
|
||||
"/api/entries/{id}/secrets/decrypt",
|
||||
get(entries::api_entry_secrets_decrypt),
|
||||
)
|
||||
.route("/api/secrets/{secret_id}", patch(entries::api_secret_patch))
|
||||
.route(
|
||||
"/api/secrets/check-name",
|
||||
get(entries::api_secret_check_name),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn client_ip_ignores_forwarded_headers_without_trusted_proxy() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("x-forwarded-for", "203.0.113.10".parse().unwrap());
|
||||
|
||||
let ip = crate::client_ip::extract_client_ip_parts(
|
||||
&headers,
|
||||
SocketAddr::from(([127, 0, 0, 1], 9315)),
|
||||
);
|
||||
|
||||
assert_eq!(ip, "127.0.0.1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_ip_uses_valid_forwarded_header_with_trusted_proxy() {
|
||||
// This test relies on TRUST_PROXY being unset (default); skip if set in env
|
||||
if std::env::var("TRUST_PROXY").is_ok() {
|
||||
return;
|
||||
}
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("x-forwarded-for", "203.0.113.10, 10.0.0.1".parse().unwrap());
|
||||
|
||||
// Direct connection IP is used when TRUST_PROXY is not set
|
||||
let ip = crate::client_ip::extract_client_ip_parts(
|
||||
&headers,
|
||||
SocketAddr::from(([127, 0, 0, 1], 9315)),
|
||||
);
|
||||
|
||||
assert_eq!(ip, "127.0.0.1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_ui_lang_prefers_zh_cn_over_en_fallback() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(header::ACCEPT_LANGUAGE, "zh-CN, en;q=0.5".parse().unwrap());
|
||||
|
||||
assert!(matches!(request_ui_lang(&headers), UiLang::ZhCn));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_ui_lang_detects_traditional_chinese_variants() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::ACCEPT_LANGUAGE,
|
||||
"zh-Hant, en;q=0.5".parse().unwrap(),
|
||||
);
|
||||
|
||||
assert!(matches!(request_ui_lang(&headers), UiLang::ZhTw));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paginate_clamps_page_before_computing_offset() {
|
||||
let (current_page, total_pages, offset) = paginate(100, 12, 10);
|
||||
|
||||
assert_eq!(current_page, 2);
|
||||
assert_eq!(total_pages, 2);
|
||||
assert_eq!(offset, 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paginate_handles_large_page_without_overflow() {
|
||||
let (current_page, total_pages, offset) = paginate(u32::MAX, 1, ENTRIES_PAGE_LIMIT);
|
||||
|
||||
assert_eq!(current_page, 1);
|
||||
assert_eq!(total_pages, 1);
|
||||
assert_eq!(offset, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paginate_saturates_large_total_count() {
|
||||
let (_, total_pages, _) = paginate(1, i64::MAX, ENTRIES_PAGE_LIMIT);
|
||||
|
||||
assert_eq!(total_pages, u32::MAX.div_ceil(ENTRIES_PAGE_LIMIT));
|
||||
}
|
||||
}
|
||||
3
crates/secrets-mcp/static/favicon.svg
Normal file
3
crates/secrets-mcp/static/favicon.svg
Normal file
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
|
||||
<text x="16" y="23" text-anchor="middle" font-family="system-ui,Segoe UI,sans-serif" font-size="22" font-weight="700" fill="#58a6ff">S</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 212 B |
28
crates/secrets-mcp/static/llms.txt
Normal file
28
crates/secrets-mcp/static/llms.txt
Normal file
@@ -0,0 +1,28 @@
|
||||
# Secrets MCP
|
||||
|
||||
> 给 AI 与自动化工具的简要说明。本站是 **secrets-mcp**:Streamable HTTP **MCP**(Model Context Protocol)与 **Web 控制台** 的组合,用于在多租户场景下存储条目元数据与加密后的秘密字段;持久化在 PostgreSQL。用户通过 OAuth(如已配置)登录 Web;MCP 调用使用 API Key 与加密相关请求头。
|
||||
|
||||
## 公开页面
|
||||
|
||||
- **`/`**:公开首页,说明安全架构(客户端密钥派生、密文存储、多租户与审计等),无需登录。
|
||||
|
||||
## 不应抓取或索引的内容
|
||||
|
||||
- **`/mcp`**:MCP 流式 HTTP 端点(JSON-RPC 等),**不是** HTML 文档,也不适合作为公开知识库来源。
|
||||
- **`/api/*`**:会话或 API Key 相关的 HTTP API。
|
||||
- **`/login`**:登录入口页(`noindex` / robots 通常 disallow)。
|
||||
- **`/dashboard`、`/audit`、`/auth/*`、`/account/*`**:需浏览器会话,属于用户私有界面与 OAuth 流程。
|
||||
|
||||
## 给 AI 助手的实用提示
|
||||
|
||||
- 向用户说明连接方式时:MCP 基址为 `{BASE_URL}/mcp`(`BASE_URL` 由部署方设置),通常需要 `Authorization: Bearer <api_key>`;读写加密秘密时还需按部署文档传递 `X-Encryption-Key` 等头(与客户端模式有关)。
|
||||
- **不要编造**本实例的数据库 URL、OAuth 密钥、回调地址或任何凭据;一律以用户环境变量与运维文档为准。
|
||||
- Web 端在浏览器内用密码短语派生密钥完成端到端加密;MCP 路径下服务端可能在请求周期内临时使用客户端提供的密钥处理密文(架构细节见项目 README「加密架构」)。
|
||||
|
||||
## 延伸阅读
|
||||
|
||||
- 源码仓库:<https://gitea.refining.dev/refining/secrets>(`README.md`、`AGENTS.md` 含环境变量、表结构与运维约定)。
|
||||
|
||||
## 关于本文件
|
||||
|
||||
- 遵循常见的 **`/llms.txt`** 约定,便于人类与 LLM 快速了解站点性质与抓取边界;同文可在 **`/ai.txt`** 获取。
|
||||
31
crates/secrets-mcp/static/robots.txt
Normal file
31
crates/secrets-mcp/static/robots.txt
Normal file
@@ -0,0 +1,31 @@
|
||||
# Secrets MCP — robots.txt
|
||||
# 本站为需登录的私密控制台与 MCP API;以下路径请勿抓取,以免浪费配额并避免误索引敏感端点。
|
||||
# This host serves an authenticated dashboard and machine APIs; please skip crawling the paths below.
|
||||
|
||||
User-agent: *
|
||||
Disallow: /mcp
|
||||
Disallow: /api/
|
||||
Disallow: /dashboard
|
||||
Disallow: /audit
|
||||
Disallow: /auth/
|
||||
Disallow: /login
|
||||
Disallow: /account/
|
||||
|
||||
# 首页 `/` 为公开安全说明页,允许抓取。
|
||||
|
||||
# 面向 AI / LLM 的机器可读站点说明(Markdown):/llms.txt
|
||||
# Human & AI-readable site summary: /llms.txt (also /ai.txt)
|
||||
|
||||
User-agent: GPTBot
|
||||
User-agent: Google-Extended
|
||||
User-agent: anthropic-ai
|
||||
User-agent: Claude-Web
|
||||
User-agent: PerplexityBot
|
||||
User-agent: Bytespider
|
||||
Disallow: /mcp
|
||||
Disallow: /api/
|
||||
Disallow: /dashboard
|
||||
Disallow: /audit
|
||||
Disallow: /auth/
|
||||
Disallow: /login
|
||||
Disallow: /account/
|
||||
235
crates/secrets-mcp/templates/audit.html
Normal file
235
crates/secrets-mcp/templates/audit.html
Normal file
@@ -0,0 +1,235 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="icon" href="/favicon.svg?v={{ version }}" type="image/svg+xml">
|
||||
<title>Secrets — Audit</title>
|
||||
<style>
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600&family=Inter:wght@400;500;600&display=swap');
|
||||
:root {
|
||||
--bg: #0d1117; --surface: #161b22; --surface2: #21262d;
|
||||
--border: #30363d; --text: #e6edf3; --text-muted: #8b949e;
|
||||
--accent: #58a6ff; --accent-hover: #79b8ff;
|
||||
}
|
||||
body { background: var(--bg); color: var(--text); font-family: 'Inter', sans-serif; min-height: 100vh; }
|
||||
.layout { display: flex; min-height: 100vh; }
|
||||
.sidebar {
|
||||
width: 220px; flex-shrink: 0; background: var(--surface); border-right: 1px solid var(--border);
|
||||
padding: 24px 16px; display: flex; flex-direction: column; gap: 20px;
|
||||
}
|
||||
.sidebar-logo { font-family: 'JetBrains Mono', monospace; font-size: 16px; font-weight: 600;
|
||||
color: var(--text); text-decoration: none; padding: 0 10px; }
|
||||
.sidebar-logo span { color: var(--accent); }
|
||||
.sidebar-menu { display: flex; flex-direction: column; gap: 6px; }
|
||||
.sidebar-link {
|
||||
padding: 10px 12px; border-radius: 8px; color: var(--text-muted); text-decoration: none;
|
||||
border: 1px solid transparent; font-size: 13px; font-weight: 500;
|
||||
}
|
||||
.sidebar-link:hover { background: var(--surface2); color: var(--text); }
|
||||
.sidebar-link.active {
|
||||
background: rgba(88,166,255,0.12); color: var(--text); border-color: rgba(88,166,255,0.35);
|
||||
}
|
||||
.content-shell { flex: 1; min-width: 0; display: flex; flex-direction: column; }
|
||||
.topbar {
|
||||
background: var(--surface); border-bottom: 1px solid var(--border); padding: 0 24px;
|
||||
display: flex; align-items: center; gap: 12px; min-height: 52px;
|
||||
}
|
||||
.topbar-spacer { flex: 1; }
|
||||
.nav-user { font-size: 13px; color: var(--text-muted); }
|
||||
.lang-bar { display: flex; gap: 2px; background: var(--surface2); border-radius: 6px; padding: 2px; }
|
||||
.lang-btn { padding: 3px 9px; border: none; background: none; color: var(--text-muted);
|
||||
font-size: 12px; cursor: pointer; border-radius: 4px; }
|
||||
.lang-btn.active { background: var(--border); color: var(--text); }
|
||||
.btn-sign-out {
|
||||
padding: 5px 12px; border-radius: 6px; border: 1px solid var(--border);
|
||||
background: none; color: var(--text); font-size: 12px; text-decoration: none; cursor: pointer;
|
||||
}
|
||||
.btn-sign-out:hover { background: var(--surface2); }
|
||||
.main { padding: 32px 24px 40px; flex: 1; }
|
||||
.card { background: var(--surface); border: 1px solid var(--border); border-radius: 12px;
|
||||
padding: 24px; width: 100%; max-width: 1180px; margin: 0 auto; }
|
||||
.card-title-row {
|
||||
display: flex; align-items: center; flex-wrap: wrap; gap: 8px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.card-title { font-size: 20px; font-weight: 600; margin: 0; }
|
||||
.card-title-count {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 24px;
|
||||
padding: 0 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
background: var(--bg);
|
||||
color: var(--text-muted);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
}
|
||||
.empty { color: var(--text-muted); font-size: 14px; padding: 20px 0; }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th, td { text-align: left; vertical-align: top; padding: 12px 10px; border-top: 1px solid var(--border); }
|
||||
th { color: var(--text-muted); font-size: 12px; font-weight: 600; }
|
||||
td { font-size: 13px; }
|
||||
.mono { font-family: 'JetBrains Mono', monospace; }
|
||||
.detail {
|
||||
background: var(--bg); border: 1px solid var(--border); border-radius: 8px;
|
||||
padding: 10px; white-space: pre-wrap; word-break: break-word; font-size: 12px;
|
||||
max-width: 460px;
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.layout { flex-direction: column; }
|
||||
.sidebar {
|
||||
width: 100%; border-right: none; border-bottom: 1px solid var(--border);
|
||||
padding: 16px; gap: 14px;
|
||||
}
|
||||
.sidebar-menu { flex-direction: row; }
|
||||
.sidebar-link { flex: 1; text-align: center; }
|
||||
.main { padding: 20px 12px 28px; }
|
||||
.card { padding: 16px; }
|
||||
.topbar { padding: 12px 16px; flex-wrap: wrap; }
|
||||
table, thead, tbody, th, td, tr { display: block; }
|
||||
thead { display: none; }
|
||||
tr { border-top: 1px solid var(--border); padding: 12px 0; }
|
||||
td { border-top: none; padding: 6px 0; }
|
||||
td::before {
|
||||
display: block; color: var(--text-muted); font-size: 11px;
|
||||
margin-bottom: 4px; text-transform: uppercase;
|
||||
content: attr(data-label);
|
||||
}
|
||||
.detail { max-width: none; }
|
||||
}
|
||||
.pagination {
|
||||
display: flex; align-items: center; gap: 8px; margin-top: 20px;
|
||||
justify-content: center; padding: 12px 0;
|
||||
}
|
||||
.page-btn {
|
||||
padding: 6px 14px; border-radius: 6px; border: 1px solid var(--border);
|
||||
background: var(--surface); color: var(--text); text-decoration: none;
|
||||
font-size: 13px; cursor: pointer;
|
||||
}
|
||||
.page-btn:hover { background: var(--surface2); }
|
||||
.page-btn-disabled {
|
||||
padding: 6px 14px; border-radius: 6px; border: 1px solid var(--border);
|
||||
background: var(--surface); color: var(--text-muted); font-size: 13px;
|
||||
opacity: 0.5; cursor: not-allowed;
|
||||
}
|
||||
.page-info {
|
||||
color: var(--text-muted); font-size: 13px; font-family: 'JetBrains Mono', monospace;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="layout">
|
||||
<aside class="sidebar">
|
||||
<a href="/dashboard" class="sidebar-logo"><span>secrets</span></a>
|
||||
<nav class="sidebar-menu">
|
||||
<a href="/dashboard" class="sidebar-link" data-i18n="navMcp">MCP</a>
|
||||
<a href="/entries" class="sidebar-link" data-i18n="navEntries">条目</a>
|
||||
<a href="/audit" class="sidebar-link active" data-i18n="navAudit">审计</a>
|
||||
</nav>
|
||||
</aside>
|
||||
|
||||
<div class="content-shell">
|
||||
<div class="topbar">
|
||||
<span class="topbar-spacer"></span>
|
||||
<span class="nav-user">{{ user_name }}{% if !user_email.is_empty() %} · {{ user_email }}{% endif %}</span>
|
||||
<div class="lang-bar">
|
||||
<button class="lang-btn" onclick="setLang('zh-CN')">简</button>
|
||||
<button class="lang-btn" onclick="setLang('zh-TW')">繁</button>
|
||||
<button class="lang-btn" onclick="setLang('en')">EN</button>
|
||||
</div>
|
||||
<form action="/auth/logout" method="post" style="display:inline">
|
||||
<button type="submit" class="btn-sign-out" data-i18n="signOut">退出</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<main class="main">
|
||||
<section class="card">
|
||||
<div class="card-title-row">
|
||||
<div class="card-title" data-i18n="auditTitle">我的审计</div>
|
||||
<span class="card-title-count">{{ total_count }}</span>
|
||||
</div>
|
||||
|
||||
{% if entries.is_empty() %}
|
||||
<div class="empty" data-i18n="emptyAudit">暂无审计记录。</div>
|
||||
{% else %}
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th data-i18n="colTime">时间</th>
|
||||
<th data-i18n="colAction">动作</th>
|
||||
<th data-i18n="colTarget">目标</th>
|
||||
<th data-i18n="colDetail">详情</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for entry in entries %}
|
||||
<tr>
|
||||
<td class="col-time mono" data-label="时间"><time class="audit-local-time" datetime="{{ entry.created_at_iso }}">{{ entry.created_at_iso }}</time></td>
|
||||
<td class="col-action mono" data-label="动作">{{ entry.action }}</td>
|
||||
<td class="col-target mono" data-label="目标">{{ entry.target }}</td>
|
||||
<td class="col-detail" data-label="详情"><pre class="detail">{{ entry.detail }}</pre></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{% if total_count > 0 %}
|
||||
<div class="pagination">
|
||||
{% if current_page > 1 %}
|
||||
<a href="?page={{ current_page - 1 }}" class="page-btn" data-i18n="prevPage">上一页</a>
|
||||
{% else %}
|
||||
<span class="page-btn page-btn-disabled" data-i18n="prevPage">上一页</span>
|
||||
{% endif %}
|
||||
<span class="page-info">{{ current_page }} / {{ total_pages }}</span>
|
||||
{% if current_page < total_pages %}
|
||||
<a href="?page={{ current_page + 1 }}" class="page-btn" data-i18n="nextPage">下一页</a>
|
||||
{% else %}
|
||||
<span class="page-btn page-btn-disabled" data-i18n="nextPage">下一页</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/static/i18n.js"></script>
|
||||
<script>
|
||||
(function () {
|
||||
I18N_PAGE = {
|
||||
'zh-CN': { pageTitle: 'Secrets — 审计', auditTitle: '我的审计', emptyAudit: '暂无审计记录。', colTime: '时间', colAction: '动作', colTarget: '目标', colDetail: '详情', prevPage: '上一页', nextPage: '下一页' },
|
||||
'zh-TW': { pageTitle: 'Secrets — 審計', auditTitle: '我的審計', emptyAudit: '暫無審計記錄。', colTime: '時間', colAction: '動作', colTarget: '目標', colDetail: '詳情', prevPage: '上一頁', nextPage: '下一頁' },
|
||||
en: { pageTitle: 'Secrets — Audit', auditTitle: 'My audit', emptyAudit: 'No audit records.', colTime: 'Time', colAction: 'Action', colTarget: 'Target', colDetail: 'Detail', prevPage: 'Previous', nextPage: 'Next' }
|
||||
};
|
||||
|
||||
window.applyPageLang = function () {
|
||||
document.querySelectorAll('tbody tr').forEach(function (tr) {
|
||||
var time = tr.querySelector('.col-time');
|
||||
var action = tr.querySelector('.col-action');
|
||||
var target = tr.querySelector('.col-target');
|
||||
var detail = tr.querySelector('.col-detail');
|
||||
if (time) time.setAttribute('data-label', t('mobileLabelTime'));
|
||||
if (action) action.setAttribute('data-label', t('mobileLabelAction'));
|
||||
if (target) target.setAttribute('data-label', t('mobileLabelTarget'));
|
||||
if (detail) detail.setAttribute('data-label', t('mobileLabelDetail'));
|
||||
});
|
||||
};
|
||||
|
||||
document.querySelectorAll('time.audit-local-time[datetime]').forEach(function (el) {
|
||||
var raw = el.getAttribute('datetime');
|
||||
var d = raw ? new Date(raw) : null;
|
||||
if (d && !isNaN(d.getTime())) {
|
||||
el.textContent = d.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'medium' });
|
||||
el.title = raw + ' (UTC)';
|
||||
}
|
||||
});
|
||||
applyLang();
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
979
crates/secrets-mcp/templates/dashboard.html
Normal file
979
crates/secrets-mcp/templates/dashboard.html
Normal file
@@ -0,0 +1,979 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="icon" href="/favicon.svg?v={{ version }}" type="image/svg+xml">
|
||||
<title>Secrets</title>
|
||||
<style>
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600&family=Inter:wght@400;500;600&display=swap');
|
||||
:root {
|
||||
--bg: #0d1117; --surface: #161b22; --surface2: #21262d;
|
||||
--border: #30363d; --text: #e6edf3; --text-muted: #8b949e;
|
||||
--accent: #58a6ff; --accent-hover: #79b8ff;
|
||||
--danger: #f85149; --success: #3fb950; --warn: #d29922;
|
||||
}
|
||||
body { background: var(--bg); color: var(--text); font-family: 'Inter', sans-serif; min-height: 100vh; }
|
||||
|
||||
.layout { display: flex; min-height: 100vh; }
|
||||
.sidebar {
|
||||
width: 220px; flex-shrink: 0; background: var(--surface); border-right: 1px solid var(--border);
|
||||
padding: 24px 16px; display: flex; flex-direction: column; gap: 20px;
|
||||
}
|
||||
.sidebar-logo { font-family: 'JetBrains Mono', monospace; font-size: 16px; font-weight: 600;
|
||||
color: var(--text); text-decoration: none; padding: 0 10px; }
|
||||
.sidebar-logo span { color: var(--accent); }
|
||||
.sidebar-menu { display: flex; flex-direction: column; gap: 6px; }
|
||||
.sidebar-link {
|
||||
padding: 10px 12px; border-radius: 8px; color: var(--text-muted); text-decoration: none;
|
||||
border: 1px solid transparent; font-size: 13px; font-weight: 500;
|
||||
}
|
||||
.sidebar-link:hover { background: var(--surface2); color: var(--text); }
|
||||
.sidebar-link.active {
|
||||
background: rgba(88,166,255,0.12); color: var(--text); border-color: rgba(88,166,255,0.35);
|
||||
}
|
||||
.content-shell { flex: 1; min-width: 0; display: flex; flex-direction: column; }
|
||||
.topbar {
|
||||
background: var(--surface); border-bottom: 1px solid var(--border); padding: 0 24px;
|
||||
display: flex; align-items: center; gap: 12px; min-height: 52px;
|
||||
}
|
||||
.topbar-spacer { flex: 1; }
|
||||
.nav-user { font-size: 13px; color: var(--text-muted); }
|
||||
.lang-bar { display: flex; gap: 2px; background: var(--surface2); border-radius: 6px; padding: 2px; }
|
||||
.lang-btn { padding: 3px 9px; border: none; background: none; color: var(--text-muted);
|
||||
font-size: 12px; cursor: pointer; border-radius: 4px; }
|
||||
.lang-btn.active { background: var(--border); color: var(--text); }
|
||||
.btn-sign-out { padding: 5px 12px; border-radius: 6px; border: 1px solid var(--border);
|
||||
background: none; color: var(--text); font-size: 12px; cursor: pointer; }
|
||||
.btn-sign-out:hover { background: var(--surface2); }
|
||||
|
||||
/* Main content column */
|
||||
.main { display: flex; flex-direction: column; align-items: center;
|
||||
padding: 24px 20px 8px; min-height: 0; }
|
||||
.app-footer {
|
||||
margin-top: auto;
|
||||
text-align: center;
|
||||
padding: 4px 20px 12px;
|
||||
font-size: 12px;
|
||||
color: #9da7b3;
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
}
|
||||
.card { background: var(--surface); border: 1px solid var(--border); border-radius: 12px;
|
||||
padding: 24px; width: 100%; max-width: 980px; }
|
||||
.card-title { font-size: 18px; font-weight: 600; margin-bottom: 24px; }
|
||||
/* Form */
|
||||
.field { margin-bottom: 12px; }
|
||||
.field label { display: block; font-size: 12px; color: var(--text-muted); margin-bottom: 5px; }
|
||||
.field input { width: 100%; background: var(--bg); border: 1px solid var(--border);
|
||||
color: var(--text); padding: 9px 12px; border-radius: 6px;
|
||||
font-size: 13px; outline: none; }
|
||||
.field input:focus { border-color: var(--accent); }
|
||||
.pw-field { position: relative; }
|
||||
.pw-field > input { padding-right: 42px; }
|
||||
.pw-toggle {
|
||||
position: absolute; right: 6px; top: 50%; transform: translateY(-50%);
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
width: 32px; height: 32px; border: none; border-radius: 6px;
|
||||
background: transparent; color: var(--text-muted); cursor: pointer;
|
||||
}
|
||||
.pw-toggle:hover { color: var(--text); background: var(--surface2); }
|
||||
.pw-toggle:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.pw-icon svg { display: block; }
|
||||
.pw-icon.hidden { display: none; }
|
||||
.error-msg { color: var(--danger); font-size: 12px; margin-top: 6px; display: none; }
|
||||
|
||||
/* Buttons */
|
||||
.btn-primary { display: inline-flex; align-items: center; gap: 6px; width: 100%;
|
||||
justify-content: center; padding: 10px 20px; border-radius: 7px;
|
||||
border: none; background: var(--accent); color: #0d1117;
|
||||
font-size: 14px; font-weight: 600; cursor: pointer; transition: background 0.15s; }
|
||||
.btn-primary:hover { background: var(--accent-hover); }
|
||||
.btn-primary:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
.btn-sm { display: inline-flex; align-items: center; gap: 4px; padding: 5px 12px;
|
||||
border-radius: 5px; border: 1px solid var(--border); background: none;
|
||||
color: var(--text-muted); font-size: 12px; cursor: pointer; }
|
||||
.btn-sm:hover { color: var(--text); border-color: var(--text-muted); }
|
||||
.btn-copy { display: flex; align-items: center; gap: 8px; width: 100%; justify-content: center;
|
||||
padding: 11px 20px; border-radius: 7px; border: 1px solid var(--success);
|
||||
background: rgba(63,185,80,0.1); color: var(--success);
|
||||
font-size: 14px; font-weight: 600; cursor: pointer; transition: all 0.15s; }
|
||||
.btn-copy:hover { background: rgba(63,185,80,0.2); }
|
||||
.btn-copy.copied { background: var(--success); color: #0d1117; border-color: var(--success); }
|
||||
|
||||
/* Config format switcher */
|
||||
.config-tabs { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; margin-bottom: 12px; }
|
||||
.config-tab { padding: 12px 14px; border-radius: 10px; border: 1px solid var(--border);
|
||||
background: var(--surface2); color: var(--text-muted); cursor: pointer;
|
||||
font-family: inherit; text-align: left; transition: border-color 0.15s, background 0.15s, transform 0.15s; }
|
||||
.config-tab:hover { color: var(--text); border-color: var(--accent); transform: translateY(-1px); }
|
||||
.config-tab.active { background: rgba(88,166,255,0.1); color: var(--text); border-color: var(--accent); }
|
||||
.config-tab-title { display: block; font-size: 13px; font-weight: 600; color: inherit; }
|
||||
/* Config box */
|
||||
.config-wrap { position: relative; margin-bottom: 14px; }
|
||||
.config-box { background: var(--bg); border: 1px solid var(--border); border-radius: 8px;
|
||||
padding: 16px; font-family: 'JetBrains Mono', monospace; font-size: 11px;
|
||||
line-height: 1.7; color: var(--text); overflow-x: auto; white-space: pre; }
|
||||
.config-box.locked { color: var(--text-muted); filter: blur(3px); user-select: none;
|
||||
pointer-events: none; }
|
||||
.config-key { color: #79c0ff; }
|
||||
.config-str { color: #a5d6ff; }
|
||||
.config-val { color: var(--accent); }
|
||||
|
||||
/* Divider */
|
||||
.divider { border: none; border-top: 1px solid var(--border); margin: 20px 0; }
|
||||
|
||||
/* Actions row */
|
||||
.actions-row { display: flex; gap: 8px; flex-wrap: wrap; justify-content: center; }
|
||||
|
||||
/* Spinner */
|
||||
.spinner { display: inline-block; width: 14px; height: 14px; border: 2px solid rgba(13,17,23,0.3);
|
||||
border-top-color: #0d1117; border-radius: 50%; animation: spin 0.7s linear infinite; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
|
||||
/* Modal */
|
||||
.modal-bd { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.75);
|
||||
z-index: 100; align-items: center; justify-content: center; }
|
||||
.modal-bd.open { display: flex; }
|
||||
.modal { background: var(--surface); border: 1px solid var(--border); border-radius: 12px;
|
||||
padding: 28px; width: 100%; max-width: 420px; }
|
||||
.modal h3 { font-size: 16px; font-weight: 600; margin-bottom: 16px; }
|
||||
.modal-actions { display: flex; gap: 8px; margin-top: 16px; }
|
||||
.btn-modal-ok { flex: 1; padding: 8px; border-radius: 6px; border: none;
|
||||
background: var(--accent); color: #0d1117; font-size: 13px;
|
||||
font-weight: 600; cursor: pointer; }
|
||||
.btn-modal-ok:hover { background: var(--accent-hover); }
|
||||
.btn-modal-cancel { padding: 8px 16px; border-radius: 6px; border: 1px solid var(--border);
|
||||
background: none; color: var(--text); font-size: 13px; cursor: pointer; }
|
||||
.btn-modal-cancel:hover { background: var(--surface2); }
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.layout { flex-direction: column; }
|
||||
.sidebar {
|
||||
width: 100%; border-right: none; border-bottom: 1px solid var(--border);
|
||||
padding: 16px; gap: 14px;
|
||||
}
|
||||
.sidebar-menu { flex-direction: row; }
|
||||
.sidebar-link { flex: 1; text-align: center; }
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.config-tabs { grid-template-columns: 1fr; }
|
||||
.topbar { padding: 12px 16px; flex-wrap: wrap; }
|
||||
.main { padding: 16px 12px 6px; }
|
||||
.app-footer { padding: 4px 12px 10px; }
|
||||
.card { padding: 18px; }
|
||||
}
|
||||
|
||||
</style>
|
||||
</head>
|
||||
<body data-has-passphrase="{{ has_passphrase }}" data-base-url="{{ base_url }}">
|
||||
|
||||
<div class="layout">
|
||||
<aside class="sidebar">
|
||||
<a href="/dashboard" class="sidebar-logo"><span>secrets</span></a>
|
||||
<nav class="sidebar-menu">
|
||||
<a href="/dashboard" class="sidebar-link active">MCP</a>
|
||||
<a href="/entries" class="sidebar-link">条目</a>
|
||||
<a href="/audit" class="sidebar-link">审计</a>
|
||||
</nav>
|
||||
</aside>
|
||||
|
||||
<div class="content-shell">
|
||||
<div class="topbar">
|
||||
<span class="topbar-spacer"></span>
|
||||
<span class="nav-user">{{ user_name }}{% if !user_email.is_empty() %} · {{ user_email }}{% endif %}</span>
|
||||
<div class="lang-bar">
|
||||
<button class="lang-btn" onclick="setLang('zh-CN')">简</button>
|
||||
<button class="lang-btn" onclick="setLang('zh-TW')">繁</button>
|
||||
<button class="lang-btn" onclick="setLang('en')">EN</button>
|
||||
</div>
|
||||
<form action="/auth/logout" method="post" style="display:inline">
|
||||
<button type="submit" class="btn-sign-out" data-i18n="signOut">退出</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="main">
|
||||
<div class="card">
|
||||
|
||||
<!-- ── Locked state ──────────────────────────────────────────────────── -->
|
||||
<div id="locked-view">
|
||||
<div class="card-title" data-i18n="lockedTitle">获取 MCP 配置</div>
|
||||
|
||||
<!-- placeholder config -->
|
||||
<div class="config-wrap">
|
||||
<div class="config-box locked" id="placeholder-config"></div>
|
||||
</div>
|
||||
|
||||
<!-- Setup form (no passphrase yet) -->
|
||||
<div id="setup-form" style="display:none">
|
||||
<div class="field">
|
||||
<label data-i18n="labelPassphrase">加密密码</label>
|
||||
<div class="pw-field">
|
||||
<input type="password" id="setup-pass1" data-i18n-ph="phPassphrase" autocomplete="new-password">
|
||||
<button type="button" class="pw-toggle" data-target="setup-pass1" aria-pressed="false"
|
||||
onclick="togglePwVisibility(this)" aria-label="">
|
||||
<span class="pw-icon pw-icon-show" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span>
|
||||
<span class="pw-icon pw-icon-hide hidden" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg></span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label data-i18n="labelConfirm">确认密码</label>
|
||||
<div class="pw-field">
|
||||
<input type="password" id="setup-pass2" data-i18n-ph="phConfirm" autocomplete="new-password">
|
||||
<button type="button" class="pw-toggle" data-target="setup-pass2" aria-pressed="false"
|
||||
onclick="togglePwVisibility(this)" aria-label="">
|
||||
<span class="pw-icon pw-icon-show" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span>
|
||||
<span class="pw-icon pw-icon-hide hidden" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg></span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="error-msg" id="setup-error"></div>
|
||||
<button class="btn-primary" id="setup-btn" onclick="doSetup()">
|
||||
<span data-i18n="btnSetup">设置并获取配置</span>
|
||||
</button>
|
||||
<p style="font-size:11px;color:var(--text-muted);text-align:center;margin-top:10px" data-i18n="setupNote">
|
||||
密码不会上传服务器。遗忘后数据将无法恢复。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Unlock form (passphrase already set) -->
|
||||
<div id="unlock-form" style="display:none">
|
||||
<div class="field">
|
||||
<label data-i18n="labelPassphrase">加密密码</label>
|
||||
<div class="pw-field">
|
||||
<input type="password" id="unlock-pass" data-i18n-ph="phPassphrase" autocomplete="current-password">
|
||||
<button type="button" class="pw-toggle" data-target="unlock-pass" aria-pressed="false"
|
||||
onclick="togglePwVisibility(this)" aria-label="">
|
||||
<span class="pw-icon pw-icon-show" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span>
|
||||
<span class="pw-icon pw-icon-hide hidden" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg></span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="error-msg" id="unlock-error"></div>
|
||||
<button class="btn-primary" id="unlock-btn" onclick="doUnlock()">
|
||||
<span data-i18n="btnUnlock">解锁并获取配置</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Unlocked state ────────────────────────────────────────────────── -->
|
||||
<div id="unlocked-view" style="display:none">
|
||||
<div class="card-title" data-i18n="unlockedTitle" style="margin-bottom:16px">MCP 配置</div>
|
||||
|
||||
<div class="config-tabs" role="tablist" aria-label="Config format">
|
||||
<button type="button" class="config-tab active" role="tab" id="tab-mcp" aria-selected="true"
|
||||
onclick="setConfigFormat('mcp')">
|
||||
<span class="config-tab-title" data-i18n="tabMcp">Cursor、Claude Code、Codex、Gemini CLI</span>
|
||||
</button>
|
||||
<button type="button" class="config-tab" role="tab" id="tab-opencode" aria-selected="false"
|
||||
onclick="setConfigFormat('opencode')">
|
||||
<span class="config-tab-title" data-i18n="tabOpencode">OpenCode</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="config-wrap">
|
||||
<pre class="config-box" id="real-config"></pre>
|
||||
</div>
|
||||
|
||||
<div style="display:flex;gap:10px;flex-wrap:wrap">
|
||||
<button class="btn-copy" id="copy-full-btn" onclick="copyFullConfig()" style="flex:1">
|
||||
<span id="copy-full-text">复制完整 mcp.json</span>
|
||||
</button>
|
||||
<button class="btn-copy" id="copy-secrets-btn" onclick="copySecretsConfig()" style="flex:1">
|
||||
<span id="copy-secrets-text">仅复制 secrets 节点</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<hr class="divider">
|
||||
|
||||
<div class="actions-row">
|
||||
<button class="btn-sm" onclick="clearAndLock()" data-i18n="btnClear">清除密钥</button>
|
||||
<button class="btn-sm" onclick="openChangeModal()" data-i18n="btnChangePass">更换密码</button>
|
||||
<button class="btn-sm" onclick="confirmRegenerate()" data-i18n="btnRegen">重置 API Key</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
<footer class="app-footer">{{ version }}</footer>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Change passphrase modal ──────────────────────────────────────────────── -->
|
||||
<div class="modal-bd" id="change-modal">
|
||||
<div class="modal">
|
||||
<h3 data-i18n="changeTitle">更换密码</h3>
|
||||
<div class="field">
|
||||
<label data-i18n="labelCurrent">当前密码</label>
|
||||
<div class="pw-field">
|
||||
<input type="password" id="change-pass-old" data-i18n-ph="phCurrent" autocomplete="current-password">
|
||||
<button type="button" class="pw-toggle" data-target="change-pass-old" aria-pressed="false"
|
||||
onclick="togglePwVisibility(this)" aria-label="">
|
||||
<span class="pw-icon pw-icon-show" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span>
|
||||
<span class="pw-icon pw-icon-hide hidden" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg></span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label data-i18n="labelNew">新密码</label>
|
||||
<div class="pw-field">
|
||||
<input type="password" id="change-pass1" data-i18n-ph="phPassphrase" autocomplete="new-password">
|
||||
<button type="button" class="pw-toggle" data-target="change-pass1" aria-pressed="false"
|
||||
onclick="togglePwVisibility(this)" aria-label="">
|
||||
<span class="pw-icon pw-icon-show" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span>
|
||||
<span class="pw-icon pw-icon-hide hidden" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg></span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label data-i18n="labelConfirm">确认</label>
|
||||
<div class="pw-field">
|
||||
<input type="password" id="change-pass2" data-i18n-ph="phConfirm" autocomplete="new-password">
|
||||
<button type="button" class="pw-toggle" data-target="change-pass2" aria-pressed="false"
|
||||
onclick="togglePwVisibility(this)" aria-label="">
|
||||
<span class="pw-icon pw-icon-show" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span>
|
||||
<span class="pw-icon pw-icon-hide hidden" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg></span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="error-msg" id="change-error"></div>
|
||||
<div class="modal-actions">
|
||||
<button class="btn-modal-ok" id="change-btn" onclick="doChange()" data-i18n="btnChange">确认更换</button>
|
||||
<button class="btn-modal-cancel" onclick="closeChangeModal()" data-i18n="btnCancel">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// ── i18n ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
const T = {
|
||||
'zh-CN': {
|
||||
signOut: '退出',
|
||||
lockedTitle: '获取 MCP 配置',
|
||||
labelPassphrase: '加密密码',
|
||||
labelConfirm: '确认密码',
|
||||
labelNew: '新密码',
|
||||
labelCurrent: '当前密码',
|
||||
phPassphrase: '输入密码…',
|
||||
phConfirm: '再次输入…',
|
||||
phCurrent: '输入当前密码…',
|
||||
btnSetup: '设置并获取配置',
|
||||
btnUnlock: '解锁并获取配置',
|
||||
setupNote: '密码不会上传服务器。遗忘后数据将无法恢复。',
|
||||
errEmpty: '密码不能为空。',
|
||||
errShort: '密码至少需要 8 个字符。',
|
||||
errMismatch: '两次输入不一致。',
|
||||
errWrong: '密码错误,请重试。',
|
||||
errWrongOld: '当前密码错误,请重试。',
|
||||
unlockedTitle: 'MCP 配置',
|
||||
tabMcp: 'Cursor、Claude Code、Codex、Gemini CLI',
|
||||
tabOpencode: 'OpenCode',
|
||||
btnCopyFull: '复制完整 mcp.json',
|
||||
btnCopySecrets: '仅复制 secrets 节点',
|
||||
btnCopyFullOpencode: '复制完整 mcp.json',
|
||||
btnCopySecretsOpencode: '仅复制 secrets 节点',
|
||||
btnCopied: '已复制!',
|
||||
btnClear: '清除密钥',
|
||||
btnChangePass: '更换密码',
|
||||
btnRegen: '重置 API Key',
|
||||
changeTitle: '更换密码',
|
||||
btnChange: '确认更换',
|
||||
btnCancel: '取消',
|
||||
regenConfirm: '重置 API Key 后,当前 Key 立即失效,需同步更新 AI 客户端配置。确认继续?',
|
||||
regenFailed: '重置失败,请刷新页面重试。',
|
||||
ariaShowPw: '显示密码',
|
||||
ariaHidePw: '隐藏密码',
|
||||
},
|
||||
'zh-TW': {
|
||||
signOut: '登出',
|
||||
lockedTitle: '取得 MCP 設定',
|
||||
labelPassphrase: '加密密碼',
|
||||
labelConfirm: '確認密碼',
|
||||
labelNew: '新密碼',
|
||||
labelCurrent: '目前密碼',
|
||||
phPassphrase: '輸入密碼…',
|
||||
phConfirm: '再次輸入…',
|
||||
phCurrent: '輸入目前密碼…',
|
||||
btnSetup: '設定並取得設定',
|
||||
btnUnlock: '解鎖並取得設定',
|
||||
setupNote: '密碼不會上傳伺服器。遺忘後資料將無法復原。',
|
||||
errEmpty: '密碼不能為空。',
|
||||
errShort: '密碼至少需要 8 個字元。',
|
||||
errMismatch: '兩次輸入不一致。',
|
||||
errWrong: '密碼錯誤,請重試。',
|
||||
errWrongOld: '目前密碼錯誤,請重試。',
|
||||
unlockedTitle: 'MCP 設定',
|
||||
tabMcp: 'Cursor、Claude Code、Codex、Gemini CLI',
|
||||
tabOpencode: 'OpenCode',
|
||||
btnCopyFull: '複製完整 mcp.json',
|
||||
btnCopySecrets: '僅複製 secrets 節點',
|
||||
btnCopyFullOpencode: '複製完整 mcp.json',
|
||||
btnCopySecretsOpencode: '僅複製 secrets 節點',
|
||||
btnCopied: '已複製!',
|
||||
btnClear: '清除密鑰',
|
||||
btnChangePass: '更換密碼',
|
||||
btnRegen: '重置 API Key',
|
||||
changeTitle: '更換密碼',
|
||||
btnChange: '確認更換',
|
||||
btnCancel: '取消',
|
||||
regenConfirm: '重置 API Key 後,目前 Key 立即失效,需同步更新 AI 用戶端設定。確認繼續?',
|
||||
regenFailed: '重置失敗,請重新整理頁面再試。',
|
||||
ariaShowPw: '顯示密碼',
|
||||
ariaHidePw: '隱藏密碼',
|
||||
},
|
||||
'en': {
|
||||
signOut: 'Sign out',
|
||||
lockedTitle: 'Get MCP Config',
|
||||
labelPassphrase: 'Encryption password',
|
||||
labelConfirm: 'Confirm password',
|
||||
labelNew: 'New password',
|
||||
labelCurrent: 'Current password',
|
||||
phPassphrase: 'Enter password…',
|
||||
phConfirm: 'Repeat password…',
|
||||
phCurrent: 'Enter current password…',
|
||||
btnSetup: 'Set up & get config',
|
||||
btnUnlock: 'Unlock & get config',
|
||||
setupNote: 'Your password never leaves this device. If forgotten, encrypted data cannot be recovered.',
|
||||
errEmpty: 'Password cannot be empty.',
|
||||
errShort: 'Password must be at least 8 characters.',
|
||||
errMismatch: 'Passwords do not match.',
|
||||
errWrong: 'Incorrect password, please try again.',
|
||||
errWrongOld: 'Current password is incorrect, please try again.',
|
||||
unlockedTitle: 'MCP Config',
|
||||
tabMcp: 'Cursor, Claude Code, Codex, Gemini CLI',
|
||||
tabOpencode: 'OpenCode',
|
||||
btnCopyFull: 'Copy full mcp.json',
|
||||
btnCopySecrets: 'Copy only secrets node',
|
||||
btnCopyFullOpencode: 'Copy full mcp.json',
|
||||
btnCopySecretsOpencode: 'Copy only secrets node',
|
||||
btnCopied: 'Copied!',
|
||||
btnClear: 'Clear key',
|
||||
btnChangePass: 'Change password',
|
||||
btnRegen: 'Reset API key',
|
||||
changeTitle: 'Change password',
|
||||
btnChange: 'Confirm',
|
||||
btnCancel: 'Cancel',
|
||||
regenConfirm: 'Resetting will immediately invalidate your current API key. You will need to update your AI client config. Continue?',
|
||||
regenFailed: 'Reset failed. Please refresh and try again.',
|
||||
ariaShowPw: 'Show password',
|
||||
ariaHidePw: 'Hide password',
|
||||
}
|
||||
};
|
||||
|
||||
let currentLang = localStorage.getItem('lang') || 'zh-CN';
|
||||
|
||||
function t(key) { return T[currentLang][key] || T['en'][key] || key; }
|
||||
|
||||
function applyLang() {
|
||||
document.documentElement.lang = currentLang;
|
||||
document.querySelectorAll('[data-i18n]').forEach(el => {
|
||||
const key = el.getAttribute('data-i18n');
|
||||
el.textContent = t(key);
|
||||
});
|
||||
document.querySelectorAll('[data-i18n-ph]').forEach(el => {
|
||||
el.placeholder = t(el.getAttribute('data-i18n-ph'));
|
||||
});
|
||||
document.querySelectorAll('.lang-btn').forEach(btn => {
|
||||
const map = { 'zh-CN': '简', 'zh-TW': '繁', 'en': 'EN' };
|
||||
btn.classList.toggle('active', btn.textContent === map[currentLang]);
|
||||
});
|
||||
// Rebuild placeholder config (language affects nothing but triggers re-render)
|
||||
renderPlaceholderConfig();
|
||||
// Rebuild real config if unlocked
|
||||
if (currentEncKey && currentApiKey) renderRealConfig();
|
||||
syncPwToggleI18n();
|
||||
syncConfigFormatUi();
|
||||
}
|
||||
|
||||
function setLang(lang) {
|
||||
currentLang = lang;
|
||||
localStorage.setItem('lang', lang);
|
||||
applyLang();
|
||||
}
|
||||
|
||||
function syncPwToggleI18n() {
|
||||
document.querySelectorAll('.pw-toggle').forEach(btn => {
|
||||
const input = document.getElementById(btn.getAttribute('data-target'));
|
||||
if (!input) return;
|
||||
const visible = input.type === 'text';
|
||||
btn.setAttribute('aria-pressed', visible ? 'true' : 'false');
|
||||
btn.setAttribute('aria-label', visible ? t('ariaHidePw') : t('ariaShowPw'));
|
||||
const showIc = btn.querySelector('.pw-icon-show');
|
||||
const hideIc = btn.querySelector('.pw-icon-hide');
|
||||
if (showIc) showIc.classList.toggle('hidden', visible);
|
||||
if (hideIc) hideIc.classList.toggle('hidden', !visible);
|
||||
});
|
||||
}
|
||||
|
||||
function togglePwVisibility(btn) {
|
||||
const input = document.getElementById(btn.getAttribute('data-target'));
|
||||
if (!input) return;
|
||||
input.type = input.type === 'password' ? 'text' : 'password';
|
||||
syncPwToggleI18n();
|
||||
}
|
||||
|
||||
// ── Constants ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const HAS_PASSPHRASE = document.body.dataset.hasPassphrase === 'true';
|
||||
const BASE_URL = document.body.dataset.baseUrl;
|
||||
const KEY_CHECK_PLAINTEXT = 'secrets-mcp-key-check';
|
||||
const PBKDF2_ITERATIONS = 600000;
|
||||
const ENC = new TextEncoder();
|
||||
let currentEncKey = null;
|
||||
let currentApiKey = null;
|
||||
/** @type {'mcp' | 'opencode'} */
|
||||
let configFormat = 'mcp';
|
||||
|
||||
function redirectLoginExpired() {
|
||||
sessionStorage.removeItem('enc_key');
|
||||
currentEncKey = null;
|
||||
currentApiKey = null;
|
||||
window.location.replace('/');
|
||||
}
|
||||
|
||||
/** Like fetch; on 401 clears local state and navigates to login (await does not complete). */
|
||||
async function fetchAuth(input, init) {
|
||||
const resp = await fetch(input, init);
|
||||
if (resp.status === 401) {
|
||||
redirectLoginExpired();
|
||||
await new Promise(() => {});
|
||||
}
|
||||
return resp;
|
||||
}
|
||||
|
||||
// ── Placeholder config ─────────────────────────────────────────────────────────
|
||||
|
||||
function renderPlaceholderConfig() {
|
||||
document.getElementById('placeholder-config').textContent =
|
||||
buildConfigText('sk_' + '•'.repeat(64), '•'.repeat(64));
|
||||
}
|
||||
|
||||
function buildBaseServerConfig(apiKey, encKey) {
|
||||
return {
|
||||
url: BASE_URL + '/mcp',
|
||||
headers: {
|
||||
Authorization: 'Bearer ' + apiKey,
|
||||
'X-Encryption-Key': encKey
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function buildSecretsEntryObject(apiKey, encKey) {
|
||||
return buildBaseServerConfig(apiKey, encKey);
|
||||
}
|
||||
|
||||
function buildConfigText(apiKey, encKey) {
|
||||
return JSON.stringify({ mcpServers: { secrets: buildSecretsEntryObject(apiKey, encKey) } }, null, 2);
|
||||
}
|
||||
|
||||
function buildSecretsConfigText(apiKey, encKey) {
|
||||
const wrapped = JSON.stringify({
|
||||
secrets: buildSecretsEntryObject(apiKey, encKey)
|
||||
}, null, 2);
|
||||
const lines = wrapped.split('\n');
|
||||
return lines.length < 3 ? wrapped : lines.slice(1, -1).join('\n');
|
||||
}
|
||||
|
||||
/** OpenCode: local stdio bridge to Streamable HTTP MCP (mcp-remote --transport http-only). */
|
||||
function buildOpencodeEntry(apiKey, encKey) {
|
||||
return {
|
||||
type: 'local',
|
||||
command: [
|
||||
'npx', '-y', 'mcp-remote',
|
||||
BASE_URL + '/mcp',
|
||||
'--header',
|
||||
'Authorization: Bearer ' + apiKey,
|
||||
'--header',
|
||||
'X-Encryption-Key: ' + encKey,
|
||||
'--transport',
|
||||
'http-only'
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
/** Full OpenCode config: MCP servers live under top-level `mcp`. */
|
||||
function buildOpencodeConfigText(apiKey, encKey) {
|
||||
return JSON.stringify({ mcp: { secrets: buildOpencodeEntry(apiKey, encKey) } }, null, 2);
|
||||
}
|
||||
|
||||
/** Strip outer `{` `}` so user can paste `secrets` under an existing `mcp` object. */
|
||||
function buildOpencodeMergeSnippet(apiKey, encKey) {
|
||||
const wrapped = JSON.stringify({ secrets: buildOpencodeEntry(apiKey, encKey) }, null, 2);
|
||||
const lines = wrapped.split('\n');
|
||||
return lines.length < 3 ? wrapped : lines.slice(1, -1).join('\n');
|
||||
}
|
||||
|
||||
function getCopyFullKey() {
|
||||
return 'btnCopyFull';
|
||||
}
|
||||
|
||||
function getCopySecretsKey() {
|
||||
return 'btnCopySecrets';
|
||||
}
|
||||
|
||||
const CONFIG_FORMAT_STORAGE = 'dash_config_format';
|
||||
|
||||
function setConfigFormat(fmt) {
|
||||
configFormat = fmt;
|
||||
try { sessionStorage.setItem(CONFIG_FORMAT_STORAGE, fmt); } catch (_) {}
|
||||
syncConfigFormatUi();
|
||||
if (currentEncKey && currentApiKey) renderRealConfig();
|
||||
}
|
||||
|
||||
/** Refresh tabs, format hint, and copy button labels (after language change or tab switch). */
|
||||
function syncConfigFormatUi() {
|
||||
const uv = document.getElementById('unlocked-view');
|
||||
if (!uv || uv.style.display === 'none') return;
|
||||
const tabMcp = document.getElementById('tab-mcp');
|
||||
const tabOc = document.getElementById('tab-opencode');
|
||||
if (tabMcp && tabOc) {
|
||||
tabMcp.classList.toggle('active', configFormat === 'mcp');
|
||||
tabOc.classList.toggle('active', configFormat === 'opencode');
|
||||
tabMcp.setAttribute('aria-selected', configFormat === 'mcp' ? 'true' : 'false');
|
||||
tabOc.setAttribute('aria-selected', configFormat === 'opencode' ? 'true' : 'false');
|
||||
}
|
||||
const cf = document.getElementById('copy-full-text');
|
||||
const cs = document.getElementById('copy-secrets-text');
|
||||
if (cf) cf.textContent = t(getCopyFullKey());
|
||||
if (cs) cs.textContent = t(getCopySecretsKey());
|
||||
}
|
||||
|
||||
// ── Unlock / Setup flow ───────────────────────────────────────────────────────
|
||||
|
||||
function showLockedView() {
|
||||
document.getElementById('locked-view').style.display = '';
|
||||
document.getElementById('unlocked-view').style.display = 'none';
|
||||
if (HAS_PASSPHRASE) {
|
||||
document.getElementById('setup-form').style.display = 'none';
|
||||
document.getElementById('unlock-form').style.display = '';
|
||||
setTimeout(() => document.getElementById('unlock-pass').focus(), 50);
|
||||
} else {
|
||||
document.getElementById('setup-form').style.display = '';
|
||||
document.getElementById('unlock-form').style.display = 'none';
|
||||
setTimeout(() => document.getElementById('setup-pass1').focus(), 50);
|
||||
}
|
||||
}
|
||||
|
||||
async function showUnlockedView(encKeyHex, apiKey) {
|
||||
currentEncKey = encKeyHex;
|
||||
currentApiKey = apiKey;
|
||||
sessionStorage.setItem('enc_key', encKeyHex);
|
||||
renderRealConfig();
|
||||
document.getElementById('locked-view').style.display = 'none';
|
||||
document.getElementById('unlocked-view').style.display = '';
|
||||
syncConfigFormatUi();
|
||||
}
|
||||
|
||||
function renderRealConfig() {
|
||||
if (!currentApiKey || !currentEncKey) return;
|
||||
const text = configFormat === 'mcp'
|
||||
? buildConfigText(currentApiKey, currentEncKey)
|
||||
: buildOpencodeConfigText(currentApiKey, currentEncKey);
|
||||
document.getElementById('real-config').textContent = text;
|
||||
}
|
||||
|
||||
function clearAndLock() {
|
||||
sessionStorage.removeItem('enc_key');
|
||||
currentEncKey = null;
|
||||
currentApiKey = null;
|
||||
showLockedView();
|
||||
}
|
||||
|
||||
// ── Web Crypto helpers ─────────────────────────────────────────────────────────
|
||||
|
||||
async function deriveKey(passphrase, saltBytes, extractable = false) {
|
||||
const km = await crypto.subtle.importKey('raw', ENC.encode(passphrase), 'PBKDF2', false, ['deriveKey']);
|
||||
return crypto.subtle.deriveKey(
|
||||
{ name: 'PBKDF2', salt: saltBytes, iterations: PBKDF2_ITERATIONS, hash: 'SHA-256' },
|
||||
km, { name: 'AES-GCM', length: 256 }, extractable, ['encrypt', 'decrypt']
|
||||
);
|
||||
}
|
||||
|
||||
async function exportKeyHex(cryptoKey) {
|
||||
const raw = await crypto.subtle.exportKey('raw', cryptoKey);
|
||||
return Array.from(new Uint8Array(raw)).map(b => b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
|
||||
function hexToBytes(hex) {
|
||||
const b = new Uint8Array(hex.length / 2);
|
||||
for (let i = 0; i < hex.length; i += 2) b[i / 2] = parseInt(hex.slice(i, i + 2), 16);
|
||||
return b;
|
||||
}
|
||||
|
||||
function bytesToHex(bytes) {
|
||||
return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
|
||||
async function encryptKeyCheck(cryptoKey) {
|
||||
const nonce = crypto.getRandomValues(new Uint8Array(12));
|
||||
const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce }, cryptoKey, ENC.encode(KEY_CHECK_PLAINTEXT));
|
||||
const out = new Uint8Array(12 + ct.byteLength);
|
||||
out.set(nonce); out.set(new Uint8Array(ct), 12);
|
||||
return bytesToHex(out);
|
||||
}
|
||||
|
||||
async function verifyKeyCheck(cryptoKey, keyCheckHex) {
|
||||
try {
|
||||
const b = hexToBytes(keyCheckHex);
|
||||
const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: b.slice(0, 12) }, cryptoKey, b.slice(12));
|
||||
return new TextDecoder().decode(plain) === KEY_CHECK_PLAINTEXT;
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
// ── Passphrase setup (first time) ─────────────────────────────────────────────
|
||||
|
||||
function setBtnLoading(id, loading, labelKey) {
|
||||
const btn = document.getElementById(id);
|
||||
btn.disabled = loading;
|
||||
btn.innerHTML = loading
|
||||
? '<span class="spinner"></span>'
|
||||
: `<span data-i18n="${labelKey}">${t(labelKey)}</span>`;
|
||||
}
|
||||
|
||||
async function doSetup() {
|
||||
const pass1 = document.getElementById('setup-pass1').value;
|
||||
const pass2 = document.getElementById('setup-pass2').value;
|
||||
const errEl = document.getElementById('setup-error');
|
||||
errEl.style.display = 'none';
|
||||
|
||||
if (!pass1) { showErr(errEl, t('errEmpty')); return; }
|
||||
if (pass1.length < 8) { showErr(errEl, t('errShort')); return; }
|
||||
if (pass1 !== pass2) { showErr(errEl, t('errMismatch')); return; }
|
||||
|
||||
setBtnLoading('setup-btn', true, 'btnSetup');
|
||||
try {
|
||||
const salt = crypto.getRandomValues(new Uint8Array(32));
|
||||
const cryptoKey = await deriveKey(pass1, salt, true);
|
||||
const keyCheckHex = await encryptKeyCheck(cryptoKey);
|
||||
const hexKey = await exportKeyHex(cryptoKey);
|
||||
|
||||
const resp = await fetchAuth('/api/key-setup', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
salt: bytesToHex(salt),
|
||||
key_check: keyCheckHex,
|
||||
params: { alg: 'pbkdf2-sha256', iterations: PBKDF2_ITERATIONS }
|
||||
})
|
||||
});
|
||||
if (!resp.ok) throw new Error('HTTP ' + resp.status);
|
||||
|
||||
const apiKey = await fetchApiKey();
|
||||
await showUnlockedView(hexKey, apiKey);
|
||||
} catch (e) {
|
||||
showErr(errEl, 'Error: ' + e.message);
|
||||
} finally {
|
||||
setBtnLoading('setup-btn', false, 'btnSetup');
|
||||
}
|
||||
}
|
||||
|
||||
// ── Passphrase unlock ──────────────────────────────────────────────────────────
|
||||
|
||||
async function doUnlock() {
|
||||
const pass = document.getElementById('unlock-pass').value;
|
||||
const errEl = document.getElementById('unlock-error');
|
||||
errEl.style.display = 'none';
|
||||
|
||||
if (!pass) { showErr(errEl, t('errEmpty')); return; }
|
||||
|
||||
setBtnLoading('unlock-btn', true, 'btnUnlock');
|
||||
try {
|
||||
const saltResp = await fetchAuth('/api/key-salt');
|
||||
if (!saltResp.ok) throw new Error('HTTP ' + saltResp.status);
|
||||
const saltData = await saltResp.json();
|
||||
|
||||
const cryptoKey = await deriveKey(pass, hexToBytes(saltData.salt), true);
|
||||
const valid = await verifyKeyCheck(cryptoKey, saltData.key_check);
|
||||
if (!valid) { showErr(errEl, t('errWrong')); return; }
|
||||
|
||||
const hexKey = await exportKeyHex(cryptoKey);
|
||||
const apiKey = await fetchApiKey();
|
||||
await showUnlockedView(hexKey, apiKey);
|
||||
} catch (e) {
|
||||
showErr(errEl, 'Error: ' + e.message);
|
||||
} finally {
|
||||
setBtnLoading('unlock-btn', false, 'btnUnlock');
|
||||
}
|
||||
}
|
||||
|
||||
// ── Copy config ────────────────────────────────────────────────────────────────
|
||||
|
||||
async function copyFullConfig() {
|
||||
await copyWithFeedback(
|
||||
document.getElementById('real-config').textContent,
|
||||
'copy-full-btn',
|
||||
'copy-full-text',
|
||||
getCopyFullKey()
|
||||
);
|
||||
}
|
||||
|
||||
async function copySecretsConfig() {
|
||||
const snippet = configFormat === 'mcp'
|
||||
? buildSecretsConfigText(currentApiKey, currentEncKey)
|
||||
: buildOpencodeMergeSnippet(currentApiKey, currentEncKey);
|
||||
await copyWithFeedback(
|
||||
snippet,
|
||||
'copy-secrets-btn',
|
||||
'copy-secrets-text',
|
||||
getCopySecretsKey()
|
||||
);
|
||||
}
|
||||
|
||||
async function copyWithFeedback(text, btnId, textId, resetLabelKey) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
const btn = document.getElementById(btnId);
|
||||
const textEl = document.getElementById(textId);
|
||||
btn.classList.add('copied');
|
||||
textEl.textContent = t('btnCopied');
|
||||
setTimeout(() => {
|
||||
btn.classList.remove('copied');
|
||||
textEl.textContent = t(resetLabelKey);
|
||||
}, 2500);
|
||||
}
|
||||
|
||||
// ── Reset API key ──────────────────────────────────────────────────────────────
|
||||
|
||||
async function confirmRegenerate() {
|
||||
if (!confirm(t('regenConfirm'))) return;
|
||||
try {
|
||||
const resp = await fetchAuth('/api/apikey/regenerate', { method: 'POST' });
|
||||
if (!resp.ok) throw new Error();
|
||||
const data = await resp.json();
|
||||
currentApiKey = data.api_key;
|
||||
renderRealConfig();
|
||||
} catch {
|
||||
alert(t('regenFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
// ── Change passphrase modal ────────────────────────────────────────────────────
|
||||
|
||||
function openChangeModal() {
|
||||
document.getElementById('change-pass-old').value = '';
|
||||
document.getElementById('change-pass1').value = '';
|
||||
document.getElementById('change-pass2').value = '';
|
||||
document.getElementById('change-pass-old').type = 'password';
|
||||
document.getElementById('change-pass1').type = 'password';
|
||||
document.getElementById('change-pass2').type = 'password';
|
||||
document.getElementById('change-error').style.display = 'none';
|
||||
document.getElementById('change-modal').classList.add('open');
|
||||
syncPwToggleI18n();
|
||||
setTimeout(() => document.getElementById('change-pass-old').focus(), 50);
|
||||
}
|
||||
|
||||
function closeChangeModal() {
|
||||
document.getElementById('change-modal').classList.remove('open');
|
||||
}
|
||||
|
||||
async function doChange() {
|
||||
const passOld = document.getElementById('change-pass-old').value;
|
||||
const pass1 = document.getElementById('change-pass1').value;
|
||||
const pass2 = document.getElementById('change-pass2').value;
|
||||
const errEl = document.getElementById('change-error');
|
||||
errEl.style.display = 'none';
|
||||
|
||||
if (!passOld) { showErr(errEl, t('errEmpty')); return; }
|
||||
if (!pass1) { showErr(errEl, t('errEmpty')); return; }
|
||||
if (pass1.length < 8) { showErr(errEl, t('errShort')); return; }
|
||||
if (pass1 !== pass2) { showErr(errEl, t('errMismatch')); return; }
|
||||
|
||||
const btn = document.getElementById('change-btn');
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = '<span class="spinner" style="border-top-color:#0d1117"></span>';
|
||||
try {
|
||||
// Fetch current salt to derive old key for verification
|
||||
const saltResp = await fetchAuth('/api/key-salt');
|
||||
if (!saltResp.ok) throw new Error('HTTP ' + saltResp.status);
|
||||
const saltData = await saltResp.json();
|
||||
if (!saltData.has_passphrase) throw new Error('No passphrase configured');
|
||||
|
||||
// Derive old key and verify it
|
||||
const oldCryptoKey = await deriveKey(passOld, hexToBytes(saltData.salt), true);
|
||||
const validOld = await verifyKeyCheck(oldCryptoKey, saltData.key_check);
|
||||
if (!validOld) { showErr(errEl, t('errWrongOld')); return; }
|
||||
const oldHexKey = await exportKeyHex(oldCryptoKey);
|
||||
|
||||
// Derive new key
|
||||
const newSalt = crypto.getRandomValues(new Uint8Array(32));
|
||||
const newCryptoKey = await deriveKey(pass1, newSalt, true);
|
||||
const newKeyCheckHex = await encryptKeyCheck(newCryptoKey);
|
||||
const newHexKey = await exportKeyHex(newCryptoKey);
|
||||
|
||||
const resp = await fetchAuth('/api/key-change', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
old_key: oldHexKey,
|
||||
new_key: newHexKey,
|
||||
salt: bytesToHex(newSalt),
|
||||
key_check: newKeyCheckHex,
|
||||
params: { alg: 'pbkdf2-sha256', iterations: PBKDF2_ITERATIONS }
|
||||
})
|
||||
});
|
||||
if (!resp.ok) throw new Error('HTTP ' + resp.status);
|
||||
|
||||
currentEncKey = newHexKey;
|
||||
sessionStorage.setItem('enc_key', newHexKey);
|
||||
renderRealConfig();
|
||||
closeChangeModal();
|
||||
} catch (e) {
|
||||
showErr(errEl, 'Error: ' + e.message);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = t('btnChange');
|
||||
}
|
||||
}
|
||||
|
||||
// ── Fetch API key ──────────────────────────────────────────────────────────────
|
||||
|
||||
async function fetchApiKey() {
|
||||
const resp = await fetchAuth('/api/apikey');
|
||||
if (!resp.ok) throw new Error('Failed to load API key');
|
||||
const data = await resp.json();
|
||||
return data.api_key;
|
||||
}
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────────
|
||||
|
||||
function showErr(el, msg) {
|
||||
el.textContent = msg;
|
||||
el.style.display = 'block';
|
||||
}
|
||||
|
||||
// ── Keyboard shortcuts ─────────────────────────────────────────────────────────
|
||||
|
||||
document.addEventListener('keydown', e => {
|
||||
if (e.key === 'Escape') closeChangeModal();
|
||||
if (e.key === 'Enter') {
|
||||
if (document.getElementById('change-modal').classList.contains('open')) { doChange(); return; }
|
||||
if (document.getElementById('unlock-form').style.display !== 'none' &&
|
||||
document.getElementById('locked-view').style.display !== 'none') { doUnlock(); return; }
|
||||
if (document.getElementById('setup-form').style.display !== 'none' &&
|
||||
document.getElementById('locked-view').style.display !== 'none') { doSetup(); return; }
|
||||
}
|
||||
});
|
||||
|
||||
// ── Init ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
(async function init() {
|
||||
applyLang();
|
||||
try {
|
||||
const sf = sessionStorage.getItem(CONFIG_FORMAT_STORAGE);
|
||||
if (sf === 'mcp' || sf === 'opencode') configFormat = sf;
|
||||
} catch (_) { /* ignore */ }
|
||||
const savedKey = sessionStorage.getItem('enc_key');
|
||||
if (savedKey) {
|
||||
try {
|
||||
const apiKey = await fetchApiKey();
|
||||
await showUnlockedView(savedKey, apiKey);
|
||||
return;
|
||||
} catch { /* fall through to locked */ }
|
||||
}
|
||||
showLockedView();
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
1540
crates/secrets-mcp/templates/entries.html
Normal file
1540
crates/secrets-mcp/templates/entries.html
Normal file
File diff suppressed because it is too large
Load Diff
269
crates/secrets-mcp/templates/home.html
Normal file
269
crates/secrets-mcp/templates/home.html
Normal file
@@ -0,0 +1,269 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="description" content="Secrets MCP:基于 Model Context Protocol 的密钥与配置管理。密码短语在浏览器本地 PBKDF2 派生,密文 AES-GCM 存储,完整审计与历史版本。">
|
||||
<meta name="keywords" content="secrets management,MCP,Model Context Protocol,end-to-end encryption,AES-GCM,PBKDF2,API key,密钥管理">
|
||||
<meta name="robots" content="index, follow">
|
||||
<link rel="canonical" href="{{ base_url }}/">
|
||||
<link rel="icon" href="/favicon.svg?v={{ version }}" type="image/svg+xml">
|
||||
<title>Secrets MCP — 端到端加密的密钥管理</title>
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:url" content="{{ base_url }}/">
|
||||
<meta property="og:title" content="Secrets MCP — 端到端加密的密钥管理">
|
||||
<meta property="og:description" content="密码短语客户端派生,密文存储;MCP API 与 Web 控制台,多租户与审计。">
|
||||
<meta name="twitter:card" content="summary">
|
||||
<meta name="twitter:title" content="Secrets MCP — 端到端加密的密钥管理">
|
||||
<meta name="twitter:description" content="密码短语客户端派生,密文存储;MCP API 与 Web 控制台,多租户与审计。">
|
||||
<style>
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@500;600&family=Inter:wght@400;500;600&display=swap');
|
||||
:root {
|
||||
--bg: #0d1117;
|
||||
--surface: #161b22;
|
||||
--surface2: #21262d;
|
||||
--border: #30363d;
|
||||
--text: #e6edf3;
|
||||
--text-muted: #8b949e;
|
||||
--accent: #58a6ff;
|
||||
--accent-hover: #79b8ff;
|
||||
}
|
||||
html, body { height: 100%; overflow: hidden; }
|
||||
@supports (height: 100dvh) {
|
||||
html, body { height: 100dvh; }
|
||||
}
|
||||
body {
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: 'Inter', sans-serif;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.nav {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 14px 24px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--surface);
|
||||
}
|
||||
.brand {
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
text-decoration: none;
|
||||
}
|
||||
.brand span { color: var(--accent); }
|
||||
.nav-right { display: flex; align-items: center; gap: 14px; }
|
||||
.lang-bar { display: flex; gap: 2px; background: rgba(255,255,255,0.04); border-radius: 6px; padding: 2px; }
|
||||
.lang-btn {
|
||||
padding: 4px 10px; border: none; background: none; color: var(--text-muted);
|
||||
font-size: 12px; cursor: pointer; border-radius: 4px;
|
||||
}
|
||||
.lang-btn.active { background: var(--border); color: var(--text); }
|
||||
.cta {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
padding: 8px 18px; border-radius: 8px; font-size: 13px; font-weight: 600;
|
||||
text-decoration: none; border: 1px solid var(--accent);
|
||||
background: rgba(88, 166, 255, 0.12); color: var(--accent);
|
||||
transition: background 0.15s, color 0.15s;
|
||||
}
|
||||
.cta:hover { background: var(--accent); color: var(--bg); }
|
||||
.main {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 16px 24px 12px;
|
||||
gap: 20px;
|
||||
}
|
||||
.hero { text-align: center; max-width: 720px; }
|
||||
.hero h1 { font-size: clamp(20px, 4vw, 28px); font-weight: 600; margin-bottom: 8px; line-height: 1.25; }
|
||||
.hero .tagline { color: var(--text-muted); font-size: clamp(13px, 2vw, 15px); line-height: 1.5; }
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
max-width: 900px;
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.grid { grid-template-columns: repeat(2, 1fr); }
|
||||
}
|
||||
@media (max-width: 480px) {
|
||||
.grid { grid-template-columns: 1fr; gap: 8px; }
|
||||
.main { justify-content: flex-start; padding-top: 12px; }
|
||||
}
|
||||
.card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 14px 14px 12px;
|
||||
min-height: 0;
|
||||
}
|
||||
.card-icon {
|
||||
width: 32px; height: 32px; border-radius: 8px;
|
||||
background: var(--surface2);
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
margin-bottom: 10px; color: var(--accent);
|
||||
}
|
||||
.card-icon svg { width: 18px; height: 18px; }
|
||||
.card h2 { font-size: 13px; font-weight: 600; margin-bottom: 6px; line-height: 1.3; }
|
||||
.card p { font-size: 12px; color: var(--text-muted); line-height: 1.45; }
|
||||
.foot {
|
||||
flex-shrink: 0;
|
||||
text-align: center;
|
||||
padding: 8px 16px 12px;
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
border-top: 1px solid var(--border);
|
||||
background: var(--surface);
|
||||
}
|
||||
.foot a { color: var(--accent); text-decoration: none; }
|
||||
.foot a:hover { text-decoration: underline; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="nav">
|
||||
<a class="brand" href="/">secrets<span>-mcp</span></a>
|
||||
<div class="nav-right">
|
||||
<div class="lang-bar">
|
||||
<button type="button" class="lang-btn" onclick="setLang('zh-CN')">简</button>
|
||||
<button type="button" class="lang-btn" onclick="setLang('zh-TW')">繁</button>
|
||||
<button type="button" class="lang-btn" onclick="setLang('en')">EN</button>
|
||||
</div>
|
||||
{% if is_logged_in %}
|
||||
<a class="cta" href="/dashboard" data-i18n="ctaDashboard">进入控制台</a>
|
||||
{% else %}
|
||||
<a class="cta" href="/login" data-i18n="ctaLogin">登录</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</header>
|
||||
<main class="main">
|
||||
<div class="hero">
|
||||
<h1 data-i18n="heroTitle">端到端加密的密钥与配置管理</h1>
|
||||
<p class="tagline" data-i18n="heroTagline">Streamable HTTP MCP 与 Web 控制台:元数据与密文分库存储,密钥永不离开你的客户端逻辑。</p>
|
||||
</div>
|
||||
<div class="grid">
|
||||
<article class="card">
|
||||
<div class="card-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 11c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v3c0 1.66 1.34 3 3 3z"/><path d="M19 10v1a7 7 0 01-14 0v-1"/><path d="M12 14v7M9 18h6"/></svg>
|
||||
</div>
|
||||
<h2 data-i18n="c1t">客户端密钥派生</h2>
|
||||
<p data-i18n="c1d">PBKDF2-SHA256(约 60 万次)在浏览器本地从密码短语派生密钥;服务端仅保存盐与校验值,不持有密码或明文主密钥。</p>
|
||||
</article>
|
||||
<article class="card">
|
||||
<div class="card-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></svg>
|
||||
</div>
|
||||
<h2 data-i18n="c2t">AES-256-GCM 加密</h2>
|
||||
<p data-i18n="c2d">敏感字段以 AES-GCM 密文落库;Web 端在本地加解密,明文默认不经过服务端持久化。</p>
|
||||
</article>
|
||||
<article class="card">
|
||||
<div class="card-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><path d="M14 2v6h6M16 13H8M16 17H8M10 9H8"/></svg>
|
||||
</div>
|
||||
<h2 data-i18n="c3t">审计与历史</h2>
|
||||
<p data-i18n="c3d">操作写入审计日志;条目与密文保留历史版本,支持按版本查看与恢复。</p>
|
||||
</article>
|
||||
</div>
|
||||
</main>
|
||||
<footer class="foot">
|
||||
<span data-i18n="versionLabel">版本</span> {{ version }} ·
|
||||
<a href="/llms.txt">llms.txt</a>
|
||||
<span data-i18n="sep"> · </span>
|
||||
<a href="https://gitea.refining.dev/refining/secrets" target="_blank" rel="noopener noreferrer" data-i18n="footRepo">源码仓库</a>
|
||||
{% if !is_logged_in %}
|
||||
<span data-i18n="sep"> · </span>
|
||||
<a href="/login" data-i18n="footLogin">登录</a>
|
||||
{% endif %}
|
||||
</footer>
|
||||
<script>
|
||||
const T = {
|
||||
'zh-CN': {
|
||||
docTitle: 'Secrets MCP — 端到端加密的密钥管理',
|
||||
ctaDashboard: '进入控制台',
|
||||
ctaLogin: '登录',
|
||||
heroTitle: '端到端加密的密钥与配置管理',
|
||||
heroTagline: 'Streamable HTTP MCP 与 Web 控制台:元数据与密文分库存储,密钥永不离开你的客户端逻辑。',
|
||||
c1t: '客户端密钥派生',
|
||||
c1d: 'PBKDF2-SHA256(约 60 万次)在浏览器本地从密码短语派生密钥;服务端仅保存盐与校验值,不持有密码或明文主密钥。',
|
||||
c2t: 'AES-256-GCM 加密',
|
||||
c2d: '敏感字段以 AES-GCM 密文落库;Web 端在本地加解密,明文默认不经过服务端持久化。',
|
||||
c3t: '审计与历史',
|
||||
c3d: '操作写入审计日志;条目与密文保留历史版本,支持按版本查看与恢复。',
|
||||
versionLabel: '版本',
|
||||
sep: ' · ',
|
||||
footRepo: '源码仓库',
|
||||
footLogin: '登录',
|
||||
},
|
||||
'zh-TW': {
|
||||
docTitle: 'Secrets MCP — 端到端加密的金鑰管理',
|
||||
ctaDashboard: '進入控制台',
|
||||
ctaLogin: '登入',
|
||||
heroTitle: '端到端加密的金鑰與設定管理',
|
||||
heroTagline: 'Streamable HTTP MCP 與 Web 控制台:中繼資料與密文分庫儲存,金鑰不離開你的用戶端邏輯。',
|
||||
c1t: '用戶端金鑰派生',
|
||||
c1d: 'PBKDF2-SHA256(約 60 萬次)在瀏覽器本地從密碼片語派生金鑰;伺服端僅保存鹽與校驗值,不持有密碼或明文主金鑰。',
|
||||
c2t: 'AES-256-GCM 加密',
|
||||
c2d: '敏感欄位以 AES-GCM 密文落庫;Web 端在本地加解密,明文預設不經伺服端持久化。',
|
||||
c3t: '稽核與歷史',
|
||||
c3d: '操作寫入稽核日誌;條目與密文保留歷史版本,支援依版本檢視與還原。',
|
||||
versionLabel: '版本',
|
||||
sep: ' · ',
|
||||
footRepo: '原始碼倉庫',
|
||||
footLogin: '登入',
|
||||
},
|
||||
'en': {
|
||||
docTitle: 'Secrets MCP — End-to-end encrypted secrets',
|
||||
ctaDashboard: 'Open dashboard',
|
||||
ctaLogin: 'Sign in',
|
||||
heroTitle: 'End-to-end encrypted secrets and configuration',
|
||||
heroTagline: 'Streamable HTTP MCP plus web console: metadata and ciphertext stored separately; keys stay on your client.',
|
||||
c1t: 'Client-side key derivation',
|
||||
c1d: 'PBKDF2-SHA256 (~600k iterations) derives keys from your passphrase in the browser; the server stores only salt and a verification blob, never your password or raw master key.',
|
||||
c2t: 'AES-256-GCM',
|
||||
c2d: 'Secret fields are stored as AES-GCM ciphertext; the web UI encrypts and decrypts locally so plaintext is not persisted server-side by default.',
|
||||
c3t: 'Audit and history',
|
||||
c3d: 'Operations are audited; entries and secrets keep version history for review and rollback.',
|
||||
versionLabel: 'Version',
|
||||
sep: ' · ',
|
||||
footRepo: 'Source repository',
|
||||
footLogin: 'Sign in',
|
||||
}
|
||||
};
|
||||
|
||||
let currentLang = localStorage.getItem('lang') || 'zh-CN';
|
||||
|
||||
function t(key) {
|
||||
return (T[currentLang] && T[currentLang][key]) || T['en'][key] || key;
|
||||
}
|
||||
|
||||
function applyLang() {
|
||||
document.documentElement.lang = currentLang;
|
||||
document.title = t('docTitle');
|
||||
document.querySelectorAll('[data-i18n]').forEach(el => {
|
||||
const key = el.getAttribute('data-i18n');
|
||||
el.textContent = t(key);
|
||||
});
|
||||
document.querySelectorAll('.lang-btn').forEach(btn => {
|
||||
const map = { 'zh-CN': '简', 'zh-TW': '繁', 'en': 'EN' };
|
||||
btn.classList.toggle('active', btn.textContent === map[currentLang]);
|
||||
});
|
||||
}
|
||||
|
||||
function setLang(lang) {
|
||||
currentLang = lang;
|
||||
localStorage.setItem('lang', lang);
|
||||
applyLang();
|
||||
}
|
||||
|
||||
applyLang();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
76
crates/secrets-mcp/templates/i18n.js
Normal file
76
crates/secrets-mcp/templates/i18n.js
Normal file
@@ -0,0 +1,76 @@
|
||||
var I18N_SHARED = {
|
||||
'zh-CN': {
|
||||
pageTitleBase: 'Secrets',
|
||||
navMcp: 'MCP',
|
||||
navEntries: '条目',
|
||||
navAudit: '审计',
|
||||
signOut: '退出',
|
||||
mobileLabelTime: '时间',
|
||||
mobileLabelAction: '动作',
|
||||
mobileLabelTarget: '目标',
|
||||
mobileLabelDetail: '详情'
|
||||
},
|
||||
'zh-TW': {
|
||||
pageTitleBase: 'Secrets',
|
||||
navMcp: 'MCP',
|
||||
navEntries: '條目',
|
||||
navAudit: '審計',
|
||||
signOut: '登出',
|
||||
mobileLabelTime: '時間',
|
||||
mobileLabelAction: '動作',
|
||||
mobileLabelTarget: '目標',
|
||||
mobileLabelDetail: '詳情'
|
||||
},
|
||||
en: {
|
||||
pageTitleBase: 'Secrets',
|
||||
navMcp: 'MCP',
|
||||
navEntries: 'Entries',
|
||||
navAudit: 'Audit',
|
||||
signOut: 'Sign out',
|
||||
mobileLabelTime: 'Time',
|
||||
mobileLabelAction: 'Action',
|
||||
mobileLabelTarget: 'Target',
|
||||
mobileLabelDetail: 'Detail'
|
||||
}
|
||||
};
|
||||
|
||||
var currentLang = localStorage.getItem('lang') || 'zh-CN';
|
||||
var I18N_PAGE = {};
|
||||
|
||||
function t(key) {
|
||||
var dict = I18N_PAGE[currentLang] || I18N_PAGE['en'] || {};
|
||||
var val = dict[key] || (I18N_SHARED[currentLang] && I18N_SHARED[currentLang][key]) || (I18N_SHARED.en && I18N_SHARED.en[key]) || key;
|
||||
return val;
|
||||
}
|
||||
|
||||
function tf(key, vars) {
|
||||
var tpl = t(key);
|
||||
return Object.keys(vars || {}).reduce(function (acc, k) {
|
||||
return acc.replace(new RegExp('\\{' + k + '\\}', 'g'), String(vars[k]));
|
||||
}, tpl);
|
||||
}
|
||||
|
||||
function applyLang() {
|
||||
document.documentElement.lang = currentLang;
|
||||
var title = t('pageTitle');
|
||||
if (title) document.title = title;
|
||||
document.querySelectorAll('[data-i18n]').forEach(function (el) {
|
||||
var key = el.getAttribute('data-i18n');
|
||||
el.textContent = t(key);
|
||||
});
|
||||
document.querySelectorAll('[data-i18n-ph]').forEach(function (el) {
|
||||
var key = el.getAttribute('data-i18n-ph');
|
||||
el.placeholder = t(key);
|
||||
});
|
||||
document.querySelectorAll('.lang-btn').forEach(function (btn) {
|
||||
var map = { 'zh-CN': '简', 'zh-TW': '繁', en: 'EN' };
|
||||
btn.classList.toggle('active', btn.textContent === map[currentLang]);
|
||||
});
|
||||
if (typeof applyPageLang === 'function') applyPageLang();
|
||||
}
|
||||
|
||||
window.setLang = function (lang) {
|
||||
currentLang = lang;
|
||||
localStorage.setItem('lang', lang);
|
||||
applyLang();
|
||||
};
|
||||
186
crates/secrets-mcp/templates/login.html
Normal file
186
crates/secrets-mcp/templates/login.html
Normal file
@@ -0,0 +1,186 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="robots" content="noindex, follow">
|
||||
<meta name="description" content="登录 Secrets MCP Web 控制台,安全管理跨设备加密 secrets。">
|
||||
<meta name="keywords" content="Secrets MCP,登录,OAuth,密钥管理">
|
||||
<link rel="canonical" href="{{ base_url }}/login">
|
||||
<link rel="icon" href="/favicon.svg?v={{ version }}" type="image/svg+xml">
|
||||
<title>登录 — Secrets MCP</title>
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:url" content="{{ base_url }}/login">
|
||||
<meta property="og:title" content="登录 — Secrets MCP">
|
||||
<meta property="og:description" content="登录 Web 控制台,管理加密存储的密钥与配置。">
|
||||
<meta name="twitter:card" content="summary">
|
||||
<meta name="twitter:title" content="登录 — Secrets MCP">
|
||||
<meta name="twitter:description" content="登录 Web 控制台,管理加密存储的密钥与配置。">
|
||||
<style>
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap');
|
||||
:root {
|
||||
--bg: #0d1117;
|
||||
--surface: #161b22;
|
||||
--border: #30363d;
|
||||
--text: #e6edf3;
|
||||
--text-muted: #8b949e;
|
||||
--accent: #58a6ff;
|
||||
--accent-hover: #79b8ff;
|
||||
--google: #4285f4;
|
||||
--danger: #f85149;
|
||||
}
|
||||
body { background: var(--bg); color: var(--text); font-family: 'Inter', sans-serif;
|
||||
min-height: 100vh; display: flex; align-items: center; justify-content: center; }
|
||||
.card {
|
||||
background: var(--surface); border: 1px solid var(--border); border-radius: 12px;
|
||||
padding: 48px 40px; width: 100%; max-width: 400px;
|
||||
box-shadow: 0 8px 32px rgba(0,0,0,0.4);
|
||||
}
|
||||
.topbar { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 20px; gap: 12px; }
|
||||
.back-home {
|
||||
font-size: 13px; color: var(--accent); text-decoration: none; white-space: nowrap;
|
||||
}
|
||||
.back-home:hover { text-decoration: underline; }
|
||||
.lang-bar { display: flex; gap: 2px; background: rgba(255,255,255,0.04); border-radius: 6px; padding: 2px; flex-shrink: 0; }
|
||||
.lang-btn { padding: 3px 9px; border: none; background: none; color: var(--text-muted);
|
||||
font-size: 12px; cursor: pointer; border-radius: 4px; }
|
||||
.lang-btn.active { background: var(--border); color: var(--text); }
|
||||
.oauth-alert {
|
||||
display: none;
|
||||
margin-bottom: 16px; padding: 10px 12px; border-radius: 8px;
|
||||
font-size: 13px; line-height: 1.4;
|
||||
background: rgba(248, 81, 73, 0.12);
|
||||
border: 1px solid rgba(248, 81, 73, 0.35);
|
||||
color: #ffa198;
|
||||
}
|
||||
.oauth-alert.visible { display: block; }
|
||||
h1 { font-size: 22px; font-weight: 600; margin-bottom: 8px; }
|
||||
.subtitle { color: var(--text-muted); font-size: 14px; margin-bottom: 32px; }
|
||||
.btn {
|
||||
display: flex; align-items: center; justify-content: center; gap: 12px;
|
||||
width: 100%; padding: 12px 20px; border: 1px solid var(--border); border-radius: 8px;
|
||||
background: var(--surface); color: var(--text); font-size: 14px; font-weight: 500;
|
||||
cursor: pointer; text-decoration: none; transition: all 0.2s;
|
||||
}
|
||||
.btn:hover { background: var(--border); border-color: var(--text-muted); }
|
||||
.btn + .btn { margin-top: 12px; }
|
||||
.btn svg { flex-shrink: 0; }
|
||||
.footer { margin-top: 28px; text-align: center; color: var(--text-muted); font-size: 12px; }
|
||||
.footer a { color: var(--accent); text-decoration: none; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<div class="topbar">
|
||||
<a class="back-home" href="/" data-i18n="backHome">返回首页</a>
|
||||
<div class="lang-bar">
|
||||
<button type="button" class="lang-btn" onclick="setLang('zh-CN')">简</button>
|
||||
<button type="button" class="lang-btn" onclick="setLang('zh-TW')">繁</button>
|
||||
<button type="button" class="lang-btn" onclick="setLang('en')">EN</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="oauth-alert" class="oauth-alert" role="alert"></div>
|
||||
<h1 data-i18n="title">登录</h1>
|
||||
<p class="subtitle" data-i18n="subtitle">安全管理你的跨设备 secrets。</p>
|
||||
|
||||
{% if has_google %}
|
||||
<a href="/auth/google" class="btn">
|
||||
<svg width="18" height="18" viewBox="0 0 18 18" fill="none">
|
||||
<path d="M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844a4.14 4.14 0 01-1.796 2.716v2.259h2.908c1.702-1.567 2.684-3.875 2.684-6.615z" fill="#4285F4"/>
|
||||
<path d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 009 18z" fill="#34A853"/>
|
||||
<path d="M3.964 10.71A5.41 5.41 0 013.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 000 9c0 1.452.348 2.827.957 4.042l3.007-2.332z" fill="#FBBC05"/>
|
||||
<path d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 00.957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58z" fill="#EA4335"/>
|
||||
</svg>
|
||||
<span data-i18n="google">使用 Google 登录</span>
|
||||
</a>
|
||||
{% endif %}
|
||||
|
||||
{% if !has_google %}
|
||||
<p style="text-align:center; color: var(--text-muted); font-size: 14px;" data-i18n="noProviders">
|
||||
未配置登录方式,请联系管理员。
|
||||
</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
<script>
|
||||
const T = {
|
||||
'zh-CN': {
|
||||
docTitle: '登录 — Secrets MCP',
|
||||
backHome: '返回首页',
|
||||
title: '登录',
|
||||
subtitle: '安全管理你的跨设备 secrets。',
|
||||
google: '使用 Google 登录',
|
||||
noProviders: '未配置登录方式,请联系管理员。',
|
||||
err_oauth_error: '登录失败:授权提供方返回错误,请重试。',
|
||||
err_oauth_missing_code: '登录失败:未收到授权码,请重试。',
|
||||
err_oauth_missing_state: '登录失败:缺少安全校验参数,请重试。',
|
||||
err_oauth_state: '登录失败:会话校验不匹配(可能因 Cookie 策略或服务器重启)。请返回首页再试。',
|
||||
},
|
||||
'zh-TW': {
|
||||
docTitle: '登入 — Secrets MCP',
|
||||
backHome: '返回首頁',
|
||||
title: '登入',
|
||||
subtitle: '安全管理你的跨裝置 secrets。',
|
||||
google: '使用 Google 登入',
|
||||
noProviders: '尚未設定登入方式,請聯絡管理員。',
|
||||
err_oauth_error: '登入失敗:授權方回傳錯誤,請再試一次。',
|
||||
err_oauth_missing_code: '登入失敗:未取得授權碼,請再試一次。',
|
||||
err_oauth_missing_state: '登入失敗:缺少安全校驗參數,請再試一次。',
|
||||
err_oauth_state: '登入失敗:工作階段校驗不符(可能與 Cookie 政策或伺服器重啟有關)。請回到首頁再試。',
|
||||
},
|
||||
'en': {
|
||||
docTitle: 'Sign in — Secrets MCP',
|
||||
backHome: 'Back to home',
|
||||
title: 'Sign in',
|
||||
subtitle: 'Manage your cross-device secrets securely.',
|
||||
google: 'Continue with Google',
|
||||
noProviders: 'No login providers configured. Please contact your administrator.',
|
||||
err_oauth_error: 'Sign-in failed: the identity provider returned an error. Please try again.',
|
||||
err_oauth_missing_code: 'Sign-in failed: no authorization code was returned. Please try again.',
|
||||
err_oauth_missing_state: 'Sign-in failed: missing security state. Please try again.',
|
||||
err_oauth_state: 'Sign-in failed: session state mismatch (often cookies or server restart). Open the home page and try again.',
|
||||
}
|
||||
};
|
||||
|
||||
let currentLang = localStorage.getItem('lang') || 'zh-CN';
|
||||
|
||||
function t(key) { return T[currentLang][key] || T['en'][key] || key; }
|
||||
|
||||
function showOAuthError() {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const code = params.get('error');
|
||||
const el = document.getElementById('oauth-alert');
|
||||
if (!code || !code.startsWith('oauth_')) {
|
||||
el.classList.remove('visible');
|
||||
el.textContent = '';
|
||||
return;
|
||||
}
|
||||
const key = 'err_' + code;
|
||||
el.textContent = t(key) || t('err_oauth_error');
|
||||
el.classList.add('visible');
|
||||
}
|
||||
|
||||
function applyLang() {
|
||||
document.documentElement.lang = currentLang;
|
||||
document.title = t('docTitle');
|
||||
document.querySelectorAll('[data-i18n]').forEach(el => {
|
||||
const key = el.getAttribute('data-i18n');
|
||||
el.textContent = t(key);
|
||||
});
|
||||
document.querySelectorAll('.lang-btn').forEach(btn => {
|
||||
const map = { 'zh-CN': '简', 'zh-TW': '繁', 'en': 'EN' };
|
||||
btn.classList.toggle('active', btn.textContent === map[currentLang]);
|
||||
});
|
||||
showOAuthError();
|
||||
}
|
||||
|
||||
function setLang(lang) {
|
||||
currentLang = lang;
|
||||
localStorage.setItem('lang', lang);
|
||||
applyLang();
|
||||
}
|
||||
|
||||
applyLang();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
53
deploy/.env.example
Normal file
53
deploy/.env.example
Normal file
@@ -0,0 +1,53 @@
|
||||
# Secrets MCP Server 环境变量配置
|
||||
# 复制此文件为 .env 并填写真实值
|
||||
|
||||
# ─── 数据库 ───────────────────────────────────────────────────────────
|
||||
# Web 会话(tower-sessions)与业务数据共用此库;启动时会自动 migrate 会话表,无需额外环境变量。
|
||||
SECRETS_DATABASE_URL=postgres://postgres:PASSWORD@db.refining.ltd:5432/secrets-mcp
|
||||
# 强烈建议生产使用 verify-full(至少 verify-ca)
|
||||
SECRETS_DATABASE_SSL_MODE=verify-full
|
||||
# 私有 CA 或自建链路时填写 CA 根证书路径;使用公共受信 CA 可留空
|
||||
# SECRETS_DATABASE_SSL_ROOT_CERT=/etc/secrets/pg-ca.crt
|
||||
# 当设为 prod/production 时,服务会拒绝弱 TLS 模式(prefer/disable/allow/require)
|
||||
SECRETS_ENV=production
|
||||
|
||||
# ─── 服务地址 ─────────────────────────────────────────────────────────
|
||||
# 内网监听地址(Cloudflare / Nginx 反代时填内网端口)
|
||||
SECRETS_MCP_BIND=127.0.0.1:9315
|
||||
|
||||
# 对外 HTTPS 地址(用于 OAuth 回调 URL 拼接)
|
||||
BASE_URL=https://secrets.example.com
|
||||
|
||||
# ─── Google OAuth ─────────────────────────────────────────────────────
|
||||
# Google Cloud Console → APIs & Services → Credentials
|
||||
# 授权回调 URI 须配置为:${BASE_URL}/auth/google/callback
|
||||
GOOGLE_CLIENT_ID=
|
||||
GOOGLE_CLIENT_SECRET=
|
||||
|
||||
# ─── 微信登录(暂未开放,预留)───────────────────────────────────────
|
||||
# WECHAT_APP_CLIENT_ID=
|
||||
# WECHAT_APP_CLIENT_SECRET=
|
||||
|
||||
# ─── 日志(可选)──────────────────────────────────────────────────────
|
||||
# RUST_LOG=secrets_mcp=debug
|
||||
|
||||
# ─── 数据库连接池(可选)──────────────────────────────────────────────
|
||||
# 最大连接数,默认 10
|
||||
# SECRETS_DATABASE_POOL_SIZE=10
|
||||
# 获取连接超时秒数,默认 5
|
||||
# SECRETS_DATABASE_ACQUIRE_TIMEOUT=5
|
||||
|
||||
# ─── 限流(可选)──────────────────────────────────────────────────────
|
||||
# 全局限流速率(req/s),默认 100
|
||||
# RATE_LIMIT_GLOBAL_PER_SECOND=100
|
||||
# 全局限流突发量,默认 200
|
||||
# RATE_LIMIT_GLOBAL_BURST=200
|
||||
# 单 IP 限流速率(req/s),默认 20
|
||||
# RATE_LIMIT_IP_PER_SECOND=20
|
||||
# 单 IP 限流突发量,默认 40
|
||||
# RATE_LIMIT_IP_BURST=40
|
||||
|
||||
# ─── 代理信任(可选)─────────────────────────────────────────────────
|
||||
# 设为 1/true/yes 时从 X-Forwarded-For / X-Real-IP 提取客户端 IP
|
||||
# 仅在反代环境下启用,否则客户端可伪造 IP 绕过限流
|
||||
# TRUST_PROXY=1
|
||||
92
deploy/postgres-tls-hardening.md
Normal file
92
deploy/postgres-tls-hardening.md
Normal file
@@ -0,0 +1,92 @@
|
||||
# PostgreSQL TLS Hardening Runbook
|
||||
|
||||
This runbook applies to:
|
||||
|
||||
- PostgreSQL server: `47.117.131.22` (`db.refining.ltd`)
|
||||
- `secrets-mcp` app server: `47.238.146.244` (`secrets.refining.app`)
|
||||
|
||||
## 1) Issue certificate for `db.refining.ltd` (Let's Encrypt + Cloudflare DNS-01)
|
||||
|
||||
Install `acme.sh` on the PostgreSQL server and use a Cloudflare API token with DNS edit permission for the target zone.
|
||||
|
||||
```bash
|
||||
curl https://get.acme.sh | sh -s email=ops@refining.ltd
|
||||
export CF_Token="your_cloudflare_dns_token"
|
||||
export CF_Zone_ID="your_zone_id"
|
||||
~/.acme.sh/acme.sh --issue --dns dns_cf -d db.refining.ltd --keylength ec-256
|
||||
```
|
||||
|
||||
Install cert/key into a PostgreSQL-readable path:
|
||||
|
||||
```bash
|
||||
sudo mkdir -p /etc/postgresql/tls
|
||||
sudo ~/.acme.sh/acme.sh --install-cert -d db.refining.ltd --ecc \
|
||||
--fullchain-file /etc/postgresql/tls/fullchain.pem \
|
||||
--key-file /etc/postgresql/tls/privkey.pem \
|
||||
--reloadcmd "systemctl reload postgresql || systemctl restart postgresql"
|
||||
sudo chown -R postgres:postgres /etc/postgresql/tls
|
||||
sudo chmod 600 /etc/postgresql/tls/privkey.pem
|
||||
sudo chmod 644 /etc/postgresql/tls/fullchain.pem
|
||||
```
|
||||
|
||||
## 2) Configure PostgreSQL TLS and access rules
|
||||
|
||||
In `postgresql.conf`:
|
||||
|
||||
```conf
|
||||
ssl = on
|
||||
ssl_cert_file = '/etc/postgresql/tls/fullchain.pem'
|
||||
ssl_key_file = '/etc/postgresql/tls/privkey.pem'
|
||||
```
|
||||
|
||||
In `pg_hba.conf`, allow app traffic via TLS only (example):
|
||||
|
||||
```conf
|
||||
hostssl secrets-mcp postgres 47.238.146.244/32 scram-sha-256
|
||||
```
|
||||
|
||||
Keep a safe admin path (`local` socket or restricted source CIDR) before removing old plaintext `host` rules.
|
||||
|
||||
Reload PostgreSQL:
|
||||
|
||||
```bash
|
||||
sudo systemctl reload postgresql
|
||||
```
|
||||
|
||||
## 3) Verify server-side TLS
|
||||
|
||||
```bash
|
||||
openssl s_client -starttls postgres -connect db.refining.ltd:5432 -servername db.refining.ltd
|
||||
```
|
||||
|
||||
The handshake should succeed and the certificate should match `db.refining.ltd`.
|
||||
|
||||
## 4) Update `secrets-mcp` app server env
|
||||
|
||||
Use environment values like:
|
||||
|
||||
```bash
|
||||
SECRETS_DATABASE_URL=postgres://postgres:***@db.refining.ltd:5432/secrets-mcp
|
||||
SECRETS_DATABASE_SSL_MODE=verify-full
|
||||
SECRETS_ENV=production
|
||||
```
|
||||
|
||||
If you use private CA instead of public CA, also set:
|
||||
|
||||
```bash
|
||||
SECRETS_DATABASE_SSL_ROOT_CERT=/etc/secrets/pg-ca.crt
|
||||
```
|
||||
|
||||
Restart `secrets-mcp` after updating env.
|
||||
|
||||
## 5) Verify from app server
|
||||
|
||||
Run positive and negative checks:
|
||||
|
||||
- Positive: app starts, migrations pass, dashboard + MCP API work.
|
||||
- Negative:
|
||||
- wrong hostname -> connection fails
|
||||
- wrong CA file -> connection fails
|
||||
- disable TLS on DB -> connection fails
|
||||
|
||||
This ensures no silent downgrade to weak TLS in production.
|
||||
27
deploy/secrets-mcp.service
Normal file
27
deploy/secrets-mcp.service
Normal file
@@ -0,0 +1,27 @@
|
||||
[Unit]
|
||||
Description=Secrets MCP Server
|
||||
After=network.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=secrets-mcp
|
||||
Group=secrets-mcp
|
||||
WorkingDirectory=/opt/secrets-mcp
|
||||
EnvironmentFile=/opt/secrets-mcp/.env
|
||||
ExecStart=/opt/secrets-mcp/secrets-mcp
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
SyslogIdentifier=secrets-mcp
|
||||
|
||||
# 安全加固
|
||||
NoNewPrivileges=yes
|
||||
ProtectSystem=strict
|
||||
ProtectHome=yes
|
||||
ReadWritePaths=/opt/secrets-mcp
|
||||
PrivateTmp=yes
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
3
rust-toolchain.toml
Normal file
3
rust-toolchain.toml
Normal file
@@ -0,0 +1,3 @@
|
||||
[toolchain]
|
||||
channel = "1.94.0"
|
||||
components = ["rustfmt", "clippy"]
|
||||
24
scripts/release-check.sh
Executable file
24
scripts/release-check.sh
Executable file
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
cd "$repo_root"
|
||||
|
||||
version="$(grep -m1 '^version' crates/secrets-mcp/Cargo.toml | sed 's/.*"\(.*\)".*/\1/')"
|
||||
tag="secrets-mcp-${version}"
|
||||
|
||||
echo "==> 当前 secrets-mcp 版本: ${version}"
|
||||
echo "==> 检查是否已存在 tag: ${tag}"
|
||||
|
||||
if jj log --no-graph --revisions "tag(${tag})" --limit 1 >/dev/null 2>&1; then
|
||||
echo "提示: 已存在 tag ${tag},将按重复构建处理,不阻断检查。"
|
||||
echo "如需创建新的发布版本,请先 bump crates/secrets-mcp/Cargo.toml 中的 version。"
|
||||
else
|
||||
echo "==> 未发现重复 tag,将创建新版本"
|
||||
fi
|
||||
|
||||
echo "==> 开始执行检查"
|
||||
cargo fmt -- --check
|
||||
cargo clippy --locked -- -D warnings
|
||||
cargo test --locked
|
||||
1
scripts/repair-secrets.template.csv
Normal file
1
scripts/repair-secrets.template.csv
Normal file
@@ -0,0 +1 @@
|
||||
entry_id,secret_name,secret_value
|
||||
|
383
scripts/repair_secrets_from_csv.py
Normal file
383
scripts/repair_secrets_from_csv.py
Normal file
@@ -0,0 +1,383 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Batch re-encrypt secret fields from a CSV file.
|
||||
|
||||
CSV format:
|
||||
entry_id,secret_name,secret_value
|
||||
019d...,api_key,sk-xxxx
|
||||
019d...,password,hunter2
|
||||
|
||||
The script groups rows by entry_id, then calls `secrets_update` with `secrets_obj`
|
||||
so the server re-encrypts the provided plaintext values with the current key.
|
||||
|
||||
Warnings:
|
||||
- Keep the CSV outside version control whenever possible.
|
||||
- Delete the filled CSV after the repair is complete.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from collections import OrderedDict
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
DEFAULT_USER_AGENT = "Cursor/3.0.12 (darwin arm64)"
|
||||
REQUIRED_COLUMNS = {"entry_id", "secret_name", "secret_value"}
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Repair secret ciphertexts by re-submitting plaintext via secrets_update."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--csv",
|
||||
required=True,
|
||||
help="Path to CSV file with columns: entry_id,secret_name,secret_value",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--mcp-json",
|
||||
default=str(Path.home() / ".cursor" / "mcp.json"),
|
||||
help="Path to mcp.json used to resolve URL and headers",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--server",
|
||||
default="secrets",
|
||||
help="MCP server name inside mcp.json (default: secrets)",
|
||||
)
|
||||
parser.add_argument("--url", help="Override MCP URL")
|
||||
parser.add_argument("--auth", help="Override Authorization header value")
|
||||
parser.add_argument("--encryption-key", help="Override X-Encryption-Key header value")
|
||||
parser.add_argument(
|
||||
"--user-agent",
|
||||
default=DEFAULT_USER_AGENT,
|
||||
help=f"User-Agent header (default: {DEFAULT_USER_AGENT})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dry-run",
|
||||
action="store_true",
|
||||
help="Parse and print grouped updates without sending requests",
|
||||
)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def load_mcp_config(path: str, server_name: str) -> dict[str, Any]:
|
||||
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
servers = data.get("mcpServers", {})
|
||||
if server_name not in servers:
|
||||
raise KeyError(f"Server '{server_name}' not found in {path}")
|
||||
return servers[server_name]
|
||||
|
||||
|
||||
def resolve_connection_settings(args: argparse.Namespace) -> tuple[str, str, str]:
|
||||
server = load_mcp_config(args.mcp_json, args.server)
|
||||
headers = server.get("headers", {})
|
||||
|
||||
url = args.url or server.get("url")
|
||||
auth = args.auth or headers.get("Authorization")
|
||||
encryption_key = args.encryption_key or headers.get("X-Encryption-Key")
|
||||
|
||||
if not url:
|
||||
raise ValueError("Missing MCP URL. Pass --url or configure it in mcp.json.")
|
||||
if not auth:
|
||||
raise ValueError(
|
||||
"Missing Authorization header. Pass --auth or configure it in mcp.json."
|
||||
)
|
||||
if not encryption_key:
|
||||
raise ValueError(
|
||||
"Missing X-Encryption-Key. Pass --encryption-key or configure it in mcp.json."
|
||||
)
|
||||
|
||||
return url, auth, encryption_key
|
||||
|
||||
|
||||
def load_updates(csv_path: str) -> OrderedDict[str, OrderedDict[str, str]]:
|
||||
grouped: OrderedDict[str, OrderedDict[str, str]] = OrderedDict()
|
||||
|
||||
with Path(csv_path).open("r", encoding="utf-8-sig", newline="") as fh:
|
||||
reader = csv.DictReader(fh)
|
||||
fieldnames = set(reader.fieldnames or [])
|
||||
missing = REQUIRED_COLUMNS - fieldnames
|
||||
if missing:
|
||||
raise ValueError(
|
||||
"CSV missing required columns: " + ", ".join(sorted(missing))
|
||||
)
|
||||
|
||||
for line_no, row in enumerate(reader, start=2):
|
||||
entry_id = (row.get("entry_id") or "").strip()
|
||||
secret_name = (row.get("secret_name") or "").strip()
|
||||
secret_value = row.get("secret_value") or ""
|
||||
|
||||
if not entry_id and not secret_name and not secret_value:
|
||||
continue
|
||||
if not entry_id:
|
||||
raise ValueError(f"Line {line_no}: entry_id is required")
|
||||
if not secret_name:
|
||||
raise ValueError(f"Line {line_no}: secret_name is required")
|
||||
|
||||
entry_group = grouped.setdefault(entry_id, OrderedDict())
|
||||
if secret_name in entry_group:
|
||||
raise ValueError(
|
||||
f"Line {line_no}: duplicate secret_name '{secret_name}' for entry_id '{entry_id}'"
|
||||
)
|
||||
entry_group[secret_name] = secret_value
|
||||
|
||||
if not grouped:
|
||||
raise ValueError("CSV contains no updates")
|
||||
|
||||
return grouped
|
||||
|
||||
|
||||
def post_json(
|
||||
url: str,
|
||||
payload: dict[str, Any],
|
||||
auth: str,
|
||||
encryption_key: str,
|
||||
user_agent: str,
|
||||
session_id: str | None = None,
|
||||
) -> tuple[int, str | None, str]:
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json, text/event-stream",
|
||||
"Authorization": auth,
|
||||
"X-Encryption-Key": encryption_key,
|
||||
"User-Agent": user_agent,
|
||||
}
|
||||
if session_id:
|
||||
headers["mcp-session-id"] = session_id
|
||||
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=json.dumps(payload).encode("utf-8"),
|
||||
headers=headers,
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
return (
|
||||
resp.status,
|
||||
resp.headers.get("mcp-session-id") or session_id,
|
||||
resp.read().decode("utf-8"),
|
||||
)
|
||||
except urllib.error.HTTPError as exc:
|
||||
body = exc.read().decode("utf-8", errors="replace")
|
||||
return exc.code, session_id, body
|
||||
|
||||
|
||||
def parse_sse_json(body: str) -> list[dict[str, Any]]:
|
||||
items: list[dict[str, Any]] = []
|
||||
for line in body.splitlines():
|
||||
if line.startswith("data: {"):
|
||||
items.append(json.loads(line[6:]))
|
||||
return items
|
||||
|
||||
|
||||
def initialize_session(
|
||||
url: str, auth: str, encryption_key: str, user_agent: str
|
||||
) -> str:
|
||||
status, session_id, body = post_json(
|
||||
url,
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "initialize",
|
||||
"params": {
|
||||
"protocolVersion": "2025-06-18",
|
||||
"capabilities": {},
|
||||
"clientInfo": {"name": "repair-script", "version": "1.0"},
|
||||
},
|
||||
},
|
||||
auth,
|
||||
encryption_key,
|
||||
user_agent,
|
||||
)
|
||||
if status != 200 or not session_id:
|
||||
raise RuntimeError(f"initialize failed: status={status}, body={body[:500]}")
|
||||
|
||||
status, _, body = post_json(
|
||||
url,
|
||||
{"jsonrpc": "2.0", "method": "notifications/initialized", "params": {}},
|
||||
auth,
|
||||
encryption_key,
|
||||
user_agent,
|
||||
session_id,
|
||||
)
|
||||
if status not in (200, 202):
|
||||
raise RuntimeError(
|
||||
f"notifications/initialized failed: status={status}, body={body[:500]}"
|
||||
)
|
||||
return session_id
|
||||
|
||||
|
||||
def load_entry_index(
|
||||
url: str, auth: str, encryption_key: str, user_agent: str, session_id: str
|
||||
) -> dict[str, tuple[str, str]]:
|
||||
status, _, body = post_json(
|
||||
url,
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 999_001,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "secrets_find",
|
||||
"arguments": {
|
||||
"limit": 1000,
|
||||
},
|
||||
},
|
||||
},
|
||||
auth,
|
||||
encryption_key,
|
||||
user_agent,
|
||||
session_id,
|
||||
)
|
||||
items = parse_sse_json(body)
|
||||
last = items[-1] if items else {"raw": body[:1000]}
|
||||
if status != 200:
|
||||
raise RuntimeError(
|
||||
f"secrets_find failed: status={status}, body={body[:500]}"
|
||||
)
|
||||
if "error" in last:
|
||||
raise RuntimeError(f"secrets_find returned error: {last}")
|
||||
|
||||
content = last.get("result", {}).get("content", [])
|
||||
if not content:
|
||||
raise RuntimeError("secrets_find returned no content")
|
||||
payload = json.loads(content[0]["text"])
|
||||
|
||||
index: dict[str, tuple[str, str]] = {}
|
||||
for entry in payload.get("entries", []):
|
||||
entry_id = entry.get("id")
|
||||
name = entry.get("name")
|
||||
folder = entry.get("folder", "")
|
||||
if entry_id and name is not None:
|
||||
index[entry_id] = (name, folder)
|
||||
return index
|
||||
|
||||
|
||||
def call_secrets_update(
|
||||
url: str,
|
||||
auth: str,
|
||||
encryption_key: str,
|
||||
user_agent: str,
|
||||
session_id: str,
|
||||
request_id: int,
|
||||
entry_id: str,
|
||||
entry_name: str,
|
||||
entry_folder: str,
|
||||
secrets_obj: dict[str, str],
|
||||
) -> dict[str, Any]:
|
||||
payload = {
|
||||
"jsonrpc": "2.0",
|
||||
"id": request_id,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "secrets_update",
|
||||
"arguments": {
|
||||
"id": entry_id,
|
||||
"name": entry_name,
|
||||
"folder": entry_folder,
|
||||
"secrets_obj": secrets_obj,
|
||||
# Pass the key as an argument too, so repair can still work
|
||||
# even when a client/proxy mishandles custom headers.
|
||||
"encryption_key": encryption_key,
|
||||
},
|
||||
},
|
||||
}
|
||||
status, _, body = post_json(
|
||||
url, payload, auth, encryption_key, user_agent, session_id
|
||||
)
|
||||
items = parse_sse_json(body)
|
||||
last = items[-1] if items else {"raw": body[:1000]}
|
||||
if status != 200:
|
||||
raise RuntimeError(
|
||||
f"secrets_update failed for {entry_id}: status={status}, body={body[:500]}"
|
||||
)
|
||||
return last
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = parse_args()
|
||||
|
||||
try:
|
||||
url, auth, encryption_key = resolve_connection_settings(args)
|
||||
updates = load_updates(args.csv)
|
||||
except Exception as exc:
|
||||
print(f"ERROR: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
print(f"Loaded {len(updates)} entries from {args.csv}")
|
||||
|
||||
if args.dry_run:
|
||||
for entry_id, secrets_obj in updates.items():
|
||||
print(
|
||||
json.dumps(
|
||||
{"id": entry_id, "secrets_obj": secrets_obj},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
return 0
|
||||
|
||||
try:
|
||||
session_id = initialize_session(url, auth, encryption_key, args.user_agent)
|
||||
entry_index = load_entry_index(
|
||||
url, auth, encryption_key, args.user_agent, session_id
|
||||
)
|
||||
except Exception as exc:
|
||||
print(f"ERROR: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
success = 0
|
||||
failures = 0
|
||||
for request_id, (entry_id, secrets_obj) in enumerate(updates.items(), start=2):
|
||||
try:
|
||||
if entry_id not in entry_index:
|
||||
raise RuntimeError(
|
||||
f"entry id not found in secrets_find results: {entry_id}"
|
||||
)
|
||||
entry_name, entry_folder = entry_index[entry_id]
|
||||
result = call_secrets_update(
|
||||
url,
|
||||
auth,
|
||||
encryption_key,
|
||||
args.user_agent,
|
||||
session_id,
|
||||
request_id,
|
||||
entry_id,
|
||||
entry_name,
|
||||
entry_folder,
|
||||
secrets_obj,
|
||||
)
|
||||
if "error" in result:
|
||||
failures += 1
|
||||
print(
|
||||
json.dumps(
|
||||
{"id": entry_id, "status": "error", "result": result},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
file=sys.stderr,
|
||||
)
|
||||
else:
|
||||
success += 1
|
||||
print(
|
||||
json.dumps(
|
||||
{"id": entry_id, "status": "ok", "result": result},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
except Exception as exc:
|
||||
failures += 1
|
||||
print(f"{entry_id}: ERROR: {exc}", file=sys.stderr)
|
||||
|
||||
print(f"Done. success={success} failure={failures}")
|
||||
return 0 if failures == 0 else 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -4,15 +4,24 @@
|
||||
# 参考: .gitea/workflows/secrets.yml
|
||||
#
|
||||
# 所需配置:
|
||||
# - secrets.RELEASE_TOKEN (必选) Release 上传用,值为 Gitea PAT
|
||||
# - secrets.RELEASE_TOKEN (可选,推荐) Gitea PAT;未配置则工作流跳过 Release 创建与产物上传
|
||||
# - vars.WEBHOOK_URL (可选) 飞书通知
|
||||
# - vars.DEPLOY_HOST (可选) 部署目标 SSH 主机(IP 或域名)
|
||||
# - vars.DEPLOY_USER (可选) SSH 用户名
|
||||
# - secrets.DEPLOY_SSH_KEY (可选) SSH 私钥 PEM 全文(原始字符,含 BEGIN/END 行);通过 DEPLOY_SSH_KEY_FILE 写入 API
|
||||
#
|
||||
# 注意: Gitea 不允许 secret/variable 名以 GITEA_ 或 GITHUB_ 开头,故使用 RELEASE_TOKEN
|
||||
# 注意:
|
||||
# - Gitea 不允许 secret/variable 名以 GITEA_ 或 GITHUB_ 开头,故使用 RELEASE_TOKEN
|
||||
# - Gitea Actions 的 secrets(API 的 data 字段,及网页里粘贴的值)必须是未经 base64 的原始值。
|
||||
# 若事先 base64 再写入,工作流里拿到的仍是「一串 base64 文本」,SSH/OpenSSH 无法识别,部署会失败。
|
||||
# DEPLOY_SSH_KEY 须与 .pem 文件内容一致:本脚本用 jq --rawfile 按原文上传。
|
||||
# - Variables 的 value 字段同样为原始字符串,不要 base64。
|
||||
#
|
||||
# 用法:
|
||||
# 1. 从 ~/.config/gitea/config.env 读取 GITEA_URL, GITEA_TOKEN, GITEA_WEBHOOK_URL
|
||||
# 2. 或通过环境变量覆盖: GITEA_TOKEN(作为 RELEASE_TOKEN 的值), WEBHOOK_URL
|
||||
# 3. 或使用 secrets CLI 获取: 需 DATABASE_URL,从 refining/service gitea 读取
|
||||
# 2. 或通过环境变量覆盖: GITEA_TOKEN(作为 RELEASE_TOKEN 的值), WEBHOOK_URL,
|
||||
# DEPLOY_HOST, DEPLOY_USER, DEPLOY_SSH_KEY_FILE(部署到 ECS)
|
||||
# 3. 凭据勿用 base64;部署私钥路径见 DEPLOY_SSH_KEY_FILE
|
||||
#
|
||||
|
||||
set -e
|
||||
@@ -21,26 +30,41 @@ OWNER="refining"
|
||||
REPO="secrets"
|
||||
|
||||
# 解析参数
|
||||
USE_SECRETS_CLI=false
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case $1 in
|
||||
--from-secrets) USE_SECRETS_CLI=true; shift ;;
|
||||
--from-secrets)
|
||||
echo "❌ --from-secrets 尚未实现,请使用 ~/.config/gitea/config.env 或环境变量" >&2
|
||||
exit 1
|
||||
;;
|
||||
-h|--help)
|
||||
echo "用法: $0 [--from-secrets]"
|
||||
echo "用法: $0"
|
||||
echo ""
|
||||
echo " --from-secrets 从 secrets CLI (refining/service gitea) 获取 token 和 webhook_url"
|
||||
echo " 否则从 ~/.config/gitea/config.env 读取"
|
||||
echo "从 ~/.config/gitea/config.env 读取,或由环境变量覆盖。"
|
||||
echo ""
|
||||
echo "环境变量覆盖:"
|
||||
echo " GITEA_URL Gitea 实例地址"
|
||||
echo " GITEA_TOKEN 用于 Release 上传的 PAT (创建 RELEASE_TOKEN secret)"
|
||||
echo " WEBHOOK_URL 飞书 Webhook URL (创建 variable,可选)"
|
||||
echo "环境变量:"
|
||||
echo " GITEA_URL Gitea 实例根地址(可误带尾部 /api/v1,脚本会规范化后拼接)"
|
||||
echo " GITEA_TOKEN 用于 Release 的 PAT → secrets.RELEASE_TOKEN"
|
||||
echo " WEBHOOK_URL 或 GITEA_WEBHOOK_URL → vars.WEBHOOK_URL(可选)"
|
||||
echo " DEPLOY_HOST 部署 SSH 主机(可选,须与下面两项同时设置)"
|
||||
echo " DEPLOY_USER 部署 SSH 用户"
|
||||
echo " DEPLOY_SSH_KEY_FILE 本地 PEM 路径 → secrets.DEPLOY_SSH_KEY(原文上传,勿 base64)"
|
||||
exit 0
|
||||
;;
|
||||
*) shift ;;
|
||||
*)
|
||||
echo "❌ 未知参数: $1" >&2
|
||||
echo " 使用 $0 --help 查看用法" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
for cmd in curl jq; do
|
||||
if ! command -v "$cmd" &>/dev/null; then
|
||||
echo "❌ 未找到命令: $cmd(本脚本依赖 curl 与 jq)" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
# 加载配置
|
||||
load_config() {
|
||||
local config="$HOME/.config/gitea/config.env"
|
||||
@@ -50,26 +74,6 @@ load_config() {
|
||||
fi
|
||||
}
|
||||
|
||||
# 从 secrets CLI 获取 gitea 凭据
|
||||
fetch_from_secrets() {
|
||||
if ! command -v secrets &>/dev/null; then
|
||||
echo "❌ secrets CLI 未找到,请先构建: cargo build --release" >&2
|
||||
return 1
|
||||
fi
|
||||
# 输出 JSON 格式便于解析;需要 --show-secrets
|
||||
# secrets 当前无 JSON 输出,用简单解析
|
||||
local out
|
||||
out=$(secrets search -n refining --kind service -q gitea --show-secrets 2>/dev/null || true)
|
||||
if [[ -z "$out" ]]; then
|
||||
echo "❌ 未找到 refining/service gitea 记录" >&2
|
||||
return 1
|
||||
fi
|
||||
# 简化:从 metadata 和 secrets 中提取,实际格式需根据 search 输出调整
|
||||
# 此处仅作占位,实际解析较复杂;建议用户优先用 config.env
|
||||
echo "⚠️ --from-secrets 暂不支持自动解析,请使用 config.env 或环境变量" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
load_config
|
||||
|
||||
# 优先使用环境变量
|
||||
@@ -84,18 +88,17 @@ if [[ -z "$GITEA_URL" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 去掉 URL 尾部斜杠
|
||||
# 规范为实例根 URL:去尾部斜杠,并去掉重复的 .../api/v1 后缀(避免拼成 .../api/v1/api/v1)
|
||||
GITEA_URL="${GITEA_URL%/}"
|
||||
# 确保使用 /api/v1 基础路径(若用户只写了根 URL)
|
||||
[[ "$GITEA_URL" != *"/api/v1"* ]] || true
|
||||
while [[ "$GITEA_URL" == */api/v1 ]]; do
|
||||
GITEA_URL="${GITEA_URL%/api/v1}"
|
||||
GITEA_URL="${GITEA_URL%/}"
|
||||
done
|
||||
|
||||
API_BASE="${GITEA_URL}/api/v1"
|
||||
|
||||
# 获取 GITEA_TOKEN(作为 workflow 中 secrets.RELEASE_TOKEN 的值)
|
||||
if [[ -z "$GITEA_TOKEN" ]]; then
|
||||
if $USE_SECRETS_CLI; then
|
||||
fetch_from_secrets || exit 1
|
||||
fi
|
||||
echo "❌ GITEA_TOKEN 未配置"
|
||||
echo " 在 ~/.config/gitea/config.env 中设置,或 export GITEA_TOKEN=xxx" >&2
|
||||
echo " Token 需具备 repo 写权限(创建 Release、上传附件)" >&2
|
||||
@@ -107,12 +110,13 @@ echo "配置 Gitea Actions: $OWNER/$REPO"
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
echo ""
|
||||
|
||||
# 1. 创建 Secret: RELEASE_TOKEN
|
||||
# 1. 创建 Secret: RELEASE_TOKEN(data = PAT 原文,勿 base64)
|
||||
echo "1. 创建 Secret: RELEASE_TOKEN"
|
||||
secret_payload=$(jq -n --arg t "$GITEA_TOKEN" '{data: $t}')
|
||||
resp=$(curl -s -w "\n%{http_code}" -X PUT \
|
||||
-H "Authorization: token $GITEA_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"data\":\"${GITEA_TOKEN}\"}" \
|
||||
-d "$secret_payload" \
|
||||
"${API_BASE}/repos/${OWNER}/${REPO}/actions/secrets/RELEASE_TOKEN")
|
||||
http_code=$(echo "$resp" | tail -n1)
|
||||
body=$(echo "$resp" | sed '$d')
|
||||
@@ -125,15 +129,16 @@ else
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 2. 创建/更新 Variable: WEBHOOK_URL(可选)
|
||||
# 2. 创建/更新 Variable: WEBHOOK_URL(可选,value 为原始 URL 字符串,勿 base64)
|
||||
WEBHOOK_VALUE="${WEBHOOK_URL:-$GITEA_WEBHOOK_URL}"
|
||||
if [[ -n "$WEBHOOK_VALUE" ]]; then
|
||||
echo ""
|
||||
echo "2. 创建/更新 Variable: WEBHOOK_URL"
|
||||
var_payload=$(jq -n --arg v "$WEBHOOK_VALUE" '{value: $v}')
|
||||
resp=$(curl -s -w "\n%{http_code}" -X POST \
|
||||
-H "Authorization: token $GITEA_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"value\":\"${WEBHOOK_VALUE}\"}" \
|
||||
-d "$var_payload" \
|
||||
"${API_BASE}/repos/${OWNER}/${REPO}/actions/variables/WEBHOOK_URL")
|
||||
http_code=$(echo "$resp" | tail -n1)
|
||||
body=$(echo "$resp" | sed '$d')
|
||||
@@ -145,7 +150,7 @@ if [[ -n "$WEBHOOK_VALUE" ]]; then
|
||||
resp=$(curl -s -w "\n%{http_code}" -X PUT \
|
||||
-H "Authorization: token $GITEA_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"value\":\"${WEBHOOK_VALUE}\"}" \
|
||||
-d "$var_payload" \
|
||||
"${API_BASE}/repos/${OWNER}/${REPO}/actions/variables/WEBHOOK_URL")
|
||||
http_code=$(echo "$resp" | tail -n1)
|
||||
if [[ "$http_code" == "200" || "$http_code" == "204" ]]; then
|
||||
@@ -162,6 +167,68 @@ else
|
||||
echo " 飞书通知将不可用;如需可后续在仓库 Settings → Variables 中添加"
|
||||
fi
|
||||
|
||||
# 3. 部署用 Variable + Secret(与 .gitea/workflows/secrets.yml 中 deploy-mcp 一致)
|
||||
upsert_repo_variable() {
|
||||
local var_name="$1" var_value="$2"
|
||||
local var_payload http_code body resp
|
||||
var_payload=$(jq -n --arg v "$var_value" '{value: $v}')
|
||||
resp=$(curl -s -w "\n%{http_code}" -X POST \
|
||||
-H "Authorization: token $GITEA_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$var_payload" \
|
||||
"${API_BASE}/repos/${OWNER}/${REPO}/actions/variables/${var_name}")
|
||||
http_code=$(echo "$resp" | tail -n1)
|
||||
if [[ "$http_code" == "200" || "$http_code" == "201" || "$http_code" == "204" ]]; then
|
||||
return 0
|
||||
fi
|
||||
if [[ "$http_code" == "409" ]]; then
|
||||
resp=$(curl -s -w "\n%{http_code}" -X PUT \
|
||||
-H "Authorization: token $GITEA_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$var_payload" \
|
||||
"${API_BASE}/repos/${OWNER}/${REPO}/actions/variables/${var_name}")
|
||||
http_code=$(echo "$resp" | tail -n1)
|
||||
[[ "$http_code" == "200" || "$http_code" == "204" ]]
|
||||
return
|
||||
fi
|
||||
body=$(echo "$resp" | sed '$d')
|
||||
echo " ❌ 变量 ${var_name} 失败 (HTTP $http_code)" >&2
|
||||
echo "$body" | jq -r '.message // .' 2>/dev/null || echo "$body" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
if [[ -n "$DEPLOY_HOST" && -n "$DEPLOY_USER" && -n "$DEPLOY_SSH_KEY_FILE" ]]; then
|
||||
echo ""
|
||||
echo "3. 部署目标: vars.DEPLOY_HOST / vars.DEPLOY_USER + secrets.DEPLOY_SSH_KEY"
|
||||
if [[ ! -f "$DEPLOY_SSH_KEY_FILE" ]]; then
|
||||
echo " ❌ DEPLOY_SSH_KEY_FILE 不是文件: $DEPLOY_SSH_KEY_FILE" >&2
|
||||
exit 1
|
||||
fi
|
||||
upsert_repo_variable DEPLOY_HOST "$DEPLOY_HOST" || exit 1
|
||||
echo " ✓ DEPLOY_HOST"
|
||||
upsert_repo_variable DEPLOY_USER "$DEPLOY_USER" || exit 1
|
||||
echo " ✓ DEPLOY_USER"
|
||||
# PEM 原文写入 secret.data;勿对文件先做 base64,否则 runner 侧 ssh 无法解析密钥
|
||||
secret_payload=$(jq -n --rawfile k "$DEPLOY_SSH_KEY_FILE" '{data: $k}')
|
||||
resp=$(curl -s -w "\n%{http_code}" -X PUT \
|
||||
-H "Authorization: token $GITEA_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$secret_payload" \
|
||||
"${API_BASE}/repos/${OWNER}/${REPO}/actions/secrets/DEPLOY_SSH_KEY")
|
||||
http_code=$(echo "$resp" | tail -n1)
|
||||
body=$(echo "$resp" | sed '$d')
|
||||
if [[ "$http_code" == "200" || "$http_code" == "201" || "$http_code" == "204" ]]; then
|
||||
echo " ✓ DEPLOY_SSH_KEY"
|
||||
else
|
||||
echo " ❌ DEPLOY_SSH_KEY 失败 (HTTP $http_code)" >&2
|
||||
echo "$body" | jq -r '.message // .' 2>/dev/null || echo "$body" >&2
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
echo ""
|
||||
echo "3. 跳过部署配置(需同时设置 DEPLOY_HOST、DEPLOY_USER、DEPLOY_SSH_KEY_FILE)"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
echo "✓ 配置完成"
|
||||
@@ -170,6 +237,7 @@ echo ""
|
||||
echo "Workflow 将使用:"
|
||||
echo " - secrets.RELEASE_TOKEN 创建 Release 并上传二进制"
|
||||
echo " - vars.WEBHOOK_URL 发送飞书通知(如已配置)"
|
||||
echo " - vars.DEPLOY_* / secrets.DEPLOY_SSH_KEY deploy-mcp(如已配置)"
|
||||
echo ""
|
||||
echo "推送代码触发构建:"
|
||||
echo " git push origin main"
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
use anyhow::Result;
|
||||
use serde_json::{Map, Value};
|
||||
use sqlx::PgPool;
|
||||
use std::fs;
|
||||
|
||||
/// Parse "key=value" entries. Value starting with '@' reads from file.
|
||||
pub(crate) fn parse_kv(entry: &str) -> Result<(String, String)> {
|
||||
let (key, raw_val) = entry.split_once('=').ok_or_else(|| {
|
||||
anyhow::anyhow!(
|
||||
"Invalid format '{}'. Expected: key=value or key=@file",
|
||||
entry
|
||||
)
|
||||
})?;
|
||||
|
||||
let value = if let Some(path) = raw_val.strip_prefix('@') {
|
||||
fs::read_to_string(path)
|
||||
.map_err(|e| anyhow::anyhow!("Failed to read file '{}': {}", path, e))?
|
||||
} else {
|
||||
raw_val.to_string()
|
||||
};
|
||||
|
||||
Ok((key.to_string(), value))
|
||||
}
|
||||
|
||||
fn build_json(entries: &[String]) -> Result<Value> {
|
||||
let mut map = Map::new();
|
||||
for entry in entries {
|
||||
let (key, value) = parse_kv(entry)?;
|
||||
map.insert(key, Value::String(value));
|
||||
}
|
||||
Ok(Value::Object(map))
|
||||
}
|
||||
|
||||
pub async fn run(
|
||||
pool: &PgPool,
|
||||
namespace: &str,
|
||||
kind: &str,
|
||||
name: &str,
|
||||
tags: &[String],
|
||||
meta_entries: &[String],
|
||||
secret_entries: &[String],
|
||||
) -> Result<()> {
|
||||
let metadata = build_json(meta_entries)?;
|
||||
let encrypted = build_json(secret_entries)?;
|
||||
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO secrets (namespace, kind, name, tags, metadata, encrypted, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, NOW())
|
||||
ON CONFLICT (namespace, kind, name)
|
||||
DO UPDATE SET
|
||||
tags = EXCLUDED.tags,
|
||||
metadata = EXCLUDED.metadata,
|
||||
encrypted = EXCLUDED.encrypted,
|
||||
updated_at = NOW()
|
||||
"#,
|
||||
)
|
||||
.bind(namespace)
|
||||
.bind(kind)
|
||||
.bind(name)
|
||||
.bind(tags)
|
||||
.bind(&metadata)
|
||||
.bind(&encrypted)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
|
||||
println!("Added: [{}/{}] {}", namespace, kind, name);
|
||||
if !tags.is_empty() {
|
||||
println!(" tags: {}", tags.join(", "));
|
||||
}
|
||||
if !meta_entries.is_empty() {
|
||||
let keys: Vec<&str> = meta_entries
|
||||
.iter()
|
||||
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
|
||||
.collect();
|
||||
println!(" metadata: {}", keys.join(", "));
|
||||
}
|
||||
if !secret_entries.is_empty() {
|
||||
let keys: Vec<&str> = secret_entries
|
||||
.iter()
|
||||
.filter_map(|s| s.split_once('=').map(|(k, _)| k))
|
||||
.collect();
|
||||
println!(" secrets: {}", keys.join(", "));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
use anyhow::Result;
|
||||
use sqlx::PgPool;
|
||||
|
||||
pub async fn run(pool: &PgPool, namespace: &str, kind: &str, name: &str) -> Result<()> {
|
||||
let result =
|
||||
sqlx::query("DELETE FROM secrets WHERE namespace = $1 AND kind = $2 AND name = $3")
|
||||
.bind(namespace)
|
||||
.bind(kind)
|
||||
.bind(name)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
|
||||
if result.rows_affected() == 0 {
|
||||
println!("Not found: [{}/{}] {}", namespace, kind, name);
|
||||
} else {
|
||||
println!("Deleted: [{}/{}] {}", namespace, kind, name);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
pub mod add;
|
||||
pub mod delete;
|
||||
pub mod search;
|
||||
pub mod update;
|
||||
@@ -1,110 +0,0 @@
|
||||
use anyhow::Result;
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::models::Secret;
|
||||
|
||||
pub async fn run(
|
||||
pool: &PgPool,
|
||||
namespace: Option<&str>,
|
||||
kind: Option<&str>,
|
||||
tag: Option<&str>,
|
||||
query: Option<&str>,
|
||||
show_secrets: bool,
|
||||
) -> Result<()> {
|
||||
let mut conditions: Vec<String> = Vec::new();
|
||||
let mut idx: i32 = 1;
|
||||
|
||||
if namespace.is_some() {
|
||||
conditions.push(format!("namespace = ${}", idx));
|
||||
idx += 1;
|
||||
}
|
||||
if kind.is_some() {
|
||||
conditions.push(format!("kind = ${}", idx));
|
||||
idx += 1;
|
||||
}
|
||||
if tag.is_some() {
|
||||
conditions.push(format!("tags @> ARRAY[${}]", idx));
|
||||
idx += 1;
|
||||
}
|
||||
if query.is_some() {
|
||||
conditions.push(format!(
|
||||
"(name ILIKE ${i} OR namespace ILIKE ${i} OR kind ILIKE ${i} OR metadata::text ILIKE ${i} OR EXISTS (SELECT 1 FROM unnest(tags) t WHERE t ILIKE ${i}))",
|
||||
i = idx
|
||||
));
|
||||
}
|
||||
|
||||
let where_clause = if conditions.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("WHERE {}", conditions.join(" AND "))
|
||||
};
|
||||
|
||||
let sql = format!(
|
||||
"SELECT * FROM secrets {} ORDER BY namespace, kind, name",
|
||||
where_clause
|
||||
);
|
||||
|
||||
let mut q = sqlx::query_as::<_, Secret>(&sql);
|
||||
if let Some(v) = namespace {
|
||||
q = q.bind(v);
|
||||
}
|
||||
if let Some(v) = kind {
|
||||
q = q.bind(v);
|
||||
}
|
||||
if let Some(v) = tag {
|
||||
q = q.bind(v);
|
||||
}
|
||||
if let Some(v) = query {
|
||||
q = q.bind(format!("%{}%", v));
|
||||
}
|
||||
|
||||
let rows = q.fetch_all(pool).await?;
|
||||
|
||||
if rows.is_empty() {
|
||||
println!("No records found.");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for row in &rows {
|
||||
println!("[{}/{}] {}", row.namespace, row.kind, row.name,);
|
||||
println!(" id: {}", row.id);
|
||||
|
||||
if !row.tags.is_empty() {
|
||||
println!(" tags: [{}]", row.tags.join(", "));
|
||||
}
|
||||
|
||||
if row.metadata.as_object().is_some_and(|m| !m.is_empty()) {
|
||||
println!(
|
||||
" metadata: {}",
|
||||
serde_json::to_string_pretty(&row.metadata)?
|
||||
);
|
||||
}
|
||||
|
||||
if show_secrets {
|
||||
println!(
|
||||
" secrets: {}",
|
||||
serde_json::to_string_pretty(&row.encrypted)?
|
||||
);
|
||||
} else {
|
||||
let keys: Vec<String> = row
|
||||
.encrypted
|
||||
.as_object()
|
||||
.map(|m| m.keys().cloned().collect())
|
||||
.unwrap_or_default();
|
||||
if !keys.is_empty() {
|
||||
println!(
|
||||
" secrets: [{}] (--show-secrets to reveal)",
|
||||
keys.join(", ")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
println!(
|
||||
" created: {}",
|
||||
row.created_at.format("%Y-%m-%d %H:%M:%S UTC")
|
||||
);
|
||||
println!();
|
||||
}
|
||||
println!("{} record(s) found.", rows.len());
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
use anyhow::Result;
|
||||
use serde_json::{Map, Value};
|
||||
use sqlx::PgPool;
|
||||
|
||||
use super::add::parse_kv;
|
||||
|
||||
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 = sqlx::query!(
|
||||
r#"
|
||||
SELECT id, tags, metadata, encrypted
|
||||
FROM secrets
|
||||
WHERE namespace = $1 AND kind = $2 AND name = $3
|
||||
"#,
|
||||
args.namespace,
|
||||
args.kind,
|
||||
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);
|
||||
|
||||
sqlx::query!(
|
||||
r#"
|
||||
UPDATE secrets
|
||||
SET tags = $1, metadata = $2, encrypted = $3, updated_at = NOW()
|
||||
WHERE id = $4
|
||||
"#,
|
||||
&tags,
|
||||
metadata,
|
||||
encrypted,
|
||||
row.id,
|
||||
)
|
||||
.execute(pool)
|
||||
.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(())
|
||||
}
|
||||
44
src/db.rs
44
src/db.rs
@@ -1,44 +0,0 @@
|
||||
use anyhow::Result;
|
||||
use sqlx::PgPool;
|
||||
use sqlx::postgres::PgPoolOptions;
|
||||
|
||||
pub async fn create_pool(database_url: &str) -> Result<PgPool> {
|
||||
let pool = PgPoolOptions::new()
|
||||
.max_connections(5)
|
||||
.connect(database_url)
|
||||
.await?;
|
||||
Ok(pool)
|
||||
}
|
||||
|
||||
pub async fn migrate(pool: &PgPool) -> Result<()> {
|
||||
sqlx::raw_sql(
|
||||
r#"
|
||||
CREATE TABLE IF NOT EXISTS secrets (
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||
namespace VARCHAR(64) NOT NULL,
|
||||
kind VARCHAR(64) NOT NULL,
|
||||
name VARCHAR(256) NOT NULL,
|
||||
tags TEXT[] NOT NULL DEFAULT '{}',
|
||||
metadata JSONB NOT NULL DEFAULT '{}',
|
||||
encrypted JSONB NOT NULL DEFAULT '{}',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE(namespace, kind, name)
|
||||
);
|
||||
|
||||
-- idempotent column add for existing tables
|
||||
DO $$ BEGIN
|
||||
ALTER TABLE secrets ADD COLUMN IF NOT EXISTS metadata JSONB NOT NULL DEFAULT '{}';
|
||||
EXCEPTION WHEN OTHERS THEN NULL;
|
||||
END $$;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_secrets_namespace ON secrets(namespace);
|
||||
CREATE INDEX IF NOT EXISTS idx_secrets_kind ON secrets(kind);
|
||||
CREATE INDEX IF NOT EXISTS idx_secrets_tags ON secrets USING GIN(tags);
|
||||
CREATE INDEX IF NOT EXISTS idx_secrets_metadata ON secrets USING GIN(metadata jsonb_path_ops);
|
||||
"#,
|
||||
)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
194
src/main.rs
194
src/main.rs
@@ -1,194 +0,0 @@
|
||||
mod commands;
|
||||
mod db;
|
||||
mod models;
|
||||
|
||||
use anyhow::Result;
|
||||
use clap::{Parser, Subcommand};
|
||||
use dotenvy::dotenv;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
name = "secrets",
|
||||
version,
|
||||
about = "Secrets & config manager backed by PostgreSQL"
|
||||
)]
|
||||
struct Cli {
|
||||
/// Database URL (or set DATABASE_URL env var)
|
||||
#[arg(long, env = "DATABASE_URL", global = true, default_value = "")]
|
||||
db_url: String,
|
||||
|
||||
#[command(subcommand)]
|
||||
command: Commands,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Commands {
|
||||
/// Add or update a record (upsert)
|
||||
Add {
|
||||
/// Namespace (e.g. refining, ricnsmart)
|
||||
#[arg(short, long)]
|
||||
namespace: String,
|
||||
/// Kind of record (server, service, key, ...)
|
||||
#[arg(long)]
|
||||
kind: String,
|
||||
/// Human-readable name
|
||||
#[arg(long)]
|
||||
name: String,
|
||||
/// Tags for categorization (repeatable)
|
||||
#[arg(long = "tag")]
|
||||
tags: Vec<String>,
|
||||
/// Plaintext metadata entry: key=value (repeatable, key=@file reads from file)
|
||||
#[arg(long = "meta", short = 'm')]
|
||||
meta: Vec<String>,
|
||||
/// Secret entry: key=value (repeatable, key=@file reads from file)
|
||||
#[arg(long = "secret", short = 's')]
|
||||
secrets: Vec<String>,
|
||||
},
|
||||
|
||||
/// Search records
|
||||
Search {
|
||||
/// Filter by namespace
|
||||
#[arg(short, long)]
|
||||
namespace: Option<String>,
|
||||
/// Filter by kind
|
||||
#[arg(long)]
|
||||
kind: Option<String>,
|
||||
/// Filter by tag
|
||||
#[arg(long)]
|
||||
tag: Option<String>,
|
||||
/// Search by keyword (matches name, namespace, kind)
|
||||
#[arg(short, long)]
|
||||
query: Option<String>,
|
||||
/// Reveal encrypted secret values
|
||||
#[arg(long)]
|
||||
show_secrets: bool,
|
||||
},
|
||||
|
||||
/// Delete a record
|
||||
Delete {
|
||||
/// Namespace
|
||||
#[arg(short, long)]
|
||||
namespace: String,
|
||||
/// Kind
|
||||
#[arg(long)]
|
||||
kind: String,
|
||||
/// Name
|
||||
#[arg(long)]
|
||||
name: String,
|
||||
},
|
||||
|
||||
/// Incrementally update an existing record (merge semantics)
|
||||
Update {
|
||||
/// Namespace (e.g. refining, ricnsmart)
|
||||
#[arg(short, long)]
|
||||
namespace: String,
|
||||
/// Kind of record (server, service, key, ...)
|
||||
#[arg(long)]
|
||||
kind: String,
|
||||
/// Human-readable name
|
||||
#[arg(long)]
|
||||
name: String,
|
||||
/// Add a tag (repeatable)
|
||||
#[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>,
|
||||
/// Remove a metadata field by key (repeatable)
|
||||
#[arg(long = "remove-meta")]
|
||||
remove_meta: Vec<String>,
|
||||
/// Set or overwrite a secret field: key=value (repeatable, @file supported)
|
||||
#[arg(long = "secret", short = 's')]
|
||||
secrets: Vec<String>,
|
||||
/// Remove a secret field by key (repeatable)
|
||||
#[arg(long = "remove-secret")]
|
||||
remove_secrets: Vec<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
dotenv().ok();
|
||||
|
||||
let cli = Cli::parse();
|
||||
|
||||
let db_url = if cli.db_url.is_empty() {
|
||||
std::env::var("DATABASE_URL").map_err(|_| {
|
||||
anyhow::anyhow!("DATABASE_URL not set. Use --db-url or set DATABASE_URL env var.")
|
||||
})?
|
||||
} else {
|
||||
cli.db_url.clone()
|
||||
};
|
||||
|
||||
let pool = db::create_pool(&db_url).await?;
|
||||
db::migrate(&pool).await?;
|
||||
|
||||
match &cli.command {
|
||||
Commands::Add {
|
||||
namespace,
|
||||
kind,
|
||||
name,
|
||||
tags,
|
||||
meta,
|
||||
secrets,
|
||||
} => {
|
||||
commands::add::run(&pool, namespace, kind, name, tags, meta, secrets).await?;
|
||||
}
|
||||
Commands::Search {
|
||||
namespace,
|
||||
kind,
|
||||
tag,
|
||||
query,
|
||||
show_secrets,
|
||||
} => {
|
||||
commands::search::run(
|
||||
&pool,
|
||||
namespace.as_deref(),
|
||||
kind.as_deref(),
|
||||
tag.as_deref(),
|
||||
query.as_deref(),
|
||||
*show_secrets,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Commands::Delete {
|
||||
namespace,
|
||||
kind,
|
||||
name,
|
||||
} => {
|
||||
commands::delete::run(&pool, namespace, kind, name).await?;
|
||||
}
|
||||
Commands::Update {
|
||||
namespace,
|
||||
kind,
|
||||
name,
|
||||
add_tags,
|
||||
remove_tags,
|
||||
meta,
|
||||
remove_meta,
|
||||
secrets,
|
||||
remove_secrets,
|
||||
} => {
|
||||
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?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, sqlx::FromRow)]
|
||||
pub struct Secret {
|
||||
pub id: Uuid,
|
||||
pub namespace: String,
|
||||
pub kind: String,
|
||||
pub name: String,
|
||||
pub tags: Vec<String>,
|
||||
pub metadata: Value,
|
||||
pub encrypted: Value,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
Reference in New Issue
Block a user