Compare commits
34 Commits
secrets-mc
...
secrets-mc
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 |
@@ -3,13 +3,12 @@ name: Secrets MCP — Build & Release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, feat/mcp, mcp]
|
||||
paths:
|
||||
- 'crates/**'
|
||||
- 'Cargo.toml'
|
||||
- 'Cargo.lock'
|
||||
# systemd / 部署模板变更也应跑构建(产物无变时可快速跳过 check)
|
||||
- 'deploy/**'
|
||||
- '.gitea/workflows/**'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
@@ -20,221 +19,167 @@ permissions:
|
||||
|
||||
env:
|
||||
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' crates/secrets-mcp/Cargo.toml | sed 's/.*"\(.*\)".*/\1/')
|
||||
tag="secrets-mcp-${version}"
|
||||
previous_tag=$(git tag --list 'secrets-mcp-*' --sort=-v:refname | awk -v tag="$tag" '$0 != tag { print; exit }')
|
||||
|
||||
echo "version=${version}" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=${tag}" >> "$GITHUB_OUTPUT"
|
||||
echo "previous_tag=${previous_tag}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
if git rev-parse "refs/tags/${tag}" >/dev/null 2>&1; then
|
||||
echo "⚠ 版本 ${tag} 已存在,将覆盖重新发版。"
|
||||
echo "tag_exists=true" >> "$GITHUB_OUTPUT"
|
||||
echo "版本 ${tag} 已存在"
|
||||
else
|
||||
echo "tag_exists=false" >> "$GITHUB_OUTPUT"
|
||||
echo "将创建新版本 ${tag}"
|
||||
echo "tag_exists=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: 严格拦截重复版本
|
||||
if: steps.ver.outputs.tag_exists == 'true'
|
||||
# ── Rust 工具链 ──────────────────────────────────────────────────────
|
||||
- name: 安装 Rust 与 musl 工具链
|
||||
run: |
|
||||
echo "错误: 版本 ${{ steps.ver.outputs.tag }} 已存在,禁止重复发版。"
|
||||
echo "请先 bump crates/secrets-mcp/Cargo.toml 中的 version,并执行 cargo build 同步 Cargo.lock。"
|
||||
exit 1
|
||||
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 "secrets-mcp ${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
|
||||
|
||||
check:
|
||||
name: 质量检查 (fmt / clippy / test)
|
||||
runs-on: debian
|
||||
timeout-minutes: 15
|
||||
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 Linux (secrets-mcp, musl)
|
||||
needs: [version, check]
|
||||
runs-on: debian
|
||||
timeout-minutes: 25
|
||||
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-
|
||||
|
||||
- name: 构建 secrets-mcp (musl)
|
||||
run: |
|
||||
cargo build --release --locked --target x86_64-unknown-linux-musl -p secrets-mcp
|
||||
strip target/x86_64-unknown-linux-musl/release/${{ env.MCP_BINARY }}
|
||||
|
||||
- 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.MCP_BINARY }}"
|
||||
archive="${{ env.MCP_BINARY }}-${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")"
|
||||
sha256sum "$archive" > "${archive}.sha256"
|
||||
release_url="${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${{ needs.version.outputs.release_id }}/assets"
|
||||
curl -fsS -H "Authorization: token $RELEASE_TOKEN" \
|
||||
-F "attachment=@${archive}" "$release_url"
|
||||
curl -fsS -H "Authorization: token $RELEASE_TOKEN" \
|
||||
-F "attachment=@${archive}.sha256" "$release_url"
|
||||
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} 已发布"
|
||||
|
||||
# ── 飞书汇总通知 ─────────────────────────────────────────────────────
|
||||
- name: 飞书通知
|
||||
if: always()
|
||||
env:
|
||||
WEBHOOK_URL: ${{ vars.WEBHOOK_URL }}
|
||||
run: |
|
||||
[ -z "$WEBHOOK_URL" ] && exit 0
|
||||
command -v jq >/dev/null 2>&1 || (sudo apt-get update -qq && sudo apt-get install -y -qq jq)
|
||||
tag="${{ needs.version.outputs.tag }}"
|
||||
commit=$(git log -1 --pretty=format:"%s" 2>/dev/null || echo "N/A")
|
||||
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 }}"
|
||||
result="${{ job.status }}"
|
||||
if [ "$result" = "success" ]; then icon="✅"; else icon="❌"; fi
|
||||
msg="secrets-mcp linux 构建${icon}
|
||||
msg="secrets-mcp 构建&发版 ${icon}
|
||||
版本:${tag}
|
||||
提交:${commit}
|
||||
作者:${{ github.actor }}
|
||||
@@ -242,46 +187,21 @@ jobs:
|
||||
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-mcp:
|
||||
deploy:
|
||||
name: 部署 secrets-mcp
|
||||
needs: [version, build-linux]
|
||||
# 部署目标由仓库 Actions 配置:vars.DEPLOY_HOST / vars.DEPLOY_USER;私钥 secrets.DEPLOY_SSH_KEY(PEM 原文,勿 base64)
|
||||
# (可用 scripts/setup-gitea-actions.sh 或 Gitea API 写入,勿写进本文件)
|
||||
# Google OAuth / SERVER_MASTER_KEY / SECRETS_DATABASE_URL 等勿写入 CI,请在 ECS 上
|
||||
# /opt/secrets-mcp/.env 配置(见 deploy/.env.example)。
|
||||
# 若仓库 main 仍为纯 CLI、仅 feat/mcp 含本 workflow,请去掉条件里的 main,避免误部署。
|
||||
if: needs.build-linux.result == 'success' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/feat/mcp' || github.ref == 'refs/heads/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:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- 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
|
||||
sudo apt-get update -qq && sudo apt-get install -y -qq pkg-config musl-tools
|
||||
rustup target add x86_64-unknown-linux-musl
|
||||
|
||||
- name: 缓存 Cargo
|
||||
uses: actions/cache@v4
|
||||
- name: 下载构建产物
|
||||
uses: actions/download-artifact@v3
|
||||
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-
|
||||
|
||||
- name: 构建 secrets-mcp
|
||||
run: |
|
||||
cargo build --release --locked --target x86_64-unknown-linux-musl -p secrets-mcp
|
||||
strip target/x86_64-unknown-linux-musl/release/${{ env.MCP_BINARY }}
|
||||
name: ${{ env.MCP_BINARY }}-linux-musl
|
||||
path: /tmp/artifact
|
||||
|
||||
- name: 部署到阿里云 ECS
|
||||
env:
|
||||
@@ -290,16 +210,15 @@ jobs:
|
||||
DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
|
||||
run: |
|
||||
if [ -z "$DEPLOY_HOST" ] || [ -z "$DEPLOY_USER" ] || [ -z "$DEPLOY_SSH_KEY" ]; then
|
||||
echo "部署跳过:请在仓库 Actions 中配置 vars.DEPLOY_HOST、vars.DEPLOY_USER 与 secrets.DEPLOY_SSH_KEY"
|
||||
echo "部署跳过:请配置 vars.DEPLOY_HOST、vars.DEPLOY_USER 与 secrets.DEPLOY_SSH_KEY"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "$DEPLOY_SSH_KEY" > /tmp/deploy_key
|
||||
chmod 600 /tmp/deploy_key
|
||||
|
||||
SCP="scp -i /tmp/deploy_key -o StrictHostKeyChecking=no"
|
||||
|
||||
$SCP target/x86_64-unknown-linux-musl/release/${{ env.MCP_BINARY }} \
|
||||
scp -i /tmp/deploy_key -o StrictHostKeyChecking=no \
|
||||
"/tmp/artifact/${MCP_BINARY}" \
|
||||
"${DEPLOY_USER}@${DEPLOY_HOST}:/tmp/secrets-mcp.new"
|
||||
|
||||
ssh -i /tmp/deploy_key -o StrictHostKeyChecking=no "${DEPLOY_USER}@${DEPLOY_HOST}" "
|
||||
@@ -309,7 +228,6 @@ jobs:
|
||||
sleep 2
|
||||
sudo systemctl is-active secrets-mcp && echo '服务启动成功' || (sudo journalctl -u secrets-mcp -n 20 && exit 1)
|
||||
"
|
||||
|
||||
rm -f /tmp/deploy_key
|
||||
|
||||
- name: 飞书通知
|
||||
@@ -318,94 +236,13 @@ jobs:
|
||||
WEBHOOK_URL: ${{ vars.WEBHOOK_URL }}
|
||||
run: |
|
||||
[ -z "$WEBHOOK_URL" ] && exit 0
|
||||
command -v jq >/dev/null 2>&1 || (sudo apt-get update -qq && sudo apt-get install -y -qq jq)
|
||||
tag="${{ needs.version.outputs.tag }}"
|
||||
commit=$(git log -1 --pretty=format:"%s" 2>/dev/null || echo "N/A")
|
||||
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}
|
||||
提交:${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"
|
||||
|
||||
publish-release:
|
||||
name: 发布草稿 Release
|
||||
needs: [version, build-linux]
|
||||
if: always() && needs.version.outputs.release_id != ''
|
||||
runs-on: debian
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: 发布草稿
|
||||
env:
|
||||
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
run: |
|
||||
[ -z "$RELEASE_TOKEN" ] && exit 0
|
||||
|
||||
linux_r="${{ needs.build-linux.result }}"
|
||||
if [ "$linux_r" != "success" ]; then
|
||||
echo "linux 构建未成功,保留草稿 Release"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
release_api="${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${{ needs.version.outputs.release_id }}"
|
||||
http_code=$(curl -sS -o /tmp/publish-release.json -w '%{http_code}' \
|
||||
-H "Authorization: token $RELEASE_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-X PATCH "$release_api" \
|
||||
-d '{"draft":false}')
|
||||
|
||||
if [ "$http_code" != "200" ]; then
|
||||
echo "发布草稿 Release 失败 (HTTP ${http_code})"
|
||||
cat /tmp/publish-release.json 2>/dev/null || true
|
||||
exit 1
|
||||
fi
|
||||
echo "Release 已发布"
|
||||
|
||||
- name: 飞书汇总通知
|
||||
if: always()
|
||||
env:
|
||||
WEBHOOK_URL: ${{ vars.WEBHOOK_URL }}
|
||||
run: |
|
||||
[ -z "$WEBHOOK_URL" ] && exit 0
|
||||
command -v jq >/dev/null 2>&1 || (sudo apt-get update -qq && sudo apt-get install -y -qq jq)
|
||||
|
||||
tag="${{ needs.version.outputs.tag }}"
|
||||
tag_exists="${{ needs.version.outputs.tag_exists }}"
|
||||
commit="${{ github.event.head_commit.message }}"
|
||||
[ -z "$commit" ] && commit="${{ github.sha }}"
|
||||
url="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}"
|
||||
|
||||
linux_r="${{ needs.build-linux.result }}"
|
||||
publish_r="${{ job.status }}"
|
||||
|
||||
icon() { case "$1" in success) echo "✅";; skipped) echo "⏭";; *) echo "❌";; esac; }
|
||||
|
||||
if [ "$linux_r" = "success" ] && [ "$publish_r" = "success" ]; then
|
||||
status="发布成功 ✅"
|
||||
elif [ "$linux_r" != "success" ]; then
|
||||
status="构建失败 ❌"
|
||||
else
|
||||
status="发布失败 ❌"
|
||||
fi
|
||||
|
||||
if [ "$tag_exists" = "false" ]; then
|
||||
version_line="🆕 新版本 ${tag}"
|
||||
else
|
||||
version_line="🔄 重复构建 ${tag}"
|
||||
fi
|
||||
|
||||
msg="secrets-mcp ${status}
|
||||
${version_line}
|
||||
linux $(icon "$linux_r") | Release $(icon "$publish_r")
|
||||
提交:${commit}
|
||||
作者:${{ github.actor }}
|
||||
详情:${url}"
|
||||
|
||||
payload=$(jq -n --arg text "$msg" '{msg_type: "text", content: {text: $text}}')
|
||||
curl -sS -H "Content-Type: application/json" -X POST -d "$payload" "$WEBHOOK_URL"
|
||||
|
||||
70
AGENTS.md
70
AGENTS.md
@@ -2,12 +2,13 @@
|
||||
|
||||
本仓库为 **MCP SaaS**:`secrets-core`(业务与持久化)+ `secrets-mcp`(Streamable HTTP MCP、Web、OAuth、API Key)。对外入口见 `crates/secrets-mcp`。
|
||||
|
||||
## 提交 / 发版硬规则(优先于下文)
|
||||
## 提交 / 推送硬规则(优先于下文)
|
||||
|
||||
**每次提交和推送前必须执行以下检查,无论是否明确「发版」:**
|
||||
|
||||
1. 涉及 `crates/**`、根目录 `Cargo.toml`/`Cargo.lock`、`secrets-mcp` 行为变更的提交,默认视为**需要发版**,除非明确说明「本次不发版」。
|
||||
2. 发版前检查 `crates/secrets-mcp/Cargo.toml` 的 `version`,再查 tag:`git tag -l 'secrets-mcp-*'`。
|
||||
3. 若当前版本对应 tag 已存在,须先 bump `version`,再 `cargo build` 同步 `Cargo.lock` 后提交。
|
||||
4. 提交前优先运行 `./scripts/release-check.sh`(版本/tag + `fmt` + `clippy --locked` + `test --locked`)。
|
||||
2. 提交前检查 `crates/secrets-mcp/Cargo.toml` 的 `version`,再查 tag:`git tag -l 'secrets-mcp-*'`。若当前版本对应 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`。
|
||||
|
||||
## 项目结构
|
||||
|
||||
@@ -28,7 +29,8 @@ secrets/
|
||||
|
||||
- **建议库名**:`secrets-mcp`(专用实例,与历史库名区分)。
|
||||
- **连接**:环境变量 **`SECRETS_DATABASE_URL`**(本分支无本地配置文件路径)。
|
||||
- **表**:`entries`(含 `user_id`)、`secrets`、`entries_history`、`secrets_history`、`audit_log`、`users`、`oauth_accounts`、`api_keys`,首次连接 **auto-migrate**。
|
||||
- **表**:`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**(会话表与业务表共存于该实例,无需第二套连接串)。
|
||||
|
||||
### 表结构(摘录)
|
||||
|
||||
@@ -36,15 +38,18 @@ secrets/
|
||||
entries (
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||
user_id UUID, -- 多租户:NULL=遗留行;非空=归属用户
|
||||
namespace VARCHAR(64) NOT NULL,
|
||||
kind VARCHAR(64) NOT 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
|
||||
@@ -60,7 +65,7 @@ secrets (
|
||||
)
|
||||
```
|
||||
|
||||
### users / oauth_accounts / api_keys
|
||||
### users / oauth_accounts
|
||||
|
||||
```sql
|
||||
users (
|
||||
@@ -71,6 +76,7 @@ users (
|
||||
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()
|
||||
)
|
||||
@@ -80,32 +86,31 @@ oauth_accounts (
|
||||
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)
|
||||
)
|
||||
|
||||
api_keys (
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
name VARCHAR(256) NOT NULL,
|
||||
key_hash VARCHAR(64) NOT NULL UNIQUE,
|
||||
key_prefix VARCHAR(12) NOT NULL,
|
||||
last_used_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
-- 另有唯一索引 UNIQUE(user_id, provider)(迁移中 idx_oauth_accounts_user_provider):同一用户每种 provider 至多一条关联。
|
||||
```
|
||||
|
||||
### audit_log / history
|
||||
|
||||
与迁移脚本一致:`audit_log`、`entries_history`、`secrets_history` 用于审计与时间旅行恢复;字段定义见 `crates/secrets-core/src/db.rs` 内 `migrate` SQL。
|
||||
与迁移脚本一致:`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 身份。
|
||||
|
||||
### MCP 消歧(AI 调用)
|
||||
|
||||
按 `name` 定位条目的工具(`get` / `update` / 单条 `delete` / `history` / `rollback`):若该用户下仅一条匹配则直接执行;若多条(同 `name`、不同 `folder`)则返回错误并提示补全 `folder`。`secrets_delete` 的 `dry_run=true` 与真实删除使用相同消歧规则。
|
||||
|
||||
### 字段职责
|
||||
|
||||
| 字段 | 含义 | 示例 |
|
||||
|------|------|------|
|
||||
| `namespace` | 隔离空间 | `refining` |
|
||||
| `kind` | 记录类型 | `server`, `service`, `key` |
|
||||
| `name` | 标识名 | `gitea`, `i-example0…` |
|
||||
| `folder` | 隔离空间(参与唯一键) | `refining` |
|
||||
| `type` | 软分类(不参与唯一键) | `server`, `service`, `key`, `person` |
|
||||
| `name` | 标识名 | `gitea`, `aliyun` |
|
||||
| `notes` | 非敏感说明 | 自由文本 |
|
||||
| `tags` | 标签 | `["aliyun","prod"]` |
|
||||
| `metadata` | 明文描述 | `ip`、`url`、`key_ref` |
|
||||
| `secrets.field_name` | 加密字段名(明文) | `token`, `ssh_key` |
|
||||
@@ -113,14 +118,14 @@ api_keys (
|
||||
|
||||
### PEM 共享(`key_ref`)
|
||||
|
||||
将共享 PEM 存为 `kind=key` 的 entry;其它记录在 `metadata.key_ref` 指向该 key 的 `name`。更新 key 记录后,引用方通过服务层解析合并逻辑即可使用新密钥(实现见 `secrets_core::service`)。
|
||||
将共享 PEM 存为 **`type=key`** 的 entry;其它记录在 `metadata.key_ref` 指向该 key 的 `name`(支持 `folder/name` 格式消歧)。更新 key 记录后,引用方通过服务层解析合并逻辑即可使用新密钥(实现见 `secrets_core::service::env_map`)。
|
||||
|
||||
## 代码规范
|
||||
|
||||
- 错误:业务层 `anyhow::Result`,避免生产路径 `unwrap()`。
|
||||
- 异步:`tokio` + `sqlx` async。
|
||||
- SQL:`sqlx::query` / `query_as` 参数绑定;动态 WHERE 仍须用占位符绑定。
|
||||
- 日志:运维用 `tracing`;面向用户的 Web 响应走 axum handler。
|
||||
- 日志:运维用 `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`)保持同步,鉴权以请求扩展中的用户上下文为准。
|
||||
@@ -148,11 +153,13 @@ git tag -l 'secrets-mcp-*'
|
||||
|
||||
## CI/CD
|
||||
|
||||
- **触发**:`main` / `feat/mcp`(以仓库 workflow 为准);路径含 `crates/**`、`deploy/**`、`Cargo.toml`、`Cargo.lock`。
|
||||
- **构建**:`x86_64-unknown-linux-musl` → `secrets-mcp`。
|
||||
- **Release**:tag `secrets-mcp-<version>`,上传 tar.gz + `.sha256`。
|
||||
- **部署**:可选在仓库 Actions 中配置 `vars.DEPLOY_HOST`、`vars.DEPLOY_USER` 与 `secrets.DEPLOY_SSH_KEY`(勿写进 workflow);可用 `scripts/setup-gitea-actions.sh` 调 Gitea API 写入。Actions **secrets 须为原始值**(如 PEM 全文、PAT 明文),**不要**先 base64 再写入,否则工作流内无法识别(例如 SSH 私钥无效)。**勿**在 CI 中保存 `GOOGLE_CLIENT_SECRET`、DB 密码。
|
||||
- **通知**:`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)
|
||||
|
||||
@@ -160,9 +167,8 @@ git tag -l 'secrets-mcp-*'
|
||||
|------|------|
|
||||
| `SECRETS_DATABASE_URL` | **必填**。PostgreSQL URL。 |
|
||||
| `BASE_URL` | 对外基址;OAuth 回调 `${BASE_URL}/auth/google/callback`。 |
|
||||
| `SECRETS_MCP_BIND` | 监听地址,默认 `0.0.0.0:9315`。 |
|
||||
| `SECRETS_MCP_BIND` | 监听地址,默认 `127.0.0.1:9315`(容器/远程直接暴露时需改为 `0.0.0.0:9315`)。 |
|
||||
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | 可选;仅运行时配置。 |
|
||||
| `RUST_LOG` | 如 `secrets_mcp=debug`。 |
|
||||
| `USER` | 若写入审计 `actor`,由运行环境提供。 |
|
||||
|
||||
> `SERVER_MASTER_KEY` 已不再需要。新架构下密钥由用户密码短语在客户端派生,服务端不持有。
|
||||
|
||||
40
Cargo.lock
generated
40
Cargo.lock
generated
@@ -1809,6 +1809,25 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rmp"
|
||||
version = "0.8.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rmp-serde"
|
||||
version = "1.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155"
|
||||
dependencies = [
|
||||
"rmp",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rsa"
|
||||
version = "0.9.10"
|
||||
@@ -1949,7 +1968,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "secrets-mcp"
|
||||
version = "0.1.0"
|
||||
version = "0.3.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"askama",
|
||||
@@ -1967,10 +1986,12 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sqlx",
|
||||
"time",
|
||||
"tokio",
|
||||
"tower",
|
||||
"tower-http",
|
||||
"tower-sessions",
|
||||
"tower-sessions-sqlx-store-chrono",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"urlencoding",
|
||||
@@ -2700,6 +2721,7 @@ dependencies = [
|
||||
"tower",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2765,6 +2787,22 @@ dependencies = [
|
||||
"tower-sessions-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower-sessions-sqlx-store-chrono"
|
||||
version = "0.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b295c8fc08db03246e92773c5e10119b72db6bc4240112135bebb0e49670804f"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
"chrono",
|
||||
"rmp-serde",
|
||||
"sqlx",
|
||||
"thiserror",
|
||||
"time",
|
||||
"tower-sessions-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing"
|
||||
version = "0.1.44"
|
||||
|
||||
42
README.md
42
README.md
@@ -19,15 +19,24 @@ cargo build --release -p secrets-mcp
|
||||
|------|------|
|
||||
| `SECRETS_DATABASE_URL` | **必填**。PostgreSQL 连接串(建议专用库,如 `secrets-mcp`)。 |
|
||||
| `BASE_URL` | 对外访问基址;OAuth 回调为 `{BASE_URL}/auth/google/callback`。默认 `http://localhost:9315`。 |
|
||||
| `SECRETS_MCP_BIND` | 监听地址,默认 `0.0.0.0:9315`。反代时常为 `127.0.0.1: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`。 |
|
||||
|
||||
```bash
|
||||
cargo run -p secrets-mcp
|
||||
```
|
||||
|
||||
- **Web**:`BASE_URL`(登录、Dashboard、设置密码短语、创建 API Key)。
|
||||
- **MCP**:Streamable HTTP 基址 `{BASE_URL}/mcp`,需 `Authorization: Bearer <api_key>` + `X-Encryption-Key: <hex>` 请求头。
|
||||
- **MCP**:Streamable HTTP 基址 `{BASE_URL}/mcp`,需 `Authorization: Bearer <api_key>` + `X-Encryption-Key: <hex>` 请求头(读密文工具须带密钥)。
|
||||
|
||||
## MCP 与 AI 工作流(v0.3+)
|
||||
|
||||
条目在逻辑上以 **`(folder, name)`** 在用户内唯一(数据库唯一索引:`user_id + folder + name`)。同名可在不同 folder 下各存一条(例如 `refining/aliyun` 与 `ricnsmart/aliyun`)。
|
||||
|
||||
- **`secrets_search`**:发现条目(可按 query / folder / type / name 过滤);不要求加密头。
|
||||
- **`secrets_get` / `secrets_update` / `secrets_delete`(按 name)/ `secrets_history` / `secrets_rollback`**:仅 `name` 且全局唯一则直接命中;若多条同名,返回消歧错误,需在参数中补 **`folder`**。
|
||||
- **`secrets_delete`**:`dry_run=true` 时与真实删除相同的消歧规则——唯一则预览一条,多条则报错并要求 `folder`。
|
||||
|
||||
## 加密架构(混合 E2EE)
|
||||
|
||||
@@ -77,7 +86,7 @@ flowchart LR
|
||||
### 敏感数据传输
|
||||
|
||||
- **OAuth `client_secret`** 只存服务端环境变量,不发给浏览器
|
||||
- **API Key** 创建时原始 key 仅展示一次,库中只存 SHA-256 哈希
|
||||
- **API Key** 当前存放在 `users.api_key`,Dashboard 会明文展示并可重置
|
||||
- **X-Encryption-Key** 随 MCP 请求经 TLS 传输,服务端仅在请求处理期间持有(不持久化)
|
||||
- **生产环境必须走 HTTPS/TLS**
|
||||
|
||||
@@ -121,13 +130,14 @@ flowchart LR
|
||||
|
||||
## 数据模型
|
||||
|
||||
主表 **`entries`**(`namespace`、`kind`、`name`、`tags`、`metadata`,多租户时带 `user_id`)+ 子表 **`secrets`**(每行一个加密字段:`field_name`、`encrypted`)。另有 `entries_history`、`secrets_history`、`audit_log`,以及 **`users`**(含 `key_salt`、`key_check`、`key_params`)、**`oauth_accounts`**、**`api_keys`**。首次连库自动迁移建表。
|
||||
主表 **`entries`**(`folder`、`type`、`name`、`notes`、`tags`、`metadata`,多租户时带 `user_id`)+ 子表 **`secrets`**(每行一个加密字段:`field_name`、`encrypted`)。**唯一性**:`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`);已有库可对照 [`scripts/migrate-v0.3.0.sql`](scripts/migrate-v0.3.0.sql) 做列重命名与索引重建。**Web 登录会话**(tower-sessions)使用同一 `SECRETS_DATABASE_URL`,进程启动时对会话存储执行迁移(见 `secrets-mcp` 中 `PostgresStore::migrate`),无需额外环境变量。
|
||||
|
||||
| 位置 | 字段 | 说明 |
|
||||
|------|------|------|
|
||||
| entries | namespace | 一级隔离,如 `refining`、`ricnsmart` |
|
||||
| entries | kind | `server`、`service`、`key` 等(可扩展) |
|
||||
| entries | name | 人类可读标识 |
|
||||
| entries | folder | 组织/隔离空间,如 `refining`、`ricnsmart`;参与唯一键 |
|
||||
| entries | type | 软分类,如 `server`、`service`、`key`、`person`(可扩展,不参与唯一键) |
|
||||
| entries | name | 人类可读标识;与 `folder` 一起在用户内唯一 |
|
||||
| entries | notes | 非敏感说明文本 |
|
||||
| entries | metadata | 明文 JSON(ip、url、`key_ref` 等) |
|
||||
| secrets | field_name | 明文字段名,便于 schema 展示 |
|
||||
| secrets | encrypted | AES-GCM 密文(含 nonce) |
|
||||
@@ -137,14 +147,15 @@ flowchart LR
|
||||
|
||||
### PEM 共享(`key_ref`)
|
||||
|
||||
同一 PEM 可被多条 `server` 记录引用:将 PEM 存为 `kind=key` 的 entry,在服务器条目的 `metadata.key_ref` 中写 key 的名称;轮换时只更新 key 对应记录即可。
|
||||
同一 PEM 可被多条 `server` 等记录引用:将 PEM 存为 **`type=key`** 的 entry,在其它条目的 `metadata.key_ref` 中写该 key 条目的 `name`(支持 `folder/name` 格式消歧);轮换时只更新 key 记录即可。
|
||||
|
||||
## 审计日志
|
||||
|
||||
`add`、`update`、`delete` 等写操作写入 **`audit_log`**(操作类型、对象、摘要,不含 secret 明文)。
|
||||
`add`、`update`、`delete` 等写操作写入 **`audit_log`**(操作类型、对象、摘要,不含 secret 明文)。多租户场景下可写 **`user_id`**(可空,兼容遗留行)。
|
||||
业务条目事件使用 **`folder` / `type` / `name`**;登录类事件使用 **`folder='auth'`**,此时 `type`/`name` 表示认证目标(例如 `oauth` / `google`),不表示某条 secrets entry。
|
||||
|
||||
```sql
|
||||
SELECT action, namespace, kind, name, actor, detail, created_at
|
||||
SELECT action, folder, type, name, detail, user_id, created_at
|
||||
FROM audit_log
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 20;
|
||||
@@ -157,15 +168,22 @@ Cargo.toml
|
||||
crates/secrets-core/ # db / crypto / models / audit / service
|
||||
crates/secrets-mcp/ # MCP HTTP、Web、OAuth、API Key
|
||||
scripts/
|
||||
migrate-v0.3.0.sql # 可选:手动 SQL 迁移(namespace/kind → folder/type、唯一键含 folder)
|
||||
deploy/ # systemd、.env 示例
|
||||
```
|
||||
|
||||
## CI/CD(Gitea Actions)
|
||||
|
||||
见 [`.gitea/workflows/secrets.yml`](.gitea/workflows/secrets.yml)。变更 `crates/**`、`deploy/**`、根目录 `Cargo.toml`/`Cargo.lock` 并推送到配置的分支时:fmt / clippy / test → 构建 `x86_64-unknown-linux-musl` → tag `secrets-mcp-<version>` 与 Release 产物 → 可选 SSH 部署。
|
||||
见 [`.gitea/workflows/secrets.yml`](.gitea/workflows/secrets.yml)。
|
||||
|
||||
- **触发**:任意分支 `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
|
||||
./scripts/setup-gitea-actions.sh # 配置 Gitea 变量与 Secrets
|
||||
./scripts/setup-gitea-actions.sh # 通过 Gitea API 写入 RELEASE_TOKEN、WEBHOOK_URL、部署相关变量等
|
||||
```
|
||||
|
||||
详见 [AGENTS.md](AGENTS.md)(发版规则、代码规范)。
|
||||
|
||||
@@ -1,37 +1,88 @@
|
||||
use serde_json::Value;
|
||||
use sqlx::{Postgres, Transaction};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{PgPool, Postgres, Transaction};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Return the current OS user as the audit actor (falls back to empty string).
|
||||
pub fn current_actor() -> String {
|
||||
std::env::var("USER").unwrap_or_default()
|
||||
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,
|
||||
namespace: &str,
|
||||
kind: &str,
|
||||
folder: &str,
|
||||
entry_type: &str,
|
||||
name: &str,
|
||||
detail: Value,
|
||||
) {
|
||||
let actor = current_actor();
|
||||
let result: Result<_, sqlx::Error> = sqlx::query(
|
||||
"INSERT INTO audit_log (action, namespace, kind, name, detail, actor) \
|
||||
"INSERT INTO audit_log (user_id, action, folder, type, name, detail) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(action)
|
||||
.bind(namespace)
|
||||
.bind(kind)
|
||||
.bind(folder)
|
||||
.bind(entry_type)
|
||||
.bind(name)
|
||||
.bind(&detail)
|
||||
.bind(&actor)
|
||||
.execute(&mut **tx)
|
||||
.await;
|
||||
|
||||
if let Err(e) = result {
|
||||
tracing::warn!(error = %e, "failed to write audit log");
|
||||
} else {
|
||||
tracing::debug!(action, namespace, kind, name, actor, "audit logged");
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,35 +55,6 @@ pub fn decrypt_json(master_key: &[u8; 32], data: &[u8]) -> Result<Value> {
|
||||
serde_json::from_slice(&bytes).context("deserialize decrypted JSON")
|
||||
}
|
||||
|
||||
// ─── Per-user key management (DEPRECATED — kept only for migration) ───────────
|
||||
|
||||
/// Generate a new random 32-byte per-user encryption key.
|
||||
#[allow(dead_code)]
|
||||
pub fn generate_user_key() -> [u8; 32] {
|
||||
use aes_gcm::aead::rand_core::RngCore;
|
||||
let mut key = [0u8; 32];
|
||||
OsRng.fill_bytes(&mut key);
|
||||
key
|
||||
}
|
||||
|
||||
/// Wrap a per-user key with the server master key using AES-256-GCM.
|
||||
#[allow(dead_code)]
|
||||
pub fn wrap_user_key(server_master_key: &[u8; 32], user_key: &[u8; 32]) -> Result<Vec<u8>> {
|
||||
encrypt(server_master_key, user_key.as_ref())
|
||||
}
|
||||
|
||||
/// Unwrap a per-user key using the server master key.
|
||||
#[allow(dead_code)]
|
||||
pub fn unwrap_user_key(server_master_key: &[u8; 32], wrapped: &[u8]) -> Result<[u8; 32]> {
|
||||
let bytes = decrypt(server_master_key, wrapped)?;
|
||||
if bytes.len() != 32 {
|
||||
bail!("unwrapped user key has unexpected length {}", bytes.len());
|
||||
}
|
||||
let mut key = [0u8; 32];
|
||||
key.copy_from_slice(&bytes);
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
// ─── Client-supplied key extraction ──────────────────────────────────────────
|
||||
|
||||
/// Parse a 64-char hex string (from X-Encryption-Key header) into a 32-byte key.
|
||||
@@ -100,33 +71,6 @@ pub fn extract_key_from_hex(hex_str: &str) -> Result<[u8; 32]> {
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
// ─── Server master key ────────────────────────────────────────────────────────
|
||||
|
||||
/// Load the server master key from `SERVER_MASTER_KEY` environment variable (64 hex chars).
|
||||
pub fn load_master_key_auto() -> Result<[u8; 32]> {
|
||||
let hex_str = std::env::var("SERVER_MASTER_KEY").map_err(|_| {
|
||||
anyhow::anyhow!(
|
||||
"SERVER_MASTER_KEY is not set. \
|
||||
Generate one with: openssl rand -hex 32"
|
||||
)
|
||||
})?;
|
||||
|
||||
if hex_str.is_empty() {
|
||||
bail!("SERVER_MASTER_KEY is set but empty");
|
||||
}
|
||||
|
||||
let bytes = hex::decode_hex(hex_str.trim())?;
|
||||
if bytes.len() != 32 {
|
||||
bail!(
|
||||
"SERVER_MASTER_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 {
|
||||
@@ -186,22 +130,4 @@ mod tests {
|
||||
let dec = decrypt_json(&key, &enc).unwrap();
|
||||
assert_eq!(dec, value);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_key_wrap_unwrap_roundtrip() {
|
||||
let server_key = [0xABu8; 32];
|
||||
let user_key = [0xCDu8; 32];
|
||||
let wrapped = wrap_user_key(&server_key, &user_key).unwrap();
|
||||
let unwrapped = unwrap_user_key(&server_key, &wrapped).unwrap();
|
||||
assert_eq!(unwrapped, user_key);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_key_wrap_wrong_server_key_fails() {
|
||||
let server_key1 = [0xABu8; 32];
|
||||
let server_key2 = [0xEFu8; 32];
|
||||
let user_key = [0xCDu8; 32];
|
||||
let wrapped = wrap_user_key(&server_key1, &user_key).unwrap();
|
||||
assert!(unwrap_user_key(&server_key2, &wrapped).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,6 @@ use serde_json::Value;
|
||||
use sqlx::PgPool;
|
||||
use sqlx::postgres::PgPoolOptions;
|
||||
|
||||
use crate::audit::current_actor;
|
||||
|
||||
pub async fn create_pool(database_url: &str) -> Result<PgPool> {
|
||||
tracing::debug!("connecting to database");
|
||||
let pool = PgPoolOptions::new()
|
||||
@@ -24,9 +22,10 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
|
||||
CREATE TABLE IF NOT EXISTS entries (
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||
user_id UUID,
|
||||
namespace VARCHAR(64) NOT NULL,
|
||||
kind VARCHAR(64) NOT 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,
|
||||
@@ -36,16 +35,16 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
|
||||
|
||||
-- Legacy unique constraint without user_id (single-user mode)
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_entries_unique_legacy
|
||||
ON entries(namespace, kind, name)
|
||||
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, namespace, kind, name)
|
||||
ON entries(user_id, folder, name)
|
||||
WHERE user_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_entries_namespace ON entries(namespace);
|
||||
CREATE INDEX IF NOT EXISTS idx_entries_kind ON entries(kind);
|
||||
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);
|
||||
@@ -67,42 +66,46 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
|
||||
-- ── 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,
|
||||
namespace VARCHAR(64) NOT NULL,
|
||||
kind VARCHAR(64) NOT NULL,
|
||||
folder VARCHAR(128) NOT NULL DEFAULT '',
|
||||
type VARCHAR(64) NOT NULL DEFAULT '',
|
||||
name VARCHAR(256) NOT NULL,
|
||||
detail JSONB NOT NULL DEFAULT '{}',
|
||||
actor VARCHAR(128) NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_log_created ON audit_log(created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_log_ns_kind ON audit_log(namespace, kind);
|
||||
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,
|
||||
namespace VARCHAR(64) NOT NULL,
|
||||
kind VARCHAR(64) 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 '{}',
|
||||
actor VARCHAR(128) 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_ns_kind_name
|
||||
ON entries_history(namespace, kind, name, 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 (
|
||||
@@ -113,7 +116,6 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
|
||||
field_name VARCHAR(256) NOT NULL,
|
||||
encrypted BYTEA NOT NULL DEFAULT '\x',
|
||||
action VARCHAR(16) NOT NULL,
|
||||
actor VARCHAR(128) NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
@@ -122,6 +124,9 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
|
||||
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(),
|
||||
@@ -152,21 +157,284 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
|
||||
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_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;
|
||||
"#,
|
||||
)
|
||||
.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 namespace: &'a str,
|
||||
pub kind: &'a str,
|
||||
pub folder: &'a str,
|
||||
pub entry_type: &'a str,
|
||||
pub name: &'a str,
|
||||
pub version: i64,
|
||||
pub action: &'a str,
|
||||
@@ -178,21 +446,19 @@ pub async fn snapshot_entry_history(
|
||||
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
p: EntrySnapshotParams<'_>,
|
||||
) -> Result<()> {
|
||||
let actor = current_actor();
|
||||
sqlx::query(
|
||||
"INSERT INTO entries_history \
|
||||
(entry_id, namespace, kind, name, version, action, tags, metadata, actor, user_id) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
|
||||
(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.namespace)
|
||||
.bind(p.kind)
|
||||
.bind(p.folder)
|
||||
.bind(p.entry_type)
|
||||
.bind(p.name)
|
||||
.bind(p.version)
|
||||
.bind(p.action)
|
||||
.bind(p.tags)
|
||||
.bind(p.metadata)
|
||||
.bind(&actor)
|
||||
.bind(p.user_id)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
@@ -214,11 +480,10 @@ pub async fn snapshot_secret_history(
|
||||
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
p: SecretSnapshotParams<'_>,
|
||||
) -> Result<()> {
|
||||
let actor = current_actor();
|
||||
sqlx::query(
|
||||
"INSERT INTO secrets_history \
|
||||
(entry_id, secret_id, entry_version, field_name, encrypted, action, actor) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)",
|
||||
(entry_id, secret_id, entry_version, field_name, encrypted, action) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
)
|
||||
.bind(p.entry_id)
|
||||
.bind(p.secret_id)
|
||||
@@ -226,7 +491,6 @@ pub async fn snapshot_secret_history(
|
||||
.bind(p.field_name)
|
||||
.bind(p.encrypted)
|
||||
.bind(p.action)
|
||||
.bind(&actor)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
|
||||
@@ -4,14 +4,18 @@ use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// A top-level entry (server, service, key, …).
|
||||
/// A top-level entry (server, service, key, person, …).
|
||||
/// Sensitive fields are stored separately in `secrets`.
|
||||
#[derive(Debug, Serialize, Deserialize, sqlx::FromRow)]
|
||||
pub struct Entry {
|
||||
pub id: Uuid,
|
||||
pub namespace: String,
|
||||
pub kind: String,
|
||||
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,
|
||||
@@ -39,8 +43,12 @@ pub struct SecretField {
|
||||
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,
|
||||
}
|
||||
|
||||
/// Minimal secret field row fetched before snapshots or cascade deletes.
|
||||
@@ -127,10 +135,14 @@ pub struct ExportData {
|
||||
/// A single entry with decrypted secrets for export/import.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ExportEntry {
|
||||
pub namespace: String,
|
||||
pub kind: String,
|
||||
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,
|
||||
@@ -174,6 +186,21 @@ pub struct OauthAccount {
|
||||
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.
|
||||
|
||||
@@ -159,18 +159,20 @@ pub fn flatten_json_fields(prefix: &str, value: &Value) -> Vec<(String, Value)>
|
||||
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
pub struct AddResult {
|
||||
pub namespace: String,
|
||||
pub kind: String,
|
||||
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 namespace: &'a str,
|
||||
pub kind: &'a str,
|
||||
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],
|
||||
@@ -186,25 +188,23 @@ pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) ->
|
||||
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
// Fetch existing entry (user-scoped or global depending on user_id)
|
||||
// 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, tags, metadata FROM entries \
|
||||
WHERE user_id = $1 AND namespace = $2 AND kind = $3 AND name = $4",
|
||||
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||
WHERE user_id = $1 AND folder = $2 AND name = $3",
|
||||
)
|
||||
.bind(uid)
|
||||
.bind(params.namespace)
|
||||
.bind(params.kind)
|
||||
.bind(params.folder)
|
||||
.bind(params.name)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_as(
|
||||
"SELECT id, version, tags, metadata FROM entries \
|
||||
WHERE user_id IS NULL AND namespace = $1 AND kind = $2 AND name = $3",
|
||||
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||
WHERE user_id IS NULL AND folder = $1 AND name = $2",
|
||||
)
|
||||
.bind(params.namespace)
|
||||
.bind(params.kind)
|
||||
.bind(params.folder)
|
||||
.bind(params.name)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
@@ -216,8 +216,8 @@ pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) ->
|
||||
db::EntrySnapshotParams {
|
||||
entry_id: ex.id,
|
||||
user_id: params.user_id,
|
||||
namespace: params.namespace,
|
||||
kind: params.kind,
|
||||
folder: params.folder,
|
||||
entry_type: params.entry_type,
|
||||
name: params.name,
|
||||
version: ex.version,
|
||||
action: "add",
|
||||
@@ -232,10 +232,13 @@ pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) ->
|
||||
|
||||
let entry_id: Uuid = if let Some(uid) = params.user_id {
|
||||
sqlx::query_scalar(
|
||||
r#"INSERT INTO entries (user_id, namespace, kind, name, tags, metadata, version, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, 1, NOW())
|
||||
ON CONFLICT (user_id, namespace, kind, name) WHERE user_id IS NOT NULL
|
||||
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,
|
||||
@@ -243,28 +246,33 @@ pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) ->
|
||||
RETURNING id"#,
|
||||
)
|
||||
.bind(uid)
|
||||
.bind(params.namespace)
|
||||
.bind(params.kind)
|
||||
.bind(params.folder)
|
||||
.bind(params.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 (namespace, kind, name, tags, metadata, version, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, 1, NOW())
|
||||
ON CONFLICT (namespace, kind, name) WHERE user_id IS NULL
|
||||
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.namespace)
|
||||
.bind(params.kind)
|
||||
.bind(params.folder)
|
||||
.bind(params.entry_type)
|
||||
.bind(params.name)
|
||||
.bind(params.notes)
|
||||
.bind(params.tags)
|
||||
.bind(&metadata)
|
||||
.fetch_one(&mut *tx)
|
||||
@@ -282,8 +290,8 @@ pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) ->
|
||||
db::EntrySnapshotParams {
|
||||
entry_id,
|
||||
user_id: params.user_id,
|
||||
namespace: params.namespace,
|
||||
kind: params.kind,
|
||||
folder: params.folder,
|
||||
entry_type: params.entry_type,
|
||||
name: params.name,
|
||||
version: new_entry_version,
|
||||
action: "create",
|
||||
@@ -346,9 +354,10 @@ pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) ->
|
||||
|
||||
crate::audit::log_tx(
|
||||
&mut tx,
|
||||
params.user_id,
|
||||
"add",
|
||||
params.namespace,
|
||||
params.kind,
|
||||
params.folder,
|
||||
params.entry_type,
|
||||
params.name,
|
||||
serde_json::json!({
|
||||
"tags": params.tags,
|
||||
@@ -361,9 +370,9 @@ pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) ->
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(AddResult {
|
||||
namespace: params.namespace.to_string(),
|
||||
kind: params.kind.to_string(),
|
||||
name: params.name.to_string(),
|
||||
folder: params.folder.to_string(),
|
||||
entry_type: params.entry_type.to_string(),
|
||||
tags: params.tags.to_vec(),
|
||||
meta_keys,
|
||||
secret_keys,
|
||||
|
||||
23
crates/secrets-core/src/service/audit_log.rs
Normal file
23
crates/secrets-core/src/service/audit_log.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
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) -> Result<Vec<AuditLogEntry>> {
|
||||
let limit = limit.clamp(1, 200);
|
||||
|
||||
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",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(limit)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
|
||||
Ok(rows)
|
||||
}
|
||||
@@ -8,9 +8,10 @@ use crate::models::{EntryRow, SecretFieldRow};
|
||||
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
pub struct DeletedEntry {
|
||||
pub namespace: String,
|
||||
pub kind: String,
|
||||
pub name: String,
|
||||
pub folder: String,
|
||||
#[serde(rename = "type")]
|
||||
pub entry_type: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
@@ -20,34 +21,29 @@ pub struct DeleteResult {
|
||||
}
|
||||
|
||||
pub struct DeleteParams<'a> {
|
||||
pub namespace: &'a str,
|
||||
pub kind: Option<&'a str>,
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
pub async fn run(pool: &PgPool, params: DeleteParams<'_>) -> Result<DeleteResult> {
|
||||
match params.name {
|
||||
Some(name) => {
|
||||
let kind = params
|
||||
.kind
|
||||
.ok_or_else(|| anyhow::anyhow!("--kind is required when --name is specified"))?;
|
||||
delete_one(
|
||||
pool,
|
||||
params.namespace,
|
||||
kind,
|
||||
name,
|
||||
params.dry_run,
|
||||
params.user_id,
|
||||
)
|
||||
.await
|
||||
}
|
||||
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.namespace,
|
||||
params.kind,
|
||||
params.folder,
|
||||
params.entry_type,
|
||||
params.dry_run,
|
||||
params.user_id,
|
||||
)
|
||||
@@ -58,93 +54,169 @@ pub async fn run(pool: &PgPool, params: DeleteParams<'_>) -> Result<DeleteResult
|
||||
|
||||
async fn delete_one(
|
||||
pool: &PgPool,
|
||||
namespace: &str,
|
||||
kind: &str,
|
||||
name: &str,
|
||||
folder: Option<&str>,
|
||||
dry_run: bool,
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<DeleteResult> {
|
||||
if dry_run {
|
||||
let exists: bool = if let Some(uid) = user_id {
|
||||
sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM entries \
|
||||
WHERE user_id = $1 AND namespace = $2 AND kind = $3 AND name = $4)",
|
||||
// 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 rows: Vec<DryRunRow> = if let Some(uid) = user_id {
|
||||
if let Some(f) = folder {
|
||||
sqlx::query_as(
|
||||
"SELECT folder, type FROM entries WHERE user_id = $1 AND folder = $2 AND name = $3",
|
||||
)
|
||||
.bind(uid)
|
||||
.bind(namespace)
|
||||
.bind(kind)
|
||||
.bind(f)
|
||||
.bind(name)
|
||||
.fetch_one(pool)
|
||||
.fetch_all(pool)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM entries \
|
||||
WHERE user_id IS NULL AND namespace = $1 AND kind = $2 AND name = $3)",
|
||||
)
|
||||
.bind(namespace)
|
||||
.bind(kind)
|
||||
sqlx::query_as("SELECT folder, type FROM entries WHERE user_id = $1 AND name = $2")
|
||||
.bind(uid)
|
||||
.bind(name)
|
||||
.fetch_one(pool)
|
||||
.fetch_all(pool)
|
||||
.await?
|
||||
}
|
||||
} else if let Some(f) = folder {
|
||||
sqlx::query_as(
|
||||
"SELECT folder, type FROM entries WHERE user_id IS NULL AND folder = $1 AND name = $2",
|
||||
)
|
||||
.bind(f)
|
||||
.bind(name)
|
||||
.fetch_all(pool)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_as("SELECT folder, type FROM entries WHERE user_id IS NULL AND name = $1")
|
||||
.bind(name)
|
||||
.fetch_all(pool)
|
||||
.await?
|
||||
};
|
||||
|
||||
let deleted = if exists {
|
||||
vec![DeletedEntry {
|
||||
namespace: namespace.to_string(),
|
||||
kind: kind.to_string(),
|
||||
name: name.to_string(),
|
||||
}]
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
return Ok(DeleteResult {
|
||||
deleted,
|
||||
return match rows.len() {
|
||||
0 => Ok(DeleteResult {
|
||||
deleted: vec![],
|
||||
dry_run: true,
|
||||
});
|
||||
}),
|
||||
1 => {
|
||||
let row = rows.into_iter().next().unwrap();
|
||||
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?;
|
||||
|
||||
let row: Option<EntryRow> = if let Some(uid) = user_id {
|
||||
// Fetch matching rows with FOR UPDATE; use folder when provided to resolve ambiguity.
|
||||
let rows: Vec<EntryRow> = if let Some(uid) = user_id {
|
||||
if let Some(f) = folder {
|
||||
sqlx::query_as(
|
||||
"SELECT id, version, tags, metadata FROM entries \
|
||||
WHERE user_id = $1 AND namespace = $2 AND kind = $3 AND name = $4 FOR UPDATE",
|
||||
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||
WHERE user_id = $1 AND folder = $2 AND name = $3 FOR UPDATE",
|
||||
)
|
||||
.bind(uid)
|
||||
.bind(namespace)
|
||||
.bind(kind)
|
||||
.bind(f)
|
||||
.bind(name)
|
||||
.fetch_optional(&mut *tx)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_as(
|
||||
"SELECT id, version, tags, metadata FROM entries \
|
||||
WHERE user_id IS NULL AND namespace = $1 AND kind = $2 AND name = $3 FOR UPDATE",
|
||||
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||
WHERE user_id = $1 AND name = $2 FOR UPDATE",
|
||||
)
|
||||
.bind(namespace)
|
||||
.bind(kind)
|
||||
.bind(uid)
|
||||
.bind(name)
|
||||
.fetch_optional(&mut *tx)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?
|
||||
}
|
||||
} else if let Some(f) = folder {
|
||||
sqlx::query_as(
|
||||
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||
WHERE user_id IS NULL AND folder = $1 AND name = $2 FOR UPDATE",
|
||||
)
|
||||
.bind(f)
|
||||
.bind(name)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_as(
|
||||
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||
WHERE user_id IS NULL AND name = $1 FOR UPDATE",
|
||||
)
|
||||
.bind(name)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?
|
||||
};
|
||||
|
||||
let Some(row) = row else {
|
||||
let row = match rows.len() {
|
||||
0 => {
|
||||
tx.rollback().await?;
|
||||
return Ok(DeleteResult {
|
||||
deleted: vec![],
|
||||
dry_run: false,
|
||||
});
|
||||
}
|
||||
1 => rows.into_iter().next().unwrap(),
|
||||
_ => {
|
||||
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(", ")
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
snapshot_and_delete(&mut tx, namespace, kind, name, &row, user_id).await?;
|
||||
crate::audit::log_tx(&mut tx, "delete", namespace, kind, name, json!({})).await;
|
||||
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 {
|
||||
namespace: namespace.to_string(),
|
||||
kind: kind.to_string(),
|
||||
name: name.to_string(),
|
||||
folder,
|
||||
entry_type,
|
||||
}],
|
||||
dry_run: false,
|
||||
})
|
||||
@@ -152,8 +224,8 @@ async fn delete_one(
|
||||
|
||||
async fn delete_bulk(
|
||||
pool: &PgPool,
|
||||
namespace: &str,
|
||||
kind: Option<&str>,
|
||||
folder: Option<&str>,
|
||||
entry_type: Option<&str>,
|
||||
dry_run: bool,
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<DeleteResult> {
|
||||
@@ -161,62 +233,57 @@ async fn delete_bulk(
|
||||
struct FullEntryRow {
|
||||
id: Uuid,
|
||||
version: i64,
|
||||
kind: String,
|
||||
folder: String,
|
||||
#[sqlx(rename = "type")]
|
||||
entry_type: String,
|
||||
name: String,
|
||||
metadata: serde_json::Value,
|
||||
tags: Vec<String>,
|
||||
notes: String,
|
||||
}
|
||||
|
||||
let rows: Vec<FullEntryRow> = match (user_id, kind) {
|
||||
(Some(uid), Some(k)) => {
|
||||
sqlx::query_as(
|
||||
"SELECT id, version, kind, name, metadata, tags FROM entries \
|
||||
WHERE user_id = $1 AND namespace = $2 AND kind = $3 ORDER BY name",
|
||||
)
|
||||
.bind(uid)
|
||||
.bind(namespace)
|
||||
.bind(k)
|
||||
.fetch_all(pool)
|
||||
.await?
|
||||
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());
|
||||
}
|
||||
(Some(uid), None) => {
|
||||
sqlx::query_as(
|
||||
"SELECT id, version, kind, name, metadata, tags FROM entries \
|
||||
WHERE user_id = $1 AND namespace = $2 ORDER BY kind, name",
|
||||
)
|
||||
.bind(uid)
|
||||
.bind(namespace)
|
||||
.fetch_all(pool)
|
||||
.await?
|
||||
if folder.is_some() {
|
||||
conditions.push(format!("folder = ${}", idx));
|
||||
idx += 1;
|
||||
}
|
||||
(None, Some(k)) => {
|
||||
sqlx::query_as(
|
||||
"SELECT id, version, kind, name, metadata, tags FROM entries \
|
||||
WHERE user_id IS NULL AND namespace = $1 AND kind = $2 ORDER BY name",
|
||||
)
|
||||
.bind(namespace)
|
||||
.bind(k)
|
||||
.fetch_all(pool)
|
||||
.await?
|
||||
if entry_type.is_some() {
|
||||
conditions.push(format!("type = ${}", idx));
|
||||
}
|
||||
(None, None) => {
|
||||
sqlx::query_as(
|
||||
"SELECT id, version, kind, name, metadata, tags FROM entries \
|
||||
WHERE user_id IS NULL AND namespace = $1 ORDER BY kind, name",
|
||||
)
|
||||
.bind(namespace)
|
||||
.fetch_all(pool)
|
||||
.await?
|
||||
|
||||
let where_clause = format!("WHERE {}", conditions.join(" AND "));
|
||||
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?;
|
||||
|
||||
if dry_run {
|
||||
let deleted = rows
|
||||
.iter()
|
||||
.map(|r| DeletedEntry {
|
||||
namespace: namespace.to_string(),
|
||||
kind: r.kind.clone(),
|
||||
name: r.name.clone(),
|
||||
folder: r.folder.clone(),
|
||||
entry_type: r.entry_type.clone(),
|
||||
})
|
||||
.collect();
|
||||
return Ok(DeleteResult {
|
||||
@@ -230,28 +297,37 @@ async fn delete_bulk(
|
||||
let entry_row = 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(),
|
||||
};
|
||||
let mut tx = pool.begin().await?;
|
||||
snapshot_and_delete(
|
||||
&mut tx, namespace, &row.kind, &row.name, &entry_row, user_id,
|
||||
&mut tx,
|
||||
&row.folder,
|
||||
&row.entry_type,
|
||||
&row.name,
|
||||
&entry_row,
|
||||
user_id,
|
||||
)
|
||||
.await?;
|
||||
crate::audit::log_tx(
|
||||
&mut tx,
|
||||
user_id,
|
||||
"delete",
|
||||
namespace,
|
||||
&row.kind,
|
||||
&row.folder,
|
||||
&row.entry_type,
|
||||
&row.name,
|
||||
json!({"bulk": true}),
|
||||
)
|
||||
.await;
|
||||
tx.commit().await?;
|
||||
deleted.push(DeletedEntry {
|
||||
namespace: namespace.to_string(),
|
||||
kind: row.kind.clone(),
|
||||
name: row.name.clone(),
|
||||
folder: row.folder.clone(),
|
||||
entry_type: row.entry_type.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -263,8 +339,8 @@ async fn delete_bulk(
|
||||
|
||||
async fn snapshot_and_delete(
|
||||
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
namespace: &str,
|
||||
kind: &str,
|
||||
folder: &str,
|
||||
entry_type: &str,
|
||||
name: &str,
|
||||
row: &EntryRow,
|
||||
user_id: Option<Uuid>,
|
||||
@@ -274,8 +350,8 @@ async fn snapshot_and_delete(
|
||||
db::EntrySnapshotParams {
|
||||
entry_id: row.id,
|
||||
user_id,
|
||||
namespace,
|
||||
kind,
|
||||
folder,
|
||||
entry_type,
|
||||
name,
|
||||
version: row.version,
|
||||
action: "delete",
|
||||
|
||||
@@ -12,8 +12,8 @@ use crate::service::search::{fetch_entries, fetch_secrets_for_entries};
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn build_env_map(
|
||||
pool: &PgPool,
|
||||
namespace: Option<&str>,
|
||||
kind: Option<&str>,
|
||||
folder: Option<&str>,
|
||||
entry_type: Option<&str>,
|
||||
name: Option<&str>,
|
||||
tags: &[String],
|
||||
only_fields: &[String],
|
||||
@@ -21,12 +21,13 @@ pub async fn build_env_map(
|
||||
master_key: &[u8; 32],
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<HashMap<String, String>> {
|
||||
let entries = fetch_entries(pool, namespace, kind, name, tags, None, user_id).await?;
|
||||
let entries = fetch_entries(pool, folder, entry_type, name, tags, None, user_id).await?;
|
||||
|
||||
let mut combined: HashMap<String, String> = HashMap::new();
|
||||
|
||||
for entry in &entries {
|
||||
let entry_map = build_entry_env_map(pool, entry, only_fields, prefix, master_key).await?;
|
||||
let entry_map =
|
||||
build_entry_env_map(pool, entry, only_fields, prefix, master_key, user_id).await?;
|
||||
combined.extend(entry_map);
|
||||
}
|
||||
|
||||
@@ -39,6 +40,7 @@ async fn build_entry_env_map(
|
||||
only_fields: &[String],
|
||||
prefix: &str,
|
||||
master_key: &[u8; 32],
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<HashMap<String, String>> {
|
||||
let entry_ids = vec![entry.id];
|
||||
let secrets_map = fetch_secrets_for_entries(pool, &entry_ids).await?;
|
||||
@@ -66,19 +68,32 @@ async fn build_entry_env_map(
|
||||
map.insert(key, json_to_env_string(&decrypted));
|
||||
}
|
||||
|
||||
// Resolve key_ref
|
||||
// Resolve key_ref. Supported formats: "name" or "folder/name".
|
||||
if let Some(key_ref) = entry.metadata.get("key_ref").and_then(|v| v.as_str()) {
|
||||
let (ref_folder, ref_name) = if let Some((f, n)) = key_ref.split_once('/') {
|
||||
(Some(f), n)
|
||||
} else {
|
||||
(None, key_ref)
|
||||
};
|
||||
let key_entries = fetch_entries(
|
||||
pool,
|
||||
Some(&entry.namespace),
|
||||
ref_folder,
|
||||
Some("key"),
|
||||
Some(key_ref),
|
||||
Some(ref_name),
|
||||
&[],
|
||||
None,
|
||||
None,
|
||||
user_id,
|
||||
)
|
||||
.await?;
|
||||
|
||||
if key_entries.len() > 1 {
|
||||
anyhow::bail!(
|
||||
"key_ref '{}' matched {} entries; qualify with folder/name to resolve the ambiguity",
|
||||
key_ref,
|
||||
key_entries.len()
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(key_entry) = key_entries.first() {
|
||||
let key_ids = vec![key_entry.id];
|
||||
let key_fields_map = fetch_secrets_for_entries(pool, &key_ids).await?;
|
||||
@@ -95,7 +110,7 @@ async fn build_entry_env_map(
|
||||
map.insert(key_var, json_to_env_string(&decrypted));
|
||||
}
|
||||
} else {
|
||||
tracing::warn!(key_ref, "key_ref target not found");
|
||||
tracing::warn!(key_ref, ?user_id, "key_ref target not found");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@ use crate::models::{ExportData, ExportEntry, ExportFormat};
|
||||
use crate::service::search::{fetch_entries, fetch_secrets_for_entries};
|
||||
|
||||
pub struct ExportParams<'a> {
|
||||
pub namespace: Option<&'a str>,
|
||||
pub kind: Option<&'a str>,
|
||||
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>,
|
||||
@@ -25,8 +25,8 @@ pub async fn export(
|
||||
) -> Result<ExportData> {
|
||||
let entries = fetch_entries(
|
||||
pool,
|
||||
params.namespace,
|
||||
params.kind,
|
||||
params.folder,
|
||||
params.entry_type,
|
||||
params.name,
|
||||
params.tags,
|
||||
params.query,
|
||||
@@ -62,9 +62,10 @@ pub async fn export(
|
||||
};
|
||||
|
||||
export_entries.push(ExportEntry {
|
||||
namespace: entry.namespace.clone(),
|
||||
kind: entry.kind.clone(),
|
||||
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,
|
||||
|
||||
@@ -5,31 +5,19 @@ use std::collections::HashMap;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::crypto;
|
||||
use crate::service::search::{fetch_entries, fetch_secrets_for_entries};
|
||||
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,
|
||||
namespace: &str,
|
||||
kind: &str,
|
||||
name: &str,
|
||||
folder: Option<&str>,
|
||||
field_name: &str,
|
||||
master_key: &[u8; 32],
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<Value> {
|
||||
let entries = fetch_entries(
|
||||
pool,
|
||||
Some(namespace),
|
||||
Some(kind),
|
||||
Some(name),
|
||||
&[],
|
||||
None,
|
||||
user_id,
|
||||
)
|
||||
.await?;
|
||||
let entry = entries
|
||||
.first()
|
||||
.ok_or_else(|| anyhow::anyhow!("Not found: [{}/{}] {}", namespace, kind, name))?;
|
||||
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?;
|
||||
@@ -44,27 +32,15 @@ pub async fn get_secret_field(
|
||||
}
|
||||
|
||||
/// 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,
|
||||
namespace: &str,
|
||||
kind: &str,
|
||||
name: &str,
|
||||
folder: Option<&str>,
|
||||
master_key: &[u8; 32],
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<HashMap<String, Value>> {
|
||||
let entries = fetch_entries(
|
||||
pool,
|
||||
Some(namespace),
|
||||
Some(kind),
|
||||
Some(name),
|
||||
&[],
|
||||
None,
|
||||
user_id,
|
||||
)
|
||||
.await?;
|
||||
let entry = entries
|
||||
.first()
|
||||
.ok_or_else(|| anyhow::anyhow!("Not found: [{}/{}] {}", namespace, kind, name))?;
|
||||
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?;
|
||||
@@ -77,3 +53,52 @@ pub async fn get_all_secrets(
|
||||
}
|
||||
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::anyhow!("Entry with id '{}' not found", entry_id))?;
|
||||
|
||||
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.field_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::anyhow!("Entry with id '{}' not found", entry_id))?;
|
||||
|
||||
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.field_name.clone(), decrypted);
|
||||
}
|
||||
Ok(map)
|
||||
}
|
||||
|
||||
@@ -3,19 +3,21 @@ 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 actor: 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,
|
||||
namespace: &str,
|
||||
kind: &str,
|
||||
name: &str,
|
||||
folder: Option<&str>,
|
||||
limit: u32,
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<Vec<HistoryEntry>> {
|
||||
@@ -23,43 +25,25 @@ pub async fn run(
|
||||
struct Row {
|
||||
version: i64,
|
||||
action: String,
|
||||
actor: String,
|
||||
created_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
let rows: Vec<Row> = if let Some(uid) = user_id {
|
||||
sqlx::query_as(
|
||||
"SELECT version, action, actor, created_at FROM entries_history \
|
||||
WHERE namespace = $1 AND kind = $2 AND name = $3 AND user_id = $4 \
|
||||
ORDER BY id DESC LIMIT $5",
|
||||
let entry = resolve_entry(pool, name, folder, user_id).await?;
|
||||
|
||||
let rows: Vec<Row> = sqlx::query_as(
|
||||
"SELECT version, action, created_at FROM entries_history \
|
||||
WHERE entry_id = $1 ORDER BY id DESC LIMIT $2",
|
||||
)
|
||||
.bind(namespace)
|
||||
.bind(kind)
|
||||
.bind(name)
|
||||
.bind(uid)
|
||||
.bind(entry.id)
|
||||
.bind(limit as i64)
|
||||
.fetch_all(pool)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_as(
|
||||
"SELECT version, action, actor, created_at FROM entries_history \
|
||||
WHERE namespace = $1 AND kind = $2 AND name = $3 AND user_id IS NULL \
|
||||
ORDER BY id DESC LIMIT $4",
|
||||
)
|
||||
.bind(namespace)
|
||||
.bind(kind)
|
||||
.bind(name)
|
||||
.bind(limit as i64)
|
||||
.fetch_all(pool)
|
||||
.await?
|
||||
};
|
||||
.await?;
|
||||
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|r| HistoryEntry {
|
||||
version: r.version,
|
||||
action: r.action,
|
||||
actor: r.actor,
|
||||
created_at: r.created_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
|
||||
})
|
||||
.collect())
|
||||
@@ -67,12 +51,11 @@ pub async fn run(
|
||||
|
||||
pub async fn run_json(
|
||||
pool: &PgPool,
|
||||
namespace: &str,
|
||||
kind: &str,
|
||||
name: &str,
|
||||
folder: Option<&str>,
|
||||
limit: u32,
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<Value> {
|
||||
let entries = run(pool, namespace, kind, name, limit, user_id).await?;
|
||||
let entries = run(pool, name, folder, limit, user_id).await?;
|
||||
Ok(serde_json::to_value(entries)?)
|
||||
}
|
||||
|
||||
@@ -47,10 +47,9 @@ pub async fn run(
|
||||
for entry in &data.entries {
|
||||
let exists: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM entries \
|
||||
WHERE namespace = $1 AND kind = $2 AND name = $3 AND user_id IS NOT DISTINCT FROM $4)",
|
||||
WHERE folder = $1 AND name = $2 AND user_id IS NOT DISTINCT FROM $3)",
|
||||
)
|
||||
.bind(&entry.namespace)
|
||||
.bind(&entry.kind)
|
||||
.bind(&entry.folder)
|
||||
.bind(&entry.name)
|
||||
.bind(params.user_id)
|
||||
.fetch_one(pool)
|
||||
@@ -59,9 +58,7 @@ pub async fn run(
|
||||
|
||||
if exists && !params.force {
|
||||
return Err(anyhow::anyhow!(
|
||||
"Import aborted: conflict on [{}/{}/{}]",
|
||||
entry.namespace,
|
||||
entry.kind,
|
||||
"Import aborted: conflict on '{}'",
|
||||
entry.name
|
||||
));
|
||||
}
|
||||
@@ -81,9 +78,10 @@ pub async fn run(
|
||||
match add_run(
|
||||
pool,
|
||||
AddParams {
|
||||
namespace: &entry.namespace,
|
||||
kind: &entry.kind,
|
||||
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,
|
||||
@@ -98,8 +96,6 @@ pub async fn run(
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
namespace = entry.namespace,
|
||||
kind = entry.kind,
|
||||
name = entry.name,
|
||||
error = %e,
|
||||
"failed to import entry"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
pub mod add;
|
||||
pub mod api_key;
|
||||
pub mod audit_log;
|
||||
pub mod delete;
|
||||
pub mod env_map;
|
||||
pub mod export;
|
||||
|
||||
@@ -8,17 +8,19 @@ use crate::db;
|
||||
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
pub struct RollbackResult {
|
||||
pub namespace: String,
|
||||
pub kind: String,
|
||||
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,
|
||||
namespace: &str,
|
||||
kind: &str,
|
||||
name: &str,
|
||||
folder: Option<&str>,
|
||||
to_version: Option<i64>,
|
||||
master_key: &[u8; 32],
|
||||
user_id: Option<Uuid>,
|
||||
@@ -26,69 +28,122 @@ pub async fn run(
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct EntryHistoryRow {
|
||||
entry_id: Uuid,
|
||||
folder: String,
|
||||
#[sqlx(rename = "type")]
|
||||
entry_type: String,
|
||||
version: i64,
|
||||
action: String,
|
||||
tags: Vec<String>,
|
||||
metadata: Value,
|
||||
}
|
||||
|
||||
let snap: Option<EntryHistoryRow> = if let Some(ver) = to_version {
|
||||
if let Some(uid) = user_id {
|
||||
sqlx::query_as(
|
||||
"SELECT entry_id, version, action, tags, metadata FROM entries_history \
|
||||
WHERE namespace = $1 AND kind = $2 AND name = $3 AND version = $4 \
|
||||
AND user_id = $5 ORDER BY id DESC LIMIT 1",
|
||||
// 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(namespace)
|
||||
.bind(kind)
|
||||
.bind(name)
|
||||
.bind(ver)
|
||||
.bind(f)
|
||||
.bind(uid)
|
||||
.fetch_optional(pool)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_as(
|
||||
"SELECT entry_id, version, action, tags, metadata FROM entries_history \
|
||||
WHERE namespace = $1 AND kind = $2 AND name = $3 AND version = $4 \
|
||||
AND user_id IS NULL ORDER BY id DESC LIMIT 1",
|
||||
let ids: Vec<Uuid> = sqlx::query_scalar(
|
||||
"SELECT DISTINCT entry_id FROM entries_history \
|
||||
WHERE name = $1 AND user_id = $2",
|
||||
)
|
||||
.bind(namespace)
|
||||
.bind(kind)
|
||||
.bind(name)
|
||||
.bind(ver)
|
||||
.fetch_optional(pool)
|
||||
.await?
|
||||
.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(uid) = user_id {
|
||||
sqlx::query_as(
|
||||
"SELECT entry_id, version, action, tags, metadata FROM entries_history \
|
||||
WHERE namespace = $1 AND kind = $2 AND name = $3 \
|
||||
AND user_id = $4 ORDER BY id DESC LIMIT 1",
|
||||
}
|
||||
}
|
||||
} 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(namespace)
|
||||
.bind(kind)
|
||||
.bind(name)
|
||||
.bind(uid)
|
||||
.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 entry_id, folder, type, version, action, tags, metadata \
|
||||
FROM entries_history \
|
||||
WHERE entry_id = $1 AND version = $2 ORDER BY id DESC LIMIT 1",
|
||||
)
|
||||
.bind(entry_id)
|
||||
.bind(ver)
|
||||
.fetch_optional(pool)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_as(
|
||||
"SELECT entry_id, version, action, tags, metadata FROM entries_history \
|
||||
WHERE namespace = $1 AND kind = $2 AND name = $3 \
|
||||
AND user_id IS NULL ORDER BY id DESC LIMIT 1",
|
||||
"SELECT entry_id, folder, type, version, action, tags, metadata \
|
||||
FROM entries_history \
|
||||
WHERE entry_id = $1 ORDER BY id DESC LIMIT 1",
|
||||
)
|
||||
.bind(namespace)
|
||||
.bind(kind)
|
||||
.bind(name)
|
||||
.bind(entry_id)
|
||||
.fetch_optional(pool)
|
||||
.await?
|
||||
};
|
||||
|
||||
let snap = snap.ok_or_else(|| {
|
||||
anyhow::anyhow!(
|
||||
"No history found for [{}/{}] {}{}.",
|
||||
namespace,
|
||||
kind,
|
||||
"No history found for '{}'{}.",
|
||||
name,
|
||||
to_version
|
||||
.map(|v| format!(" at version {}", v))
|
||||
@@ -130,43 +185,32 @@ pub async fn run(
|
||||
struct LiveEntry {
|
||||
id: Uuid,
|
||||
version: i64,
|
||||
folder: String,
|
||||
#[sqlx(rename = "type")]
|
||||
entry_type: String,
|
||||
tags: Vec<String>,
|
||||
metadata: Value,
|
||||
#[allow(dead_code)]
|
||||
notes: String,
|
||||
}
|
||||
|
||||
// Query live entry with correct user_id scoping to avoid PK conflicts
|
||||
let live: Option<LiveEntry> = if let Some(uid) = user_id {
|
||||
sqlx::query_as(
|
||||
"SELECT id, version, tags, metadata FROM entries \
|
||||
WHERE user_id = $1 AND namespace = $2 AND kind = $3 AND name = $4 FOR UPDATE",
|
||||
// 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, notes FROM entries \
|
||||
WHERE id = $1 FOR UPDATE",
|
||||
)
|
||||
.bind(uid)
|
||||
.bind(namespace)
|
||||
.bind(kind)
|
||||
.bind(name)
|
||||
.bind(entry_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_as(
|
||||
"SELECT id, version, tags, metadata FROM entries \
|
||||
WHERE user_id IS NULL AND namespace = $1 AND kind = $2 AND name = $3 FOR UPDATE",
|
||||
)
|
||||
.bind(namespace)
|
||||
.bind(kind)
|
||||
.bind(name)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
};
|
||||
.await?;
|
||||
|
||||
let entry_id = if let Some(ref lr) = live {
|
||||
// Snapshot current state before overwriting
|
||||
let live_entry_id = if let Some(ref lr) = live {
|
||||
if let Err(e) = db::snapshot_entry_history(
|
||||
&mut tx,
|
||||
db::EntrySnapshotParams {
|
||||
entry_id: lr.id,
|
||||
user_id,
|
||||
namespace,
|
||||
kind,
|
||||
folder: &lr.folder,
|
||||
entry_type: &lr.entry_type,
|
||||
name,
|
||||
version: lr.version,
|
||||
action: "rollback",
|
||||
@@ -209,7 +253,6 @@ pub async fn run(
|
||||
}
|
||||
}
|
||||
|
||||
// Update the existing row in-place to preserve its primary key and user_id
|
||||
sqlx::query(
|
||||
"UPDATE entries SET tags = $1, metadata = $2, version = version + 1, \
|
||||
updated_at = NOW() WHERE id = $3",
|
||||
@@ -222,16 +265,15 @@ pub async fn run(
|
||||
|
||||
lr.id
|
||||
} else {
|
||||
// No live entry — insert a fresh one with a new UUID
|
||||
if let Some(uid) = user_id {
|
||||
sqlx::query_scalar(
|
||||
"INSERT INTO entries \
|
||||
(user_id, namespace, kind, name, tags, metadata, version, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, NOW()) RETURNING id",
|
||||
(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(namespace)
|
||||
.bind(kind)
|
||||
.bind(&snap.folder)
|
||||
.bind(&snap.entry_type)
|
||||
.bind(name)
|
||||
.bind(&snap.tags)
|
||||
.bind(&snap.metadata)
|
||||
@@ -241,11 +283,11 @@ pub async fn run(
|
||||
} else {
|
||||
sqlx::query_scalar(
|
||||
"INSERT INTO entries \
|
||||
(namespace, kind, name, tags, metadata, version, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, NOW()) RETURNING id",
|
||||
(folder, type, name, notes, tags, metadata, version, updated_at) \
|
||||
VALUES ($1, $2, $3, '', $4, $5, $6, NOW()) RETURNING id",
|
||||
)
|
||||
.bind(namespace)
|
||||
.bind(kind)
|
||||
.bind(&snap.folder)
|
||||
.bind(&snap.entry_type)
|
||||
.bind(name)
|
||||
.bind(&snap.tags)
|
||||
.bind(&snap.metadata)
|
||||
@@ -256,7 +298,7 @@ pub async fn run(
|
||||
};
|
||||
|
||||
sqlx::query("DELETE FROM secrets WHERE entry_id = $1")
|
||||
.bind(entry_id)
|
||||
.bind(live_entry_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
@@ -265,7 +307,7 @@ pub async fn run(
|
||||
continue;
|
||||
}
|
||||
sqlx::query("INSERT INTO secrets (entry_id, field_name, encrypted) VALUES ($1, $2, $3)")
|
||||
.bind(entry_id)
|
||||
.bind(live_entry_id)
|
||||
.bind(&f.field_name)
|
||||
.bind(&f.encrypted)
|
||||
.execute(&mut *tx)
|
||||
@@ -274,9 +316,10 @@ pub async fn run(
|
||||
|
||||
crate::audit::log_tx(
|
||||
&mut tx,
|
||||
user_id,
|
||||
"rollback",
|
||||
namespace,
|
||||
kind,
|
||||
&snap.folder,
|
||||
&snap.entry_type,
|
||||
name,
|
||||
serde_json::json!({
|
||||
"restored_version": snap.version,
|
||||
@@ -288,9 +331,9 @@ pub async fn run(
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(RollbackResult {
|
||||
namespace: namespace.to_string(),
|
||||
kind: kind.to_string(),
|
||||
name: name.to_string(),
|
||||
folder: snap.folder,
|
||||
entry_type: snap.entry_type,
|
||||
restored_version: snap.version,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -9,8 +9,8 @@ use crate::models::{Entry, SecretField};
|
||||
pub const FETCH_ALL_LIMIT: u32 = 100_000;
|
||||
|
||||
pub struct SearchParams<'a> {
|
||||
pub namespace: Option<&'a str>,
|
||||
pub kind: Option<&'a str>,
|
||||
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>,
|
||||
@@ -44,16 +44,16 @@ pub async fn run(pool: &PgPool, params: SearchParams<'_>) -> Result<SearchResult
|
||||
/// Fetch entries matching the given filters — returns all matching entries up to FETCH_ALL_LIMIT.
|
||||
pub async fn fetch_entries(
|
||||
pool: &PgPool,
|
||||
namespace: Option<&str>,
|
||||
kind: Option<&str>,
|
||||
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 {
|
||||
namespace,
|
||||
kind,
|
||||
folder,
|
||||
entry_type,
|
||||
name,
|
||||
tags,
|
||||
query,
|
||||
@@ -77,12 +77,12 @@ async fn fetch_entries_paged(pool: &PgPool, a: &SearchParams<'_>) -> Result<Vec<
|
||||
conditions.push("user_id IS NULL".to_string());
|
||||
}
|
||||
|
||||
if a.namespace.is_some() {
|
||||
conditions.push(format!("namespace = ${}", idx));
|
||||
if a.folder.is_some() {
|
||||
conditions.push(format!("folder = ${}", idx));
|
||||
idx += 1;
|
||||
}
|
||||
if a.kind.is_some() {
|
||||
conditions.push(format!("kind = ${}", idx));
|
||||
if a.entry_type.is_some() {
|
||||
conditions.push(format!("type = ${}", idx));
|
||||
idx += 1;
|
||||
}
|
||||
if a.name.is_some() {
|
||||
@@ -106,8 +106,9 @@ async fn fetch_entries_paged(pool: &PgPool, a: &SearchParams<'_>) -> Result<Vec<
|
||||
}
|
||||
if a.query.is_some() {
|
||||
conditions.push(format!(
|
||||
"(name ILIKE ${i} ESCAPE '\\' OR namespace ILIKE ${i} ESCAPE '\\' \
|
||||
OR kind ILIKE ${i} ESCAPE '\\' OR metadata::text ILIKE ${i} ESCAPE '\\' \
|
||||
"(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
|
||||
));
|
||||
@@ -131,8 +132,8 @@ async fn fetch_entries_paged(pool: &PgPool, a: &SearchParams<'_>) -> Result<Vec<
|
||||
};
|
||||
|
||||
let sql = format!(
|
||||
"SELECT id, COALESCE(user_id, '00000000-0000-0000-0000-000000000000'::uuid) AS user_id, \
|
||||
namespace, kind, name, tags, metadata, version, created_at, updated_at \
|
||||
"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}"
|
||||
);
|
||||
|
||||
@@ -141,10 +142,10 @@ async fn fetch_entries_paged(pool: &PgPool, a: &SearchParams<'_>) -> Result<Vec<
|
||||
if let Some(uid) = a.user_id {
|
||||
q = q.bind(uid);
|
||||
}
|
||||
if let Some(v) = a.namespace {
|
||||
if let Some(v) = a.folder {
|
||||
q = q.bind(v);
|
||||
}
|
||||
if let Some(v) = a.kind {
|
||||
if let Some(v) = a.entry_type {
|
||||
q = q.bind(v);
|
||||
}
|
||||
if let Some(v) = a.name {
|
||||
@@ -207,16 +208,81 @@ pub async fn fetch_secrets_for_entries(
|
||||
Ok(map)
|
||||
}
|
||||
|
||||
// ── Internal raw row (because user_id is nullable in DB) ─────────────────────
|
||||
/// 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 => Ok(entries.into_iter().next().unwrap()),
|
||||
_ => {
|
||||
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,
|
||||
#[allow(dead_code)] // Selected for row shape; Entry model has no user_id field
|
||||
user_id: Uuid,
|
||||
namespace: String,
|
||||
kind: String,
|
||||
user_id: Option<Uuid>,
|
||||
folder: String,
|
||||
#[sqlx(rename = "type")]
|
||||
entry_type: String,
|
||||
name: String,
|
||||
notes: String,
|
||||
tags: Vec<String>,
|
||||
metadata: Value,
|
||||
version: i64,
|
||||
@@ -228,9 +294,11 @@ impl From<EntryRaw> for Entry {
|
||||
fn from(r: EntryRaw) -> Self {
|
||||
Entry {
|
||||
id: r.id,
|
||||
namespace: r.namespace,
|
||||
kind: r.kind,
|
||||
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,
|
||||
|
||||
@@ -13,9 +13,10 @@ use crate::service::add::{
|
||||
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
pub struct UpdateResult {
|
||||
pub namespace: String,
|
||||
pub kind: String,
|
||||
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>,
|
||||
@@ -25,9 +26,10 @@ pub struct UpdateResult {
|
||||
}
|
||||
|
||||
pub struct UpdateParams<'a> {
|
||||
pub namespace: &'a str,
|
||||
pub kind: &'a str,
|
||||
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],
|
||||
@@ -44,45 +46,76 @@ pub async fn run(
|
||||
) -> Result<UpdateResult> {
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
let row: Option<EntryRow> = if let Some(uid) = params.user_id {
|
||||
// Fetch matching rows with FOR UPDATE; use folder when provided to resolve ambiguity.
|
||||
let rows: Vec<EntryRow> = if let Some(uid) = params.user_id {
|
||||
if let Some(folder) = params.folder {
|
||||
sqlx::query_as(
|
||||
"SELECT id, version, tags, metadata FROM entries \
|
||||
WHERE user_id = $1 AND namespace = $2 AND kind = $3 AND name = $4 FOR UPDATE",
|
||||
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||
WHERE user_id = $1 AND folder = $2 AND name = $3 FOR UPDATE",
|
||||
)
|
||||
.bind(uid)
|
||||
.bind(params.namespace)
|
||||
.bind(params.kind)
|
||||
.bind(folder)
|
||||
.bind(params.name)
|
||||
.fetch_optional(&mut *tx)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_as(
|
||||
"SELECT id, version, tags, metadata FROM entries \
|
||||
WHERE user_id IS NULL AND namespace = $1 AND kind = $2 AND name = $3 FOR UPDATE",
|
||||
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||
WHERE user_id = $1 AND name = $2 FOR UPDATE",
|
||||
)
|
||||
.bind(params.namespace)
|
||||
.bind(params.kind)
|
||||
.bind(uid)
|
||||
.bind(params.name)
|
||||
.fetch_optional(&mut *tx)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?
|
||||
}
|
||||
} else if let Some(folder) = params.folder {
|
||||
sqlx::query_as(
|
||||
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||
WHERE user_id IS NULL AND folder = $1 AND name = $2 FOR UPDATE",
|
||||
)
|
||||
.bind(folder)
|
||||
.bind(params.name)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_as(
|
||||
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||
WHERE user_id IS NULL AND name = $1 FOR UPDATE",
|
||||
)
|
||||
.bind(params.name)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?
|
||||
};
|
||||
|
||||
let row = row.ok_or_else(|| {
|
||||
anyhow::anyhow!(
|
||||
"Not found: [{}/{}] {}. Use `add` to create it first.",
|
||||
params.namespace,
|
||||
params.kind,
|
||||
let row = match rows.len() {
|
||||
0 => {
|
||||
tx.rollback().await?;
|
||||
anyhow::bail!(
|
||||
"Not found: '{}'. Use `add` to create it first.",
|
||||
params.name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
1 => rows.into_iter().next().unwrap(),
|
||||
_ => {
|
||||
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(", ")
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = db::snapshot_entry_history(
|
||||
&mut tx,
|
||||
db::EntrySnapshotParams {
|
||||
entry_id: row.id,
|
||||
user_id: params.user_id,
|
||||
namespace: params.namespace,
|
||||
kind: params.kind,
|
||||
folder: &row.folder,
|
||||
entry_type: &row.entry_type,
|
||||
name: params.name,
|
||||
version: row.version,
|
||||
action: "update",
|
||||
@@ -117,12 +150,16 @@ pub async fn run(
|
||||
}
|
||||
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, version = version + 1, updated_at = NOW() \
|
||||
WHERE id = $3 AND version = $4",
|
||||
"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)
|
||||
@@ -131,9 +168,7 @@ pub async fn run(
|
||||
if result.rows_affected() == 0 {
|
||||
tx.rollback().await?;
|
||||
anyhow::bail!(
|
||||
"Concurrent modification detected for [{}/{}] {}. Please retry.",
|
||||
params.namespace,
|
||||
params.kind,
|
||||
"Concurrent modification detected for '{}'. Please retry.",
|
||||
params.name
|
||||
);
|
||||
}
|
||||
@@ -241,9 +276,10 @@ pub async fn run(
|
||||
|
||||
crate::audit::log_tx(
|
||||
&mut tx,
|
||||
params.user_id,
|
||||
"update",
|
||||
params.namespace,
|
||||
params.kind,
|
||||
"",
|
||||
"",
|
||||
params.name,
|
||||
serde_json::json!({
|
||||
"add_tags": params.add_tags,
|
||||
@@ -259,9 +295,9 @@ pub async fn run(
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(UpdateResult {
|
||||
namespace: params.namespace.to_string(),
|
||||
kind: params.kind.to_string(),
|
||||
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,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "secrets-mcp"
|
||||
version = "0.1.0"
|
||||
version = "0.3.2"
|
||||
edition.workspace = true
|
||||
|
||||
[[bin]]
|
||||
@@ -17,8 +17,10 @@ rmcp = { version = "1", features = ["server", "macros", "transport-streamable-ht
|
||||
axum = "0.8"
|
||||
axum-extra = { version = "0.10", features = ["typed-header"] }
|
||||
tower = "0.5"
|
||||
tower-http = { version = "0.6", features = ["cors"] }
|
||||
tower-http = { version = "0.6", features = ["cors", "trace"] }
|
||||
tower-sessions = "0.14"
|
||||
tower-sessions-sqlx-store-chrono = { version = "0.14", features = ["postgres"] }
|
||||
time = "0.3"
|
||||
|
||||
# OAuth (manual token exchange via reqwest)
|
||||
reqwest.workspace = true
|
||||
|
||||
262
crates/secrets-mcp/src/logging.rs
Normal file
262
crates/secrets-mcp/src/logging.rs
Normal file
@@ -0,0 +1,262 @@
|
||||
use std::net::SocketAddr;
|
||||
use std::time::Instant;
|
||||
|
||||
use axum::{
|
||||
body::{Body, Bytes, to_bytes},
|
||||
extract::{ConnectInfo, Request},
|
||||
http::{
|
||||
HeaderMap, Method, StatusCode,
|
||||
header::{CONTENT_LENGTH, CONTENT_TYPE, USER_AGENT},
|
||||
},
|
||||
middleware::Next,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
|
||||
/// 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.
|
||||
///
|
||||
/// Sensitive headers (Authorization, X-Encryption-Key) and secret values
|
||||
/// are never logged.
|
||||
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());
|
||||
|
||||
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();
|
||||
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(),
|
||||
&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(),
|
||||
"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>,
|
||||
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,
|
||||
"mcp request",
|
||||
);
|
||||
}
|
||||
|
||||
// ── JSON-RPC body parsing ─────────────────────────────────────────────────────
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct JsonRpcMeta {
|
||||
request_id: Option<String>,
|
||||
rpc_method: Option<String>,
|
||||
tool_name: Option<String>,
|
||||
batch_size: Option<usize>,
|
||||
}
|
||||
|
||||
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());
|
||||
|
||||
JsonRpcMeta {
|
||||
request_id,
|
||||
rpc_method,
|
||||
tool_name,
|
||||
batch_size: None,
|
||||
}
|
||||
}
|
||||
|
||||
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> {
|
||||
if let Some(first) = req
|
||||
.headers()
|
||||
.get("x-forwarded-for")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|s| s.split(',').next())
|
||||
{
|
||||
let s = first.trim();
|
||||
if !s.is_empty() {
|
||||
return Some(s.to_string());
|
||||
}
|
||||
}
|
||||
req.extensions()
|
||||
.get::<ConnectInfo<SocketAddr>>()
|
||||
.map(|c| c.ip().to_string())
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
mod auth;
|
||||
mod logging;
|
||||
mod oauth;
|
||||
mod tools;
|
||||
mod web;
|
||||
@@ -14,8 +15,11 @@ use rmcp::transport::streamable_http_server::{
|
||||
use sqlx::PgPool;
|
||||
use tower_http::cors::{Any, CorsLayer};
|
||||
use tower_sessions::cookie::SameSite;
|
||||
use tower_sessions::{MemoryStore, SessionManagerLayer};
|
||||
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_url;
|
||||
use secrets_core::db::{create_pool, migrate};
|
||||
@@ -46,14 +50,30 @@ fn load_oauth_config(prefix: &str, base_url: &str, path: &str) -> Option<OAuthCo
|
||||
})
|
||||
}
|
||||
|
||||
/// 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".into()),
|
||||
EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| "secrets_mcp=info,tower_http=info".into()),
|
||||
)
|
||||
.init();
|
||||
|
||||
@@ -70,7 +90,8 @@ async fn main() -> Result<()> {
|
||||
|
||||
// ── 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(|| "0.0.0.0: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");
|
||||
@@ -81,12 +102,23 @@ async fn main() -> Result<()> {
|
||||
);
|
||||
}
|
||||
|
||||
// ── Session store ─────────────────────────────────────────────────────────
|
||||
let session_store = MemoryStore::default();
|
||||
// ── 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_same_site(SameSite::Lax)
|
||||
.with_expiry(Expiry::OnInactivity(time::Duration::days(14)));
|
||||
|
||||
// ── App state ─────────────────────────────────────────────────────────────
|
||||
let app_state = AppState {
|
||||
@@ -120,6 +152,9 @@ async fn main() -> Result<()> {
|
||||
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,
|
||||
@@ -144,6 +179,7 @@ async fn main() -> Result<()> {
|
||||
.await
|
||||
.context("server error")?;
|
||||
|
||||
session_cleanup.abort();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,9 +1,12 @@
|
||||
use askama::Template;
|
||||
use chrono::SecondsFormat;
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use axum::{
|
||||
Json, Router,
|
||||
body::Body,
|
||||
extract::{Path, Query, State},
|
||||
http::{StatusCode, header},
|
||||
extract::{ConnectInfo, Path, Query, State},
|
||||
http::{HeaderMap, StatusCode, header},
|
||||
response::{Html, IntoResponse, Redirect, Response},
|
||||
routing::{get, post},
|
||||
};
|
||||
@@ -11,9 +14,11 @@ use serde::{Deserialize, Serialize};
|
||||
use tower_sessions::Session;
|
||||
use uuid::Uuid;
|
||||
|
||||
use secrets_core::audit::log_login;
|
||||
use secrets_core::crypto::hex;
|
||||
use secrets_core::service::{
|
||||
api_key::{ensure_api_key, regenerate_api_key},
|
||||
audit_log::list_for_user,
|
||||
user::{
|
||||
OAuthProfile, bind_oauth_account, find_or_create_user, get_user_by_id,
|
||||
unbind_oauth_account, update_user_key_setup,
|
||||
@@ -34,6 +39,15 @@ const SESSION_LOGIN_PROVIDER: &str = "login_provider";
|
||||
#[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,
|
||||
}
|
||||
|
||||
@@ -47,6 +61,23 @@ struct DashboardTemplate {
|
||||
version: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "audit.html")]
|
||||
struct AuditPageTemplate {
|
||||
user_name: String,
|
||||
user_email: String,
|
||||
entries: Vec<AuditEntryView>,
|
||||
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,
|
||||
}
|
||||
|
||||
// ── App state helpers ─────────────────────────────────────────────────────────
|
||||
|
||||
fn google_cfg(state: &AppState) -> Option<&OAuthConfig> {
|
||||
@@ -54,28 +85,71 @@ fn google_cfg(state: &AppState) -> Option<&OAuthConfig> {
|
||||
}
|
||||
|
||||
async fn current_user_id(session: &Session) -> Option<Uuid> {
|
||||
session
|
||||
.get::<String>(SESSION_USER_ID)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.and_then(|s| Uuid::parse_str(&s).ok())
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn request_client_ip(headers: &HeaderMap, connect_info: ConnectInfo<SocketAddr>) -> Option<String> {
|
||||
if let Some(first) = headers
|
||||
.get("x-forwarded-for")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|s| s.split(',').next())
|
||||
{
|
||||
let value = first.trim();
|
||||
if !value.is_empty() {
|
||||
return Some(value.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Some(connect_info.ip().to_string())
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
// ── Routes ────────────────────────────────────────────────────────────────────
|
||||
|
||||
pub fn web_router() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/robots.txt", get(robots_txt))
|
||||
.route("/llms.txt", get(llms_txt))
|
||||
.route("/ai.txt", get(ai_txt))
|
||||
.route("/favicon.svg", get(favicon_svg))
|
||||
.route(
|
||||
"/favicon.ico",
|
||||
get(|| async { Redirect::permanent("/favicon.svg") }),
|
||||
)
|
||||
.route("/", get(login_page))
|
||||
.route(
|
||||
"/.well-known/oauth-protected-resource",
|
||||
get(oauth_protected_resource_metadata),
|
||||
)
|
||||
.route("/", get(home_page))
|
||||
.route("/login", get(login_page))
|
||||
.route("/auth/google", get(auth_google))
|
||||
.route("/auth/google/callback", get(auth_google_callback))
|
||||
.route("/auth/logout", post(auth_logout))
|
||||
.route("/dashboard", get(dashboard))
|
||||
.route("/audit", get(audit_page))
|
||||
.route("/account/bind/google", get(account_bind_google))
|
||||
.route(
|
||||
"/account/bind/google/callback",
|
||||
@@ -88,6 +162,33 @@ pub fn web_router() -> Router<AppState> {
|
||||
.route("/api/apikey/regenerate", post(api_apikey_regenerate))
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
async fn robots_txt() -> Response {
|
||||
text_asset_response(
|
||||
include_str!("../static/robots.txt"),
|
||||
"text/plain; charset=utf-8",
|
||||
)
|
||||
}
|
||||
|
||||
async fn llms_txt() -> Response {
|
||||
text_asset_response(
|
||||
include_str!("../static/llms.txt"),
|
||||
"text/markdown; charset=utf-8",
|
||||
)
|
||||
}
|
||||
|
||||
async fn ai_txt() -> Response {
|
||||
llms_txt().await
|
||||
}
|
||||
|
||||
async fn favicon_svg() -> Response {
|
||||
Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
@@ -97,6 +198,21 @@ async fn favicon_svg() -> Response {
|
||||
.expect("favicon response")
|
||||
}
|
||||
|
||||
// ── Home page (public) ───────────────────────────────────────────────────────
|
||||
|
||||
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 ────────────────────────────────────────────────────────────────
|
||||
|
||||
async fn login_page(
|
||||
@@ -109,6 +225,7 @@ async fn login_page(
|
||||
|
||||
let tmpl = LoginTemplate {
|
||||
has_google: state.google_config.is_some(),
|
||||
base_url: state.base_url.clone(),
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
};
|
||||
render_template(tmpl)
|
||||
@@ -126,7 +243,10 @@ async fn auth_google(
|
||||
session
|
||||
.insert(SESSION_OAUTH_STATE, &oauth_state)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
.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())
|
||||
@@ -141,16 +261,28 @@ struct OAuthCallbackQuery {
|
||||
|
||||
async fn auth_google_callback(
|
||||
State(state): State<AppState>,
|
||||
connect_info: ConnectInfo<SocketAddr>,
|
||||
headers: HeaderMap,
|
||||
session: Session,
|
||||
Query(params): Query<OAuthCallbackQuery>,
|
||||
) -> Result<Response, StatusCode> {
|
||||
handle_oauth_callback(&state, &session, params, "google", |s, cfg, code| {
|
||||
let client_ip = request_client_ip(&headers, connect_info);
|
||||
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
|
||||
}
|
||||
|
||||
@@ -161,6 +293,8 @@ async fn handle_oauth_callback<F>(
|
||||
session: &Session,
|
||||
params: OAuthCallbackQuery,
|
||||
provider: &str,
|
||||
client_ip: Option<&str>,
|
||||
user_agent: Option<&str>,
|
||||
exchange_fn: F,
|
||||
) -> Result<Response, StatusCode>
|
||||
where
|
||||
@@ -174,31 +308,33 @@ where
|
||||
{
|
||||
if let Some(err) = params.error {
|
||||
tracing::warn!(provider, error = %err, "OAuth error");
|
||||
return Ok(Redirect::to("/?error=oauth_error").into_response());
|
||||
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("/?error=oauth_missing_code").into_response());
|
||||
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("/?error=oauth_missing_state").into_response());
|
||||
return Ok(Redirect::to("/login?error=oauth_missing_state").into_response());
|
||||
};
|
||||
|
||||
let expected_state: Option<String> = session
|
||||
.get(SESSION_OAUTH_STATE)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
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("/?error=oauth_state").into_response());
|
||||
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");
|
||||
}
|
||||
session.remove::<String>(SESSION_OAUTH_STATE).await.ok();
|
||||
|
||||
let config = match provider {
|
||||
"google" => state
|
||||
@@ -215,17 +351,25 @@ where
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let bind_mode: bool = session
|
||||
.get(SESSION_OAUTH_BIND_MODE)
|
||||
.await
|
||||
.unwrap_or(None)
|
||||
.unwrap_or(false);
|
||||
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)?;
|
||||
session.remove::<bool>(SESSION_OAUTH_BIND_MODE).await.ok();
|
||||
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,
|
||||
@@ -260,19 +404,38 @@ where
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
// Ensure the user has an API key (auto-creates on first login).
|
||||
if let Err(e) = ensure_api_key(&state.pool, user.id).await {
|
||||
tracing::warn!(error = %e, "failed to ensure api key for user");
|
||||
}
|
||||
|
||||
session
|
||||
.insert(SESSION_USER_ID, user.id.to_string())
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
.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(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
.map_err(|e| {
|
||||
tracing::error!(
|
||||
provider,
|
||||
error = %e,
|
||||
"failed to insert login_provider into session after OAuth"
|
||||
);
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
log_login(
|
||||
&state.pool,
|
||||
"oauth",
|
||||
provider,
|
||||
user.id,
|
||||
client_ip,
|
||||
user_agent,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(Redirect::to("/dashboard").into_response())
|
||||
}
|
||||
@@ -280,7 +443,9 @@ where
|
||||
// ── Logout ────────────────────────────────────────────────────────────────────
|
||||
|
||||
async fn auth_logout(session: Session) -> impl IntoResponse {
|
||||
session.flush().await.ok();
|
||||
if let Err(e) = session.flush().await {
|
||||
tracing::warn!(error = %e, "failed to flush session on logout");
|
||||
}
|
||||
Redirect::to("/")
|
||||
}
|
||||
|
||||
@@ -291,15 +456,15 @@ async fn dashboard(
|
||||
session: Session,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let Some(user_id) = current_user_id(&session).await else {
|
||||
return Ok(Redirect::to("/").into_response());
|
||||
return Ok(Redirect::to("/login").into_response());
|
||||
};
|
||||
|
||||
let user = match get_user_by_id(&state.pool, user_id)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
{
|
||||
let user = match get_user_by_id(&state.pool, user_id).await.map_err(|e| {
|
||||
tracing::error!(error = %e, %user_id, "failed to load user for dashboard");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})? {
|
||||
Some(u) => u,
|
||||
None => return Ok(Redirect::to("/").into_response()),
|
||||
None => return Ok(Redirect::to("/login").into_response()),
|
||||
};
|
||||
|
||||
let tmpl = DashboardTemplate {
|
||||
@@ -313,6 +478,49 @@ async fn dashboard(
|
||||
render_template(tmpl)
|
||||
}
|
||||
|
||||
async fn audit_page(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let Some(user_id) = current_user_id(&session).await else {
|
||||
return Ok(Redirect::to("/login").into_response());
|
||||
};
|
||||
|
||||
let user = match get_user_by_id(&state.pool, user_id).await.map_err(|e| {
|
||||
tracing::error!(error = %e, %user_id, "failed to load user for audit page");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})? {
|
||||
Some(u) => u,
|
||||
None => return Ok(Redirect::to("/login").into_response()),
|
||||
};
|
||||
|
||||
let rows = list_for_user(&state.pool, user_id, 100)
|
||||
.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,
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
};
|
||||
|
||||
render_template(tmpl)
|
||||
}
|
||||
|
||||
// ── Account bind/unbind ───────────────────────────────────────────────────────
|
||||
|
||||
async fn account_bind_google(
|
||||
@@ -326,7 +534,10 @@ async fn account_bind_google(
|
||||
session
|
||||
.insert(SESSION_OAUTH_BIND_MODE, true)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to insert oauth_bind_mode into session");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let redirect_uri = format!("{}/account/bind/google/callback", state.base_url);
|
||||
let mut cfg = state
|
||||
@@ -335,23 +546,41 @@ async fn account_bind_google(
|
||||
.ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
cfg.redirect_uri = redirect_uri;
|
||||
let st = random_state();
|
||||
session.insert(SESSION_OAUTH_STATE, &st).await.ok();
|
||||
if let Err(e) = session.insert(SESSION_OAUTH_STATE, &st).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);
|
||||
}
|
||||
|
||||
Ok(Redirect::to(&google_auth_url(&cfg, &st)).into_response())
|
||||
}
|
||||
|
||||
async fn account_bind_google_callback(
|
||||
State(state): State<AppState>,
|
||||
connect_info: ConnectInfo<SocketAddr>,
|
||||
headers: HeaderMap,
|
||||
session: Session,
|
||||
Query(params): Query<OAuthCallbackQuery>,
|
||||
) -> Result<Response, StatusCode> {
|
||||
handle_oauth_callback(&state, &session, params, "google", |s, cfg, code| {
|
||||
let client_ip = request_client_ip(&headers, connect_info);
|
||||
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
|
||||
}
|
||||
|
||||
@@ -367,7 +596,10 @@ async fn account_unbind(
|
||||
let current_login_provider = session
|
||||
.get::<String>(SESSION_LOGIN_PROVIDER)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to read login_provider from session");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
unbind_oauth_account(
|
||||
&state.pool,
|
||||
@@ -407,7 +639,10 @@ async fn api_key_salt(
|
||||
|
||||
let user = get_user_by_id(&state.pool, user_id)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.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() {
|
||||
@@ -451,10 +686,17 @@ async fn api_key_setup(
|
||||
.await
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
let salt = hex::decode_hex(&body.salt).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let key_check = hex::decode_hex(&body.key_check).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -483,9 +725,10 @@ async fn api_apikey_get(
|
||||
.await
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
let api_key = ensure_api_key(&state.pool, user_id)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
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 }))
|
||||
}
|
||||
@@ -500,11 +743,36 @@ async fn api_apikey_regenerate(
|
||||
|
||||
let api_key = regenerate_api_key(&state.pool, user_id)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, %user_id, "regenerate_api_key failed");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
Ok(Json(ApiKeyResponse { api_key }))
|
||||
}
|
||||
|
||||
// ── OAuth / Well-known ────────────────────────────────────────────────────────
|
||||
|
||||
/// 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.
|
||||
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),
|
||||
)
|
||||
}
|
||||
|
||||
// ── Helper ────────────────────────────────────────────────────────────────────
|
||||
|
||||
fn render_template<T: Template>(tmpl: T) -> Result<Response, StatusCode> {
|
||||
@@ -514,3 +782,16 @@ fn render_template<T: Template>(tmpl: T) -> Result<Response, StatusCode> {
|
||||
})?;
|
||||
Ok(Html(html).into_response())
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
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/
|
||||
154
crates/secrets-mcp/templates/audit.html
Normal file
154
crates/secrets-mcp/templates/audit.html
Normal file
@@ -0,0 +1,154 @@
|
||||
<!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); }
|
||||
.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 { font-size: 20px; font-weight: 600; margin-bottom: 8px; }
|
||||
.card-subtitle { color: var(--text-muted); font-size: 13px; margin-bottom: 20px; }
|
||||
.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;
|
||||
}
|
||||
td.col-time::before { content: "Time"; }
|
||||
td.col-action::before { content: "Action"; }
|
||||
td.col-target::before { content: "Target"; }
|
||||
td.col-detail::before { content: "Detail"; }
|
||||
.detail { max-width: none; }
|
||||
}
|
||||
</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">MCP</a>
|
||||
<a href="/audit" class="sidebar-link active">审计</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>
|
||||
<form action="/auth/logout" method="post" style="display:inline">
|
||||
<button type="submit" class="btn-sign-out">退出</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<main class="main">
|
||||
<section class="card">
|
||||
<div class="card-title">我的审计</div>
|
||||
<div class="card-subtitle">展示最近 100 条与当前用户相关的新审计记录。时间为浏览器本地时区。</div>
|
||||
|
||||
{% if entries.is_empty() %}
|
||||
<div class="empty">暂无审计记录。</div>
|
||||
{% else %}
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>时间</th>
|
||||
<th>动作</th>
|
||||
<th>目标</th>
|
||||
<th>详情</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for entry in entries %}
|
||||
<tr>
|
||||
<td class="col-time mono"><time class="audit-local-time" datetime="{{ entry.created_at_iso }}">{{ entry.created_at_iso }}</time></td>
|
||||
<td class="col-action mono">{{ entry.action }}</td>
|
||||
<td class="col-target mono">{{ entry.target }}</td>
|
||||
<td class="col-detail"><pre class="detail">{{ entry.detail }}</pre></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% endif %}
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
(function () {
|
||||
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)';
|
||||
}
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -16,13 +16,29 @@
|
||||
}
|
||||
body { background: var(--bg); color: var(--text); font-family: 'Inter', sans-serif; min-height: 100vh; }
|
||||
|
||||
/* Nav */
|
||||
.nav { background: var(--surface); border-bottom: 1px solid var(--border);
|
||||
padding: 0 24px; display: flex; align-items: center; gap: 12px; height: 52px; }
|
||||
.nav-logo { font-family: 'JetBrains Mono', monospace; font-size: 15px; font-weight: 600;
|
||||
color: var(--text); text-decoration: none; }
|
||||
.nav-logo span { color: var(--accent); }
|
||||
.nav-spacer { flex: 1; }
|
||||
.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);
|
||||
@@ -32,17 +48,20 @@
|
||||
background: none; color: var(--text); font-size: 12px; cursor: pointer; }
|
||||
.btn-sign-out:hover { background: var(--surface2); }
|
||||
|
||||
/* Main: column so footer can sit at bottom of viewport when content is short */
|
||||
/* Main content column */
|
||||
.main { display: flex; flex-direction: column; align-items: center;
|
||||
padding: 48px 24px 24px; min-height: calc(100vh - 52px); }
|
||||
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: 32px; width: 100%; max-width: 980px; }
|
||||
.card-title { font-size: 18px; font-weight: 600; margin-bottom: 6px; }
|
||||
.card-sub { font-size: 13px; color: var(--text-muted); line-height: 1.6; margin-bottom: 24px; }
|
||||
.info-box { background: var(--surface2); border: 1px solid var(--border); border-radius: 8px;
|
||||
padding: 12px 14px; margin-bottom: 18px; }
|
||||
.info-title { font-size: 12px; font-weight: 600; color: var(--text); margin-bottom: 8px; }
|
||||
.info-line { font-size: 12px; color: var(--text-muted); line-height: 1.6; }
|
||||
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; }
|
||||
@@ -128,28 +147,40 @@
|
||||
background: none; color: var(--text); font-size: 13px; cursor: pointer; }
|
||||
.btn-modal-cancel:hover { background: var(--surface2); }
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.config-tabs { grid-template-columns: 1fr; }
|
||||
@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; }
|
||||
}
|
||||
|
||||
.app-footer {
|
||||
margin-top: auto;
|
||||
width: 100%;
|
||||
max-width: 980px;
|
||||
flex-shrink: 0;
|
||||
text-align: center;
|
||||
padding-top: 28px;
|
||||
font-size: 12px;
|
||||
color: #9da7b3;
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
@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 }}">
|
||||
|
||||
<nav class="nav">
|
||||
<a href="/dashboard" class="nav-logo"><span>secrets</span></a>
|
||||
<span class="nav-spacer"></span>
|
||||
<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="/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>
|
||||
@@ -159,7 +190,7 @@
|
||||
<form action="/auth/logout" method="post" style="display:inline">
|
||||
<button type="submit" class="btn-sign-out" data-i18n="signOut">退出</button>
|
||||
</form>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<div class="main">
|
||||
<div class="card">
|
||||
@@ -167,11 +198,6 @@
|
||||
<!-- ── Locked state ──────────────────────────────────────────────────── -->
|
||||
<div id="locked-view">
|
||||
<div class="card-title" data-i18n="lockedTitle">获取 MCP 配置</div>
|
||||
<div class="card-sub" data-i18n="lockedSub">输入加密密码,派生密钥后生成完整的 MCP 配置,可直接复制到 AI 客户端。</div>
|
||||
<div class="info-box">
|
||||
<div class="info-title" data-i18n="aboutTitle">说明</div>
|
||||
<div class="info-line" data-i18n="aboutApiKey">API Key 用于身份认证,告诉服务端“你是谁”。</div>
|
||||
</div>
|
||||
|
||||
<!-- placeholder config -->
|
||||
<div class="config-wrap">
|
||||
@@ -268,9 +294,11 @@
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<footer class="app-footer">{{ version }}</footer>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Change passphrase modal ──────────────────────────────────────────────── -->
|
||||
<div class="modal-bd" id="change-modal">
|
||||
@@ -313,9 +341,6 @@ const T = {
|
||||
'zh-CN': {
|
||||
signOut: '退出',
|
||||
lockedTitle: '获取 MCP 配置',
|
||||
lockedSub: '输入加密密码,派生密钥后生成 MCP 配置;请按你所用客户端在解锁后选择对应卡片。',
|
||||
aboutTitle: '说明',
|
||||
aboutApiKey: 'API Key 用于身份认证;X-Encryption-Key 用于加解密密文。二者请仅保存在本机配置中。',
|
||||
labelPassphrase: '加密密码',
|
||||
labelConfirm: '确认密码',
|
||||
labelNew: '新密码',
|
||||
@@ -350,9 +375,6 @@ const T = {
|
||||
'zh-TW': {
|
||||
signOut: '登出',
|
||||
lockedTitle: '取得 MCP 設定',
|
||||
lockedSub: '輸入加密密碼,派生金鑰後生成 MCP 設定;請依你所用用戶端在解鎖後選擇對應卡片。',
|
||||
aboutTitle: '說明',
|
||||
aboutApiKey: 'API Key 用於身份驗證;X-Encryption-Key 用於加解密密文。二者請僅保存在本機設定中。',
|
||||
labelPassphrase: '加密密碼',
|
||||
labelConfirm: '確認密碼',
|
||||
labelNew: '新密碼',
|
||||
@@ -387,9 +409,6 @@ const T = {
|
||||
'en': {
|
||||
signOut: 'Sign out',
|
||||
lockedTitle: 'Get MCP Config',
|
||||
lockedSub: 'Enter your encryption password to derive your key and generate MCP config. After unlock, pick the card that matches your client.',
|
||||
aboutTitle: 'About',
|
||||
aboutApiKey: 'The API key authenticates you; X-Encryption-Key encrypts secret payloads. Keep both only in local client config.',
|
||||
labelPassphrase: 'Encryption password',
|
||||
labelConfirm: 'Confirm password',
|
||||
labelNew: 'New password',
|
||||
@@ -554,12 +573,14 @@ function buildOpencodeEntry(apiKey, encKey) {
|
||||
};
|
||||
}
|
||||
|
||||
/** Full OpenCode config: MCP servers live under top-level `mcp`. */
|
||||
function buildOpencodeConfigText(apiKey, encKey) {
|
||||
return JSON.stringify({ secrets: buildOpencodeEntry(apiKey, encKey) }, null, 2);
|
||||
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 = buildOpencodeConfigText(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');
|
||||
}
|
||||
|
||||
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>
|
||||
@@ -3,8 +3,19 @@
|
||||
<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 — Sign In</title>
|
||||
<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');
|
||||
@@ -17,6 +28,7 @@
|
||||
--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; }
|
||||
@@ -25,11 +37,24 @@
|
||||
padding: 48px 40px; width: 100%; max-width: 400px;
|
||||
box-shadow: 0 8px 32px rgba(0,0,0,0.4);
|
||||
}
|
||||
.topbar { display: flex; justify-content: flex-end; margin-bottom: 20px; }
|
||||
.lang-bar { display: flex; gap: 2px; background: rgba(255,255,255,0.04); border-radius: 6px; padding: 2px; }
|
||||
.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 {
|
||||
@@ -48,12 +73,14 @@
|
||||
<body>
|
||||
<div class="card">
|
||||
<div class="topbar">
|
||||
<a class="back-home" href="/" data-i18n="backHome">返回首页</a>
|
||||
<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>
|
||||
<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>
|
||||
|
||||
@@ -78,22 +105,40 @@
|
||||
<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.',
|
||||
}
|
||||
};
|
||||
|
||||
@@ -101,8 +146,23 @@
|
||||
|
||||
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);
|
||||
@@ -111,6 +171,7 @@
|
||||
const map = { 'zh-CN': '简', 'zh-TW': '繁', 'en': 'EN' };
|
||||
btn.classList.toggle('active', btn.textContent === map[currentLang]);
|
||||
});
|
||||
showOAuthError();
|
||||
}
|
||||
|
||||
function setLang(lang) {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# 复制此文件为 .env 并填写真实值
|
||||
|
||||
# ─── 数据库 ───────────────────────────────────────────────────────────
|
||||
# Web 会话(tower-sessions)与业务数据共用此库;启动时会自动 migrate 会话表,无需额外环境变量。
|
||||
SECRETS_DATABASE_URL=postgres://postgres:PASSWORD@HOST:PORT/secrets-mcp
|
||||
|
||||
# ─── 服务地址 ─────────────────────────────────────────────────────────
|
||||
@@ -21,6 +22,9 @@ GOOGLE_CLIENT_SECRET=
|
||||
# WECHAT_APP_CLIENT_ID=
|
||||
# WECHAT_APP_CLIENT_SECRET=
|
||||
|
||||
# ─── 日志(可选)──────────────────────────────────────────────────────
|
||||
# RUST_LOG=secrets_mcp=debug
|
||||
|
||||
# ─── 注意 ─────────────────────────────────────────────────────────────
|
||||
# SERVER_MASTER_KEY 已不再需要。
|
||||
# 新架构(E2EE)中,加密密钥由用户密码短语在客户端本地派生,服务端不持有原始密钥。
|
||||
|
||||
3
rust-toolchain.toml
Normal file
3
rust-toolchain.toml
Normal file
@@ -0,0 +1,3 @@
|
||||
[toolchain]
|
||||
channel = "1.94.0"
|
||||
components = ["rustfmt", "clippy"]
|
||||
22
scripts/cleanup-orphan-user-ids.sql
Normal file
22
scripts/cleanup-orphan-user-ids.sql
Normal file
@@ -0,0 +1,22 @@
|
||||
-- Run against prod BEFORE deploying secrets-mcp with FK migration.
|
||||
-- Requires: write access to SECRETS_DATABASE_URL.
|
||||
-- Example: psql "$SECRETS_DATABASE_URL" -v ON_ERROR_STOP=1 -f scripts/cleanup-orphan-user-ids.sql
|
||||
|
||||
BEGIN;
|
||||
|
||||
UPDATE entries
|
||||
SET user_id = NULL
|
||||
WHERE user_id IS NOT NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM users u WHERE u.id = entries.user_id);
|
||||
|
||||
UPDATE entries_history
|
||||
SET user_id = NULL
|
||||
WHERE user_id IS NOT NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM users u WHERE u.id = entries_history.user_id);
|
||||
|
||||
UPDATE audit_log
|
||||
SET user_id = NULL
|
||||
WHERE user_id IS NOT NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM users u WHERE u.id = audit_log.user_id);
|
||||
|
||||
COMMIT;
|
||||
194
scripts/migrate-v0.3.0.sql
Normal file
194
scripts/migrate-v0.3.0.sql
Normal file
@@ -0,0 +1,194 @@
|
||||
-- ============================================================================
|
||||
-- migrate-v0.3.0.sql
|
||||
-- Schema migration from v0.2.x → v0.3.0
|
||||
--
|
||||
-- Changes:
|
||||
-- • entries: namespace → folder, kind → type; add notes column
|
||||
-- • audit_log: namespace → folder, kind → type
|
||||
-- • entries_history: namespace → folder, kind → type; add user_id column
|
||||
-- • Unique index: (user_id, name) → (user_id, folder, name)
|
||||
-- Same name in different folders is now allowed; no rename needed.
|
||||
--
|
||||
-- Safe to run multiple times (fully idempotent).
|
||||
-- Preserves all data in users, entries, secrets.
|
||||
-- ============================================================================
|
||||
|
||||
BEGIN;
|
||||
|
||||
-- ── 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 $$;
|
||||
|
||||
-- Set NOT NULL + default for folder/type in entries
|
||||
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 $$;
|
||||
|
||||
-- Add notes column to entries if missing
|
||||
ALTER TABLE entries ADD COLUMN IF NOT EXISTS notes TEXT NOT NULL DEFAULT '';
|
||||
|
||||
-- ── 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 $$;
|
||||
|
||||
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 $$;
|
||||
|
||||
ALTER TABLE audit_log DROP COLUMN IF EXISTS actor;
|
||||
|
||||
-- ── entries_history: rename namespace→folder, kind→type; add user_id ─────────
|
||||
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 $$;
|
||||
|
||||
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 $$;
|
||||
|
||||
ALTER TABLE entries_history ADD COLUMN IF NOT EXISTS user_id UUID;
|
||||
ALTER TABLE entries_history DROP COLUMN IF EXISTS actor;
|
||||
|
||||
-- ── secrets_history: drop actor column ───────────────────────────────────────
|
||||
ALTER TABLE secrets_history DROP COLUMN IF EXISTS actor;
|
||||
|
||||
-- ── Rebuild unique indexes: (user_id, folder, name) ──────────────────────────
|
||||
-- Note: folder is now part of the key, so same name in different folders is
|
||||
-- naturally distinct — no rename of existing rows needed.
|
||||
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 with folder/type ──────────────────────
|
||||
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_entries_user_id
|
||||
ON entries(user_id) WHERE user_id IS NOT NULL;
|
||||
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);
|
||||
CREATE INDEX IF NOT EXISTS idx_entries_history_user_id
|
||||
ON entries_history(user_id) WHERE user_id IS NOT NULL;
|
||||
|
||||
COMMIT;
|
||||
|
||||
-- ── Verification queries (run these manually to confirm) ─────────────────────
|
||||
-- SELECT column_name, data_type FROM information_schema.columns
|
||||
-- WHERE table_name = 'entries' ORDER BY ordinal_position;
|
||||
-- SELECT indexname, indexdef FROM pg_indexes WHERE tablename = 'entries';
|
||||
-- SELECT COUNT(*) FROM entries;
|
||||
-- SELECT COUNT(*) FROM users;
|
||||
-- SELECT COUNT(*) FROM secrets;
|
||||
@@ -12,12 +12,13 @@ echo "==> 当前 secrets-mcp 版本: ${version}"
|
||||
echo "==> 检查是否已存在 tag: ${tag}"
|
||||
|
||||
if git rev-parse "refs/tags/${tag}" >/dev/null 2>&1; then
|
||||
echo "错误: 已存在 tag ${tag}"
|
||||
echo "请先 bump crates/secrets-mcp/Cargo.toml 中的 version,再执行 cargo build 同步 Cargo.lock。"
|
||||
exit 1
|
||||
echo "提示: 已存在 tag ${tag},将按重复构建处理,不阻断检查。"
|
||||
echo "如需创建新的发布版本,请先 bump crates/secrets-mcp/Cargo.toml 中的 version。"
|
||||
else
|
||||
echo "==> 未发现重复 tag,将创建新版本"
|
||||
fi
|
||||
|
||||
echo "==> 未发现重复 tag,开始执行检查"
|
||||
echo "==> 开始执行检查"
|
||||
cargo fmt -- --check
|
||||
cargo clippy --locked -- -D warnings
|
||||
cargo test --locked
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
# 参考: .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 用户名
|
||||
@@ -21,7 +21,7 @@
|
||||
# 1. 从 ~/.config/gitea/config.env 读取 GITEA_URL, GITEA_TOKEN, GITEA_WEBHOOK_URL
|
||||
# 2. 或通过环境变量覆盖: GITEA_TOKEN(作为 RELEASE_TOKEN 的值), WEBHOOK_URL,
|
||||
# DEPLOY_HOST, DEPLOY_USER, DEPLOY_SSH_KEY_FILE(部署到 ECS)
|
||||
# 3. 或使用 secrets CLI 获取: 需 DATABASE_URL,从 refining/service gitea 读取
|
||||
# 3. 凭据勿用 base64;部署私钥路径见 DEPLOY_SSH_KEY_FILE
|
||||
#
|
||||
|
||||
set -e
|
||||
@@ -30,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"
|
||||
@@ -59,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
|
||||
|
||||
# 优先使用环境变量
|
||||
@@ -93,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
|
||||
|
||||
Reference in New Issue
Block a user