Compare commits
4 Commits
secrets-mc
...
secrets-mc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63cb3a8216 | ||
|
|
2b994141b8 | ||
|
|
9d6ac5c13a | ||
|
|
1860cce86c |
@@ -208,6 +208,7 @@ jobs:
|
||||
DEPLOY_HOST: ${{ vars.DEPLOY_HOST }}
|
||||
DEPLOY_USER: ${{ vars.DEPLOY_USER }}
|
||||
DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
|
||||
DEPLOY_KNOWN_HOSTS: ${{ vars.DEPLOY_KNOWN_HOSTS }}
|
||||
run: |
|
||||
if [ -z "$DEPLOY_HOST" ] || [ -z "$DEPLOY_USER" ] || [ -z "$DEPLOY_SSH_KEY" ]; then
|
||||
echo "部署跳过:请配置 vars.DEPLOY_HOST、vars.DEPLOY_USER 与 secrets.DEPLOY_SSH_KEY"
|
||||
@@ -216,19 +217,26 @@ jobs:
|
||||
|
||||
echo "$DEPLOY_SSH_KEY" > /tmp/deploy_key
|
||||
chmod 600 /tmp/deploy_key
|
||||
trap 'rm -f /tmp/deploy_key' EXIT
|
||||
|
||||
scp -i /tmp/deploy_key -o StrictHostKeyChecking=no \
|
||||
if [ -n "$DEPLOY_KNOWN_HOSTS" ]; then
|
||||
echo "$DEPLOY_KNOWN_HOSTS" > /tmp/deploy_known_hosts
|
||||
ssh_opts="-o UserKnownHostsFile=/tmp/deploy_known_hosts -o StrictHostKeyChecking=yes"
|
||||
else
|
||||
ssh_opts="-o StrictHostKeyChecking=accept-new"
|
||||
fi
|
||||
|
||||
scp -i /tmp/deploy_key $ssh_opts \
|
||||
"/tmp/artifact/${MCP_BINARY}" \
|
||||
"${DEPLOY_USER}@${DEPLOY_HOST}:/tmp/secrets-mcp.new"
|
||||
|
||||
ssh -i /tmp/deploy_key -o StrictHostKeyChecking=no "${DEPLOY_USER}@${DEPLOY_HOST}" "
|
||||
ssh -i /tmp/deploy_key $ssh_opts "${DEPLOY_USER}@${DEPLOY_HOST}" "
|
||||
sudo mv /tmp/secrets-mcp.new /opt/secrets-mcp/secrets-mcp
|
||||
sudo chmod +x /opt/secrets-mcp/secrets-mcp
|
||||
sudo systemctl restart secrets-mcp
|
||||
sleep 2
|
||||
sudo systemctl is-active secrets-mcp && echo '服务启动成功' || (sudo journalctl -u secrets-mcp -n 20 && exit 1)
|
||||
"
|
||||
rm -f /tmp/deploy_key
|
||||
|
||||
- name: 飞书通知
|
||||
if: always()
|
||||
|
||||
3
.vscode/tasks.json
vendored
3
.vscode/tasks.json
vendored
@@ -22,7 +22,6 @@
|
||||
"label": "test: workspace",
|
||||
"type": "shell",
|
||||
"command": "cargo test --workspace --locked",
|
||||
"dependsOn": "build",
|
||||
"group": { "kind": "test", "isDefault": true }
|
||||
},
|
||||
{
|
||||
@@ -35,7 +34,7 @@
|
||||
"label": "clippy: workspace",
|
||||
"type": "shell",
|
||||
"command": "cargo clippy --workspace --locked -- -D warnings",
|
||||
"dependsOn": "build"
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "ci: release-check",
|
||||
|
||||
48
AGENTS.md
48
AGENTS.md
@@ -2,12 +2,37 @@
|
||||
|
||||
本仓库为 **MCP SaaS**:`secrets-core`(业务与持久化)+ `secrets-mcp`(Streamable HTTP MCP、Web、OAuth、API Key)。对外入口见 `crates/secrets-mcp`。
|
||||
|
||||
## 版本控制
|
||||
|
||||
本仓库使用 **[Jujutsu (jj)](https://jj-vcs.dev/)** 作为版本控制系统(纯 jj 模式,无 `.git` 目录)。
|
||||
|
||||
### 常用 jj 命令对照
|
||||
|
||||
| 操作 | jj 命令 |
|
||||
|------|---------|
|
||||
| 查看历史 | `jj log` / `jj log 'all()'` |
|
||||
| 查看状态 | `jj status` |
|
||||
| 新建提交 | `jj commit` |
|
||||
| 创建新变更 | `jj new` |
|
||||
| 变基 | `jj rebase` |
|
||||
| 合并提交 | `jj squash` |
|
||||
| 撤销操作 | `jj undo` |
|
||||
| 查看标签 | `jj tag list` |
|
||||
| 查看分支 | `jj bookmark list` |
|
||||
| 推送远端 | `jj git push` |
|
||||
| 拉取远端 | `jj git fetch` |
|
||||
|
||||
### 注意事项
|
||||
- 本仓库为**纯 jj 模式**,无 `.git` 目录;本地不要使用 `git` 命令
|
||||
- CI/CD(Gitea Actions)仍通过 Git 协议拉取代码,Runner 侧自动使用 `git`,无需修改
|
||||
- 检查标签是否存在时使用 `jj log --no-graph --revisions "tag(${tag})"` 而非 `git rev-parse`
|
||||
|
||||
## 提交 / 推送硬规则(优先于下文)
|
||||
|
||||
**每次提交和推送前必须执行以下检查,无论是否明确「发版」:**
|
||||
|
||||
1. 涉及 `crates/**`、根目录 `Cargo.toml`/`Cargo.lock`、`secrets-mcp` 行为变更的提交,默认视为**需要发版**,除非明确说明「本次不发版」。
|
||||
2. 提交前检查 `crates/secrets-mcp/Cargo.toml` 的 `version`,再查 tag:`git tag -l 'secrets-mcp-*'`。若当前版本对应 tag 已存在且有代码变更,**必须 bump 版本号**并 `cargo build` 同步 `Cargo.lock`。
|
||||
2. 提交前检查 `crates/secrets-mcp/Cargo.toml` 的 `version`,再查 tag:`jj tag list`。若当前版本对应 tag 已存在且有代码变更,**必须 bump 版本号**并 `cargo build` 同步 `Cargo.lock`。
|
||||
3. 提交前运行 `./scripts/release-check.sh`(版本/tag + `fmt` + `clippy --locked` + `test --locked`)。若脚本不存在或不可用,至少运行 `cargo fmt -- --check && cargo clippy --locked -- -D warnings && cargo test --locked`。
|
||||
|
||||
## 项目结构
|
||||
@@ -112,7 +137,9 @@ oauth_accounts (
|
||||
|
||||
### MCP 消歧(AI 调用)
|
||||
|
||||
按 `name` 定位条目的工具(`get` / `update` / 单条 `delete` / `history` / `rollback`):若该用户下仅一条匹配则直接执行;若多条(同 `name`、不同 `folder`)则返回错误并提示补全 `folder`。`secrets_delete` 的 `dry_run=true` 与真实删除使用相同消歧规则。
|
||||
按 `name` 定位条目的工具(`secrets_update` / `secrets_history` / `secrets_rollback` / `secrets_delete` 单条模式):若该用户下仅一条匹配则直接执行;若多条(同 `name`、不同 `folder`)则返回错误并提示补全 `folder`。也可直接传 `id`(UUID)跳过消歧。
|
||||
|
||||
注意:`secrets_get` 只接受 UUID `id`(来自 `secrets_find` 结果),不支持按 `name` 定位。
|
||||
|
||||
### 字段职责
|
||||
|
||||
@@ -144,6 +171,14 @@ oauth_accounts (
|
||||
- 加密:密钥由用户密码短语通过 **PBKDF2-SHA256(600k 次)** 在客户端派生,服务端只存 `key_salt`/`key_check`/`key_params`,不持有原始密钥。Web 客户端在浏览器本地完成加解密;MCP 客户端通过 `X-Encryption-Key` 请求头传递密钥,服务端临时解密后返回明文。
|
||||
- MCP:tools 参数与 JSON Schema(`schemars`)保持同步,鉴权以请求扩展中的用户上下文为准。
|
||||
|
||||
## 生产 CORS
|
||||
|
||||
生产环境 CORS 使用显式请求头白名单(`build_cors_layer`),而非 `allow_headers(Any)`,
|
||||
因为 `tower-http` 禁止 `allow_credentials(true)` 与 `allow_headers(Any)` 同时使用。
|
||||
|
||||
**维护约束**:若 MCP 协议或客户端新增自定义请求头,必须同步更新 `production_allowed_headers()`。
|
||||
当前允许的请求头:`Authorization`、`Content-Type`、`X-Encryption-Key`、`mcp-session-id`、`x-mcp-session`。
|
||||
|
||||
## 提交前检查
|
||||
|
||||
```bash
|
||||
@@ -162,7 +197,7 @@ cargo test --locked
|
||||
|
||||
```bash
|
||||
grep '^version' crates/secrets-mcp/Cargo.toml
|
||||
git tag -l 'secrets-mcp-*'
|
||||
jj tag list
|
||||
```
|
||||
|
||||
## CI/CD
|
||||
@@ -182,10 +217,17 @@ git tag -l 'secrets-mcp-*'
|
||||
| `SECRETS_DATABASE_URL` | **必填**。PostgreSQL URL。 |
|
||||
| `SECRETS_DATABASE_SSL_MODE` | 可选但强烈建议生产必填。推荐 `verify-full`(至少 `verify-ca`)。 |
|
||||
| `SECRETS_DATABASE_SSL_ROOT_CERT` | 可选。私有 CA 或自签链路时指定 CA 根证书路径。 |
|
||||
| `SECRETS_DATABASE_POOL_SIZE` | 可选。连接池最大连接数,默认 `10`。 |
|
||||
| `SECRETS_DATABASE_ACQUIRE_TIMEOUT` | 可选。获取连接超时秒数,默认 `5`。 |
|
||||
| `SECRETS_ENV` | 可选。设为 `prod` / `production` 时会拒绝弱 PostgreSQL TLS 模式。 |
|
||||
| `BASE_URL` | 对外基址;OAuth 回调 `${BASE_URL}/auth/google/callback`。 |
|
||||
| `SECRETS_MCP_BIND` | 监听地址,默认 `127.0.0.1:9315`(容器/远程直接暴露时需改为 `0.0.0.0:9315`)。 |
|
||||
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | 可选;仅运行时配置。 |
|
||||
| `RUST_LOG` | 如 `secrets_mcp=debug`。 |
|
||||
| `RATE_LIMIT_GLOBAL_PER_SECOND` | 可选。全局限流速率,默认 `100` req/s。 |
|
||||
| `RATE_LIMIT_GLOBAL_BURST` | 可选。全局限流突发量,默认 `200`。 |
|
||||
| `RATE_LIMIT_IP_PER_SECOND` | 可选。单 IP 限流速率,默认 `20` req/s。 |
|
||||
| `RATE_LIMIT_IP_BURST` | 可选。单 IP 限流突发量,默认 `40`。 |
|
||||
| `TRUST_PROXY` | 可选。设为 `1`/`true`/`yes` 时从 `X-Forwarded-For` / `X-Real-IP` 提取客户端 IP。 |
|
||||
|
||||
> `SERVER_MASTER_KEY` 已不再需要。新架构下密钥由用户密码短语在客户端派生,服务端不持有。
|
||||
|
||||
55
CONTRIBUTING.md
Normal file
55
CONTRIBUTING.md
Normal file
@@ -0,0 +1,55 @@
|
||||
# Contributing
|
||||
|
||||
## 版本控制
|
||||
|
||||
本仓库使用 **[Jujutsu (jj)](https://jj-vcs.dev/)**。请勿使用 `git` 命令。
|
||||
|
||||
```bash
|
||||
jj log # 查看历史
|
||||
jj status # 查看状态
|
||||
jj new # 创建新变更
|
||||
jj commit # 提交
|
||||
jj rebase # 变基
|
||||
jj squash # 合并提交
|
||||
jj git push # 推送到远端
|
||||
```
|
||||
|
||||
详见 [AGENTS.md](AGENTS.md) 的「版本控制」章节。
|
||||
|
||||
## 本地开发
|
||||
|
||||
```bash
|
||||
# 复制环境变量
|
||||
cp deploy/.env.example .env
|
||||
|
||||
# 填写数据库连接等配置后
|
||||
cargo build
|
||||
cargo test --locked
|
||||
```
|
||||
|
||||
## 提交前检查
|
||||
|
||||
每次提交前必须通过:
|
||||
|
||||
```bash
|
||||
cargo fmt -- --check
|
||||
cargo clippy --locked -- -D warnings
|
||||
cargo test --locked
|
||||
```
|
||||
|
||||
或使用脚本:
|
||||
|
||||
```bash
|
||||
./scripts/release-check.sh
|
||||
```
|
||||
|
||||
## 发版规则
|
||||
|
||||
涉及 `crates/**`、根目录 `Cargo.toml`/`Cargo.lock`、`secrets-mcp` 行为变更的提交,默认需要发版。
|
||||
|
||||
1. 检查 `crates/secrets-mcp/Cargo.toml` 的 `version`
|
||||
2. 运行 `jj tag list` 确认对应 tag 是否已存在
|
||||
3. 若 tag 已存在且有代码变更,**必须 bump 版本**并 `cargo build` 同步 `Cargo.lock`
|
||||
4. 通过 release-check 后再提交
|
||||
|
||||
详见 [AGENTS.md](AGENTS.md) 的「提交 / 推送硬规则」章节。
|
||||
3
Cargo.lock
generated
3
Cargo.lock
generated
@@ -2049,6 +2049,7 @@ dependencies = [
|
||||
"aes-gcm",
|
||||
"anyhow",
|
||||
"chrono",
|
||||
"hex",
|
||||
"rand 0.10.0",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -2065,7 +2066,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "secrets-mcp"
|
||||
version = "0.5.2"
|
||||
version = "0.5.6"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"askama",
|
||||
|
||||
@@ -25,6 +25,13 @@ cargo build --release -p secrets-mcp
|
||||
| `SECRETS_MCP_BIND` | 监听地址,默认 `127.0.0.1:9315`。容器内或直接对外暴露端口时请改为 `0.0.0.0:9315`;反代时常为 `127.0.0.1:9315`。 |
|
||||
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | 可选;不配置则无 Google 登录入口。运行时从环境读取,勿写入 CI、勿打入二进制。 |
|
||||
| `RUST_LOG` | 可选;日志级别,如 `secrets_mcp=debug`。 |
|
||||
| `SECRETS_DATABASE_POOL_SIZE` | 可选。连接池最大连接数,默认 `10`。 |
|
||||
| `SECRETS_DATABASE_ACQUIRE_TIMEOUT` | 可选。获取连接超时秒数,默认 `5`。 |
|
||||
| `RATE_LIMIT_GLOBAL_PER_SECOND` | 可选。全局限流速率,默认 `100` req/s。 |
|
||||
| `RATE_LIMIT_GLOBAL_BURST` | 可选。全局限流突发量,默认 `200`。 |
|
||||
| `RATE_LIMIT_IP_PER_SECOND` | 可选。单 IP 限流速率,默认 `20` req/s。 |
|
||||
| `RATE_LIMIT_IP_BURST` | 可选。单 IP 限流突发量,默认 `40`。 |
|
||||
| `TRUST_PROXY` | 可选。设为 `1`/`true`/`yes` 时从 `X-Forwarded-For` / `X-Real-IP` 提取客户端 IP;仅在反代环境下启用。 |
|
||||
|
||||
```bash
|
||||
cargo run -p secrets-mcp
|
||||
|
||||
@@ -12,6 +12,7 @@ aes-gcm.workspace = true
|
||||
anyhow.workspace = true
|
||||
thiserror.workspace = true
|
||||
chrono.workspace = true
|
||||
hex = "0.4"
|
||||
rand.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
@@ -61,7 +61,7 @@ pub fn decrypt_json(master_key: &[u8; 32], data: &[u8]) -> Result<Value> {
|
||||
|
||||
/// Parse a 64-char hex string (from X-Encryption-Key header) into a 32-byte key.
|
||||
pub fn extract_key_from_hex(hex_str: &str) -> Result<[u8; 32]> {
|
||||
let bytes = hex::decode_hex(hex_str.trim())?;
|
||||
let bytes = ::hex::decode(hex_str.trim())?;
|
||||
if bytes.len() != 32 {
|
||||
bail!(
|
||||
"X-Encryption-Key must be 64 hex chars (32 bytes), got {} bytes",
|
||||
@@ -76,21 +76,14 @@ pub fn extract_key_from_hex(hex_str: &str) -> Result<[u8; 32]> {
|
||||
// ─── Public hex helpers ───────────────────────────────────────────────────────
|
||||
|
||||
pub mod hex {
|
||||
use anyhow::{Result, bail};
|
||||
use anyhow::Result;
|
||||
|
||||
pub fn encode_hex(bytes: &[u8]) -> String {
|
||||
bytes.iter().map(|b| format!("{:02x}", b)).collect()
|
||||
}
|
||||
|
||||
pub fn decode_hex(s: &str) -> Result<Vec<u8>> {
|
||||
let s = s.trim();
|
||||
if !s.len().is_multiple_of(2) {
|
||||
bail!("hex string has odd length");
|
||||
}
|
||||
(0..s.len())
|
||||
.step_by(2)
|
||||
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).map_err(|e| anyhow::anyhow!("{}", e)))
|
||||
.collect()
|
||||
Ok(::hex::decode(s.trim())?)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -243,6 +243,11 @@ pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) ->
|
||||
tracing::warn!(error = %e, "failed to snapshot entry history before upsert");
|
||||
}
|
||||
|
||||
// Upsert the entry row. On conflict (existing entry with same user_id+folder+name),
|
||||
// the entry columns are replaced wholesale. The old secret associations are torn down
|
||||
// below within the same transaction, so the whole operation is atomic: if any step
|
||||
// after this point fails, the transaction rolls back and the entry reverts to its
|
||||
// pre-upsert state (including the version bump that happened in the DO UPDATE clause).
|
||||
let entry_id: Uuid = if let Some(uid) = params.user_id {
|
||||
sqlx::query_scalar(
|
||||
r#"INSERT INTO entries (user_id, folder, type, name, notes, tags, metadata, version, updated_at)
|
||||
|
||||
@@ -4,20 +4,36 @@ use uuid::Uuid;
|
||||
|
||||
use crate::models::AuditLogEntry;
|
||||
|
||||
pub async fn list_for_user(pool: &PgPool, user_id: Uuid, limit: i64) -> Result<Vec<AuditLogEntry>> {
|
||||
pub async fn list_for_user(
|
||||
pool: &PgPool,
|
||||
user_id: Uuid,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<AuditLogEntry>> {
|
||||
let limit = limit.clamp(1, 200);
|
||||
let offset = offset.max(0);
|
||||
|
||||
let rows = sqlx::query_as(
|
||||
"SELECT id, user_id, action, folder, type, name, detail, created_at \
|
||||
FROM audit_log \
|
||||
WHERE user_id = $1 \
|
||||
ORDER BY created_at DESC, id DESC \
|
||||
LIMIT $2",
|
||||
LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
pub async fn count_for_user(pool: &PgPool, user_id: Uuid) -> Result<i64> {
|
||||
let count: i64 =
|
||||
sqlx::query_scalar("SELECT COUNT(*)::bigint FROM audit_log WHERE user_id = $1")
|
||||
.bind(user_id)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
@@ -31,6 +31,10 @@ pub struct DeleteParams<'a> {
|
||||
pub user_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
/// Maximum number of entries that can be deleted in a single bulk operation.
|
||||
/// Prevents accidental mass deletion when filters are too broad.
|
||||
pub const MAX_BULK_DELETE: usize = 1000;
|
||||
|
||||
/// Delete a single entry by id (multi-tenant: `user_id` must match).
|
||||
pub async fn delete_by_id(pool: &PgPool, entry_id: Uuid, user_id: Uuid) -> Result<DeleteResult> {
|
||||
let mut tx = pool.begin().await?;
|
||||
@@ -374,6 +378,16 @@ async fn delete_bulk(
|
||||
}
|
||||
let rows = q.fetch_all(&mut *tx).await?;
|
||||
|
||||
if rows.len() > MAX_BULK_DELETE {
|
||||
tx.rollback().await?;
|
||||
anyhow::bail!(
|
||||
"Bulk delete would affect {} entries (limit: {}). \
|
||||
Narrow your filters or delete entries individually.",
|
||||
rows.len(),
|
||||
MAX_BULK_DELETE,
|
||||
);
|
||||
}
|
||||
|
||||
let mut deleted = Vec::with_capacity(rows.len());
|
||||
for row in &rows {
|
||||
let entry_row: EntryRow = EntryRow {
|
||||
|
||||
@@ -54,7 +54,13 @@ pub async fn run(
|
||||
.bind(params.user_id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap_or(false);
|
||||
.map_err(|e| {
|
||||
anyhow::anyhow!(
|
||||
"Failed to check entry existence for '{}': {}",
|
||||
entry.name,
|
||||
e
|
||||
)
|
||||
})?;
|
||||
|
||||
if exists && !params.force {
|
||||
return Err(anyhow::anyhow!(
|
||||
|
||||
@@ -228,9 +228,11 @@ pub async fn run(
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE entries SET tags = $1, metadata = $2, version = version + 1, \
|
||||
updated_at = NOW() WHERE id = $3",
|
||||
"UPDATE entries SET folder = $1, type = $2, tags = $3, metadata = $4, version = version + 1, \
|
||||
updated_at = NOW() WHERE id = $5",
|
||||
)
|
||||
.bind(&snap.folder)
|
||||
.bind(&snap.entry_type)
|
||||
.bind(&snap.tags)
|
||||
.bind(&snap.metadata)
|
||||
.bind(lr.id)
|
||||
|
||||
@@ -402,8 +402,8 @@ pub async fn run(
|
||||
&mut tx,
|
||||
params.user_id,
|
||||
"update",
|
||||
"",
|
||||
"",
|
||||
&row.folder,
|
||||
&row.entry_type,
|
||||
params.name,
|
||||
serde_json::json!({
|
||||
"add_tags": params.add_tags,
|
||||
|
||||
@@ -200,10 +200,14 @@ pub async fn unbind_oauth_account(
|
||||
);
|
||||
}
|
||||
|
||||
let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM oauth_accounts WHERE user_id = $1")
|
||||
.bind(user_id)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
let locked_accounts: Vec<(String,)> =
|
||||
sqlx::query_as("SELECT provider FROM oauth_accounts WHERE user_id = $1 FOR UPDATE")
|
||||
.bind(user_id)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
let count = locked_accounts.len();
|
||||
|
||||
if count <= 1 {
|
||||
anyhow::bail!("Cannot unbind the last OAuth account. Please link another account first.");
|
||||
@@ -212,8 +216,87 @@ pub async fn unbind_oauth_account(
|
||||
sqlx::query("DELETE FROM oauth_accounts WHERE user_id = $1 AND provider = $2")
|
||||
.bind(user_id)
|
||||
.bind(provider)
|
||||
.execute(pool)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
async fn maybe_test_pool() -> Option<PgPool> {
|
||||
let database_url = match std::env::var("SECRETS_DATABASE_URL") {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
eprintln!("skip user service tests: SECRETS_DATABASE_URL not set");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let pool = match sqlx::PgPool::connect(&database_url).await {
|
||||
Ok(pool) => pool,
|
||||
Err(e) => {
|
||||
eprintln!("skip user service tests: cannot connect to database: {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if let Err(e) = crate::db::migrate(&pool).await {
|
||||
eprintln!("skip user service tests: migrate failed: {e}");
|
||||
return None;
|
||||
}
|
||||
Some(pool)
|
||||
}
|
||||
|
||||
async fn cleanup_user_rows(pool: &PgPool, user_id: Uuid) -> Result<()> {
|
||||
sqlx::query("DELETE FROM oauth_accounts WHERE user_id = $1")
|
||||
.bind(user_id)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM users WHERE id = $1")
|
||||
.bind(user_id)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unbind_oauth_account_removes_only_requested_provider() -> Result<()> {
|
||||
let Some(pool) = maybe_test_pool().await else {
|
||||
return Ok(());
|
||||
};
|
||||
let user_id = Uuid::from_u128(rand::random());
|
||||
|
||||
cleanup_user_rows(&pool, user_id).await?;
|
||||
|
||||
sqlx::query("INSERT INTO users (id, name) VALUES ($1, '')")
|
||||
.bind(user_id)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO oauth_accounts (user_id, provider, provider_id, email, name, avatar_url) \
|
||||
VALUES ($1, 'google', $2, NULL, NULL, NULL), \
|
||||
($1, 'github', $3, NULL, NULL, NULL)",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(format!("google-{user_id}"))
|
||||
.bind(format!("github-{user_id}"))
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
|
||||
unbind_oauth_account(&pool, user_id, "github", Some("google")).await?;
|
||||
|
||||
let remaining: Vec<(String,)> = sqlx::query_as(
|
||||
"SELECT provider FROM oauth_accounts WHERE user_id = $1 ORDER BY provider",
|
||||
)
|
||||
.bind(user_id)
|
||||
.fetch_all(&pool)
|
||||
.await?;
|
||||
assert_eq!(remaining, vec![("google".to_string(),)]);
|
||||
|
||||
cleanup_user_rows(&pool, user_id).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "secrets-mcp"
|
||||
version = "0.5.2"
|
||||
version = "0.5.6"
|
||||
edition.workspace = true
|
||||
|
||||
[[bin]]
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
use std::net::SocketAddr;
|
||||
use std::time::Instant;
|
||||
|
||||
use axum::{
|
||||
body::{Body, Bytes, to_bytes},
|
||||
extract::{ConnectInfo, Request},
|
||||
extract::Request,
|
||||
http::{
|
||||
HeaderMap, Method, StatusCode,
|
||||
header::{CONTENT_LENGTH, CONTENT_TYPE, USER_AGENT},
|
||||
@@ -245,18 +244,5 @@ fn header_str(headers: &HeaderMap, name: impl axum::http::header::AsHeaderName)
|
||||
}
|
||||
|
||||
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())
|
||||
crate::client_ip::extract_client_ip(req).into()
|
||||
}
|
||||
|
||||
@@ -165,30 +165,7 @@ async fn main() -> Result<()> {
|
||||
Some("prod" | "production")
|
||||
);
|
||||
|
||||
let cors = if is_production {
|
||||
// Only use the origin part (scheme://host:port) of BASE_URL for CORS.
|
||||
// Browsers send Origin without path, so including a path would cause mismatches.
|
||||
let allowed_origin = if let Ok(parsed) = base_url.parse::<url::Url>() {
|
||||
let origin = parsed.origin().ascii_serialization();
|
||||
origin
|
||||
.parse::<axum::http::HeaderValue>()
|
||||
.unwrap_or_else(|_| panic!("invalid BASE_URL origin: {}", origin))
|
||||
} else {
|
||||
base_url
|
||||
.parse::<axum::http::HeaderValue>()
|
||||
.unwrap_or_else(|_| panic!("invalid BASE_URL: {}", base_url))
|
||||
};
|
||||
CorsLayer::new()
|
||||
.allow_origin(allowed_origin)
|
||||
.allow_methods(Any)
|
||||
.allow_headers(Any)
|
||||
.allow_credentials(true)
|
||||
} else {
|
||||
CorsLayer::new()
|
||||
.allow_origin(Any)
|
||||
.allow_methods(Any)
|
||||
.allow_headers(Any)
|
||||
};
|
||||
let cors = build_cors_layer(&base_url, is_production);
|
||||
|
||||
// Rate limiting
|
||||
let rate_limit_state = rate_limit::RateLimitState::new();
|
||||
@@ -210,6 +187,9 @@ async fn main() -> Result<()> {
|
||||
))
|
||||
.layer(session_layer)
|
||||
.layer(cors)
|
||||
.layer(tower_http::limit::RequestBodyLimitLayer::new(
|
||||
10 * 1024 * 1024,
|
||||
))
|
||||
.with_state(app_state);
|
||||
|
||||
// ── Start server ──────────────────────────────────────────────────────────
|
||||
@@ -257,3 +237,110 @@ async fn shutdown_signal() {
|
||||
|
||||
tracing::info!("Shutting down gracefully...");
|
||||
}
|
||||
|
||||
/// Production CORS allowed headers.
|
||||
///
|
||||
/// When adding a new custom header to the MCP or Web API, this list must be
|
||||
/// updated accordingly — otherwise browsers will block the request during
|
||||
/// the CORS preflight check.
|
||||
fn production_allowed_headers() -> [axum::http::HeaderName; 5] {
|
||||
[
|
||||
axum::http::header::AUTHORIZATION,
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
axum::http::HeaderName::from_static("x-encryption-key"),
|
||||
axum::http::HeaderName::from_static("mcp-session-id"),
|
||||
axum::http::HeaderName::from_static("x-mcp-session"),
|
||||
]
|
||||
}
|
||||
|
||||
/// Production CORS allowed methods.
|
||||
///
|
||||
/// Keep this list explicit because tower-http rejects
|
||||
/// `allow_credentials(true)` together with `allow_methods(Any)`.
|
||||
fn production_allowed_methods() -> [axum::http::Method; 5] {
|
||||
[
|
||||
axum::http::Method::GET,
|
||||
axum::http::Method::POST,
|
||||
axum::http::Method::PATCH,
|
||||
axum::http::Method::DELETE,
|
||||
axum::http::Method::OPTIONS,
|
||||
]
|
||||
}
|
||||
|
||||
/// Build the CORS layer for the application.
|
||||
///
|
||||
/// In production mode the origin is restricted to the BASE_URL origin
|
||||
/// (scheme://host:port, path stripped) and credentials are allowed.
|
||||
/// `allow_headers` and `allow_methods` use explicit whitelists to avoid the
|
||||
/// tower-http restriction on `allow_credentials(true)` + wildcards.
|
||||
///
|
||||
/// In development mode all origins, methods and headers are allowed.
|
||||
fn build_cors_layer(base_url: &str, is_production: bool) -> CorsLayer {
|
||||
if is_production {
|
||||
let allowed_origin = if let Ok(parsed) = base_url.parse::<url::Url>() {
|
||||
let origin = parsed.origin().ascii_serialization();
|
||||
origin
|
||||
.parse::<axum::http::HeaderValue>()
|
||||
.unwrap_or_else(|_| panic!("invalid BASE_URL origin: {}", origin))
|
||||
} else {
|
||||
base_url
|
||||
.parse::<axum::http::HeaderValue>()
|
||||
.unwrap_or_else(|_| panic!("invalid BASE_URL: {}", base_url))
|
||||
};
|
||||
CorsLayer::new()
|
||||
.allow_origin(allowed_origin)
|
||||
.allow_methods(production_allowed_methods())
|
||||
.allow_headers(production_allowed_headers())
|
||||
.allow_credentials(true)
|
||||
} else {
|
||||
CorsLayer::new()
|
||||
.allow_origin(Any)
|
||||
.allow_methods(Any)
|
||||
.allow_headers(Any)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn production_cors_does_not_panic() {
|
||||
let layer = build_cors_layer("https://secrets.example.com/app", true);
|
||||
let _ = layer;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_cors_headers_include_all_required() {
|
||||
let headers = production_allowed_headers();
|
||||
let names: Vec<&str> = headers.iter().map(|h| h.as_str()).collect();
|
||||
assert!(names.contains(&"authorization"));
|
||||
assert!(names.contains(&"content-type"));
|
||||
assert!(names.contains(&"x-encryption-key"));
|
||||
assert!(names.contains(&"mcp-session-id"));
|
||||
assert!(names.contains(&"x-mcp-session"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_cors_methods_include_all_required() {
|
||||
let methods = production_allowed_methods();
|
||||
assert!(methods.contains(&axum::http::Method::GET));
|
||||
assert!(methods.contains(&axum::http::Method::POST));
|
||||
assert!(methods.contains(&axum::http::Method::PATCH));
|
||||
assert!(methods.contains(&axum::http::Method::DELETE));
|
||||
assert!(methods.contains(&axum::http::Method::OPTIONS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_cors_normalizes_base_url_with_path() {
|
||||
let url = url::Url::parse("https://secrets.example.com/secrets/app").unwrap();
|
||||
let origin = url.origin().ascii_serialization();
|
||||
assert_eq!(origin, "https://secrets.example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn development_cors_allows_everything() {
|
||||
let layer = build_cors_layer("http://localhost:9315", false);
|
||||
let _ = layer;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -230,15 +230,6 @@ impl SecretsService {
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract user_id from the HTTP request parts injected by auth middleware.
|
||||
fn user_id_from_ctx(ctx: &RequestContext<RoleServer>) -> Result<Option<Uuid>, rmcp::ErrorData> {
|
||||
let parts = ctx
|
||||
.extensions
|
||||
.get::<http::request::Parts>()
|
||||
.ok_or_else(mcp_err_missing_http_parts)?;
|
||||
Ok(parts.extensions.get::<AuthUser>().map(|a| a.user_id))
|
||||
}
|
||||
|
||||
/// Get the authenticated user_id (returns error if not authenticated).
|
||||
fn require_user_id(ctx: &RequestContext<RoleServer>) -> Result<Uuid, rmcp::ErrorData> {
|
||||
let parts = ctx
|
||||
@@ -335,6 +326,9 @@ struct FindInput {
|
||||
#[schemars(description = "Max results (default 20)")]
|
||||
#[serde(default, deserialize_with = "deser::option_u32_from_string")]
|
||||
limit: Option<u32>,
|
||||
#[schemars(description = "Offset for pagination (default 0)")]
|
||||
#[serde(default, deserialize_with = "deser::option_u32_from_string")]
|
||||
offset: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
@@ -608,6 +602,10 @@ fn map_to_kv_strings(map: Map<String, Value>) -> Vec<String> {
|
||||
/// contain `@` characters (e.g. `config:=@/etc/passwd`), the `:=` branch in
|
||||
/// `parse_kv` treats the right-hand side as raw JSON and never performs file
|
||||
/// reads. The `@` in such cases is just data, not a file reference.
|
||||
///
|
||||
/// For entries without `=` that contain `@`, we only reject them if the `@`
|
||||
/// appears to be file-path syntax (i.e., the part after `@` starts with `/`,
|
||||
/// `~`, or `.`). This avoids false positives on values like `user@example.com`.
|
||||
fn contains_file_reference(entries: &[String]) -> Option<String> {
|
||||
for entry in entries {
|
||||
// key:=json — safe, skip before checking for `=`
|
||||
@@ -622,12 +620,14 @@ fn contains_file_reference(entries: &[String]) -> Option<String> {
|
||||
continue;
|
||||
}
|
||||
// key@path (no `=` present)
|
||||
// parse_kv treats entries without `=` that contain `@` as file-read
|
||||
// syntax (key@path). This includes strings like "user@example.com"
|
||||
// if passed without a `=` separator — which is correct to reject here
|
||||
// since the MCP server runs remotely and cannot read local files.
|
||||
if entry.contains('@') {
|
||||
return Some(entry.clone());
|
||||
// Only reject if the `@` looks like file-path syntax: the segment after
|
||||
// `@` starts with `/`, `~`, or `.`, which are common path prefixes.
|
||||
// Values like "user@example.com" pass through safely.
|
||||
if let Some((_, path_part)) = entry.split_once('@') {
|
||||
let trimmed = path_part.trim_start();
|
||||
if trimmed.starts_with('/') || trimmed.starts_with('~') || trimmed.starts_with('.') {
|
||||
return Some(entry.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
@@ -680,13 +680,33 @@ impl SecretsService {
|
||||
query: input.query.as_deref(),
|
||||
sort: "name",
|
||||
limit: input.limit.unwrap_or(20),
|
||||
offset: 0,
|
||||
offset: input.offset.unwrap_or(0),
|
||||
user_id: Some(user_id),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_find", Some(user_id), e))?;
|
||||
|
||||
let count_params = SearchParams {
|
||||
folder: input.folder.as_deref(),
|
||||
entry_type: input.entry_type.as_deref(),
|
||||
name: input.name.as_deref(),
|
||||
name_query: input.name_query.as_deref(),
|
||||
tags: &tags,
|
||||
query: input.query.as_deref(),
|
||||
sort: "name",
|
||||
limit: 0,
|
||||
offset: 0,
|
||||
user_id: Some(user_id),
|
||||
};
|
||||
|
||||
let total_count = secrets_core::service::search::count_entries(&self.pool, &count_params)
|
||||
.await
|
||||
.inspect_err(
|
||||
|e| tracing::warn!(tool = "secrets_find", error = %e, "count_entries failed"),
|
||||
)
|
||||
.unwrap_or(0);
|
||||
|
||||
let entries: Vec<serde_json::Value> = result
|
||||
.entries
|
||||
.iter()
|
||||
@@ -719,14 +739,20 @@ impl SecretsService {
|
||||
})
|
||||
.collect();
|
||||
|
||||
let output = serde_json::json!({
|
||||
"total_count": total_count,
|
||||
"entries": entries,
|
||||
});
|
||||
|
||||
tracing::info!(
|
||||
tool = "secrets_find",
|
||||
?user_id,
|
||||
result_count = entries.len(),
|
||||
total_count,
|
||||
elapsed_ms = t.elapsed().as_millis(),
|
||||
"tool call ok",
|
||||
);
|
||||
let json = serde_json::to_string_pretty(&entries).unwrap_or_else(|_| "[]".to_string());
|
||||
let json = serde_json::to_string_pretty(&output).unwrap_or_else(|_| "{}".to_string());
|
||||
Ok(CallToolResult::success(vec![Content::text(json)]))
|
||||
}
|
||||
|
||||
@@ -1107,7 +1133,7 @@ impl SecretsService {
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, rmcp::ErrorData> {
|
||||
let t = Instant::now();
|
||||
let user_id = Self::user_id_from_ctx(&ctx)?;
|
||||
let user_id = Self::require_user_id(&ctx)?;
|
||||
|
||||
// Safety: require at least one filter.
|
||||
if input.id.is_none()
|
||||
@@ -1137,9 +1163,9 @@ impl SecretsService {
|
||||
if let Some(ref id_str) = input.id {
|
||||
let eid = parse_uuid(id_str)?;
|
||||
let uid = user_id;
|
||||
let entry = resolve_entry_by_id(&self.pool, eid, uid)
|
||||
let entry = resolve_entry_by_id(&self.pool, eid, Some(uid))
|
||||
.await
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_delete", uid, e))?;
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_delete", Some(uid), e))?;
|
||||
(Some(entry.name), Some(entry.folder))
|
||||
} else {
|
||||
(input.name.clone(), input.folder.clone())
|
||||
@@ -1152,11 +1178,11 @@ impl SecretsService {
|
||||
folder: effective_folder.as_deref(),
|
||||
entry_type: input.entry_type.as_deref(),
|
||||
dry_run: input.dry_run.unwrap_or(false),
|
||||
user_id,
|
||||
user_id: Some(user_id),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_delete", user_id, e))?;
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_delete", Some(user_id), e))?;
|
||||
|
||||
tracing::info!(
|
||||
tool = "secrets_delete",
|
||||
@@ -1183,7 +1209,7 @@ impl SecretsService {
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, rmcp::ErrorData> {
|
||||
let t = Instant::now();
|
||||
let user_id = Self::user_id_from_ctx(&ctx)?;
|
||||
let user_id = Self::require_user_id(&ctx)?;
|
||||
tracing::info!(
|
||||
tool = "secrets_history",
|
||||
?user_id,
|
||||
@@ -1195,9 +1221,9 @@ impl SecretsService {
|
||||
let (resolved_name, resolved_folder): (String, Option<String>) =
|
||||
if let Some(ref id_str) = input.id {
|
||||
let eid = parse_uuid(id_str)?;
|
||||
let entry = resolve_entry_by_id(&self.pool, eid, user_id)
|
||||
let entry = resolve_entry_by_id(&self.pool, eid, Some(user_id))
|
||||
.await
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_history", user_id, e))?;
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_history", Some(user_id), e))?;
|
||||
(entry.name, Some(entry.folder))
|
||||
} else {
|
||||
(input.name.clone(), input.folder.clone())
|
||||
@@ -1208,10 +1234,10 @@ impl SecretsService {
|
||||
&resolved_name,
|
||||
resolved_folder.as_deref(),
|
||||
input.limit.unwrap_or(20),
|
||||
user_id,
|
||||
Some(user_id),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_history", user_id, e))?;
|
||||
.map_err(|e| mcp_err_internal_logged("secrets_history", Some(user_id), e))?;
|
||||
|
||||
tracing::info!(
|
||||
tool = "secrets_history",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use askama::Template;
|
||||
use chrono::SecondsFormat;
|
||||
use std::net::SocketAddr;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
|
||||
use axum::{
|
||||
Json, Router,
|
||||
@@ -20,9 +20,9 @@ use secrets_core::crypto::hex;
|
||||
use secrets_core::error::AppError;
|
||||
use secrets_core::service::{
|
||||
api_key::{ensure_api_key, regenerate_api_key},
|
||||
audit_log::list_for_user,
|
||||
audit_log::{count_for_user, list_for_user},
|
||||
delete::delete_by_id,
|
||||
search::{SearchParams, fetch_secret_schemas, ilike_pattern, list_entries},
|
||||
search::{SearchParams, count_entries, fetch_secret_schemas, ilike_pattern, list_entries},
|
||||
update::{UpdateEntryFieldsByIdParams, update_fields_by_id},
|
||||
user::{
|
||||
OAuthProfile, bind_oauth_account, find_or_create_user, get_user_by_id,
|
||||
@@ -72,6 +72,9 @@ struct AuditPageTemplate {
|
||||
user_name: String,
|
||||
user_email: String,
|
||||
entries: Vec<AuditEntryView>,
|
||||
current_page: u32,
|
||||
total_pages: u32,
|
||||
total_count: i64,
|
||||
version: &'static str,
|
||||
}
|
||||
|
||||
@@ -95,6 +98,9 @@ struct EntriesPageTemplate {
|
||||
filter_folder: String,
|
||||
filter_name: String,
|
||||
filter_type: String,
|
||||
current_page: u32,
|
||||
total_pages: u32,
|
||||
total_count: i64,
|
||||
version: &'static str,
|
||||
}
|
||||
|
||||
@@ -131,7 +137,8 @@ struct FolderTabView {
|
||||
}
|
||||
|
||||
/// Cap for HTML list (avoids loading unbounded rows into memory).
|
||||
const ENTRIES_PAGE_LIMIT: u32 = 5_000;
|
||||
const ENTRIES_PAGE_LIMIT: u32 = 50;
|
||||
const AUDIT_PAGE_LIMIT: i64 = 10;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct EntriesQuery {
|
||||
@@ -140,6 +147,7 @@ struct EntriesQuery {
|
||||
/// URL query key is `type` (maps to DB column `entries.type`).
|
||||
#[serde(rename = "type")]
|
||||
entry_type: Option<String>,
|
||||
page: Option<u32>,
|
||||
}
|
||||
|
||||
// ── App state helpers ─────────────────────────────────────────────────────────
|
||||
@@ -168,14 +176,33 @@ async fn current_user_id(session: &Session) -> Option<Uuid> {
|
||||
}
|
||||
|
||||
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());
|
||||
let trust_proxy = std::env::var("TRUST_PROXY")
|
||||
.as_deref()
|
||||
.is_ok_and(|v| matches!(v, "1" | "true" | "yes"));
|
||||
request_client_ip_with_trust_proxy(headers, connect_info, trust_proxy)
|
||||
}
|
||||
|
||||
fn request_client_ip_with_trust_proxy(
|
||||
headers: &HeaderMap,
|
||||
connect_info: ConnectInfo<SocketAddr>,
|
||||
trust_proxy: bool,
|
||||
) -> Option<String> {
|
||||
if trust_proxy {
|
||||
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 let Ok(ip) = value.parse::<IpAddr>() {
|
||||
return Some(ip.to_string());
|
||||
}
|
||||
}
|
||||
if let Some(value) = headers.get("x-real-ip").and_then(|v| v.to_str().ok()) {
|
||||
let value = value.trim();
|
||||
if let Ok(ip) = value.parse::<IpAddr>() {
|
||||
return Some(ip.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,6 +218,15 @@ fn request_user_agent(headers: &HeaderMap) -> Option<String> {
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
fn paginate(page: u32, total_count: i64, page_size: u32) -> (u32, u32, u32) {
|
||||
let page_size = page_size.max(1);
|
||||
let safe_total_count = u32::try_from(total_count.max(0)).unwrap_or(u32::MAX);
|
||||
let total_pages = safe_total_count.div_ceil(page_size).max(1);
|
||||
let current_page = page.max(1).min(total_pages);
|
||||
let offset = (current_page - 1).saturating_mul(page_size);
|
||||
(current_page, total_pages, offset)
|
||||
}
|
||||
|
||||
// ── Routes ────────────────────────────────────────────────────────────────────
|
||||
|
||||
pub fn web_router() -> Router<AppState> {
|
||||
@@ -217,10 +253,6 @@ pub fn web_router() -> Router<AppState> {
|
||||
.route("/entries", get(entries_page))
|
||||
.route("/audit", get(audit_page))
|
||||
.route("/account/bind/google", get(account_bind_google))
|
||||
.route(
|
||||
"/account/bind/google/callback",
|
||||
get(account_bind_google_callback),
|
||||
)
|
||||
.route("/account/unbind/{provider}", post(account_unbind))
|
||||
.route("/api/key-salt", get(api_key_salt))
|
||||
.route("/api/key-setup", post(api_key_setup))
|
||||
@@ -596,7 +628,8 @@ async fn entries_page(
|
||||
.map(|s| s.trim())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| s.to_string());
|
||||
let params = SearchParams {
|
||||
let page = q.page.unwrap_or(1).max(1);
|
||||
let count_params = SearchParams {
|
||||
folder: folder_filter.as_deref(),
|
||||
entry_type: type_filter.as_deref(),
|
||||
name: None,
|
||||
@@ -609,7 +642,18 @@ async fn entries_page(
|
||||
user_id: Some(user_id),
|
||||
};
|
||||
|
||||
let rows = list_entries(&state.pool, params).await.map_err(|e| {
|
||||
let total_count = count_entries(&state.pool, &count_params)
|
||||
.await
|
||||
.inspect_err(|e| tracing::warn!(error = %e, "count_entries failed for web entries page"))
|
||||
.unwrap_or(0);
|
||||
let (current_page, total_pages, offset) = paginate(page, total_count, ENTRIES_PAGE_LIMIT);
|
||||
|
||||
let list_params = SearchParams {
|
||||
offset,
|
||||
..count_params
|
||||
};
|
||||
|
||||
let rows = list_entries(&state.pool, list_params).await.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to load entries list for web");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
@@ -681,7 +725,12 @@ async fn entries_page(
|
||||
type_options.sort_unstable();
|
||||
}
|
||||
|
||||
fn entries_href(folder: Option<&str>, entry_type: Option<&str>, name: Option<&str>) -> String {
|
||||
fn entries_href(
|
||||
folder: Option<&str>,
|
||||
entry_type: Option<&str>,
|
||||
name: Option<&str>,
|
||||
page: Option<u32>,
|
||||
) -> String {
|
||||
let mut pairs: Vec<String> = Vec::new();
|
||||
if let Some(f) = folder
|
||||
&& !f.is_empty()
|
||||
@@ -698,6 +747,9 @@ async fn entries_page(
|
||||
{
|
||||
pairs.push(format!("name={}", urlencoding::encode(n)));
|
||||
}
|
||||
if let Some(p) = page {
|
||||
pairs.push(format!("page={}", p));
|
||||
}
|
||||
if pairs.is_empty() {
|
||||
"/entries".to_string()
|
||||
} else {
|
||||
@@ -710,13 +762,23 @@ async fn entries_page(
|
||||
folder_tabs.push(FolderTabView {
|
||||
name: "全部".to_string(),
|
||||
count: all_count,
|
||||
href: entries_href(None, type_filter.as_deref(), name_filter.as_deref()),
|
||||
href: entries_href(
|
||||
None,
|
||||
type_filter.as_deref(),
|
||||
name_filter.as_deref(),
|
||||
Some(1),
|
||||
),
|
||||
active: folder_filter.is_none(),
|
||||
});
|
||||
for r in folder_rows {
|
||||
let name = r.folder;
|
||||
folder_tabs.push(FolderTabView {
|
||||
href: entries_href(Some(&name), type_filter.as_deref(), name_filter.as_deref()),
|
||||
href: entries_href(
|
||||
Some(&name),
|
||||
type_filter.as_deref(),
|
||||
name_filter.as_deref(),
|
||||
Some(1),
|
||||
),
|
||||
active: folder_filter.as_deref() == Some(name.as_str()),
|
||||
name,
|
||||
count: r.count,
|
||||
@@ -773,15 +835,24 @@ async fn entries_page(
|
||||
filter_folder: folder_filter.unwrap_or_default(),
|
||||
filter_name: name_filter.unwrap_or_default(),
|
||||
filter_type: type_filter.unwrap_or_default(),
|
||||
current_page,
|
||||
total_pages,
|
||||
total_count,
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
};
|
||||
|
||||
render_template(tmpl)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AuditQuery {
|
||||
page: Option<u32>,
|
||||
}
|
||||
|
||||
async fn audit_page(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
Query(aq): Query<AuditQuery>,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let Some(user_id) = current_user_id(&session).await else {
|
||||
return Ok(Redirect::to("/login").into_response());
|
||||
@@ -795,7 +866,17 @@ async fn audit_page(
|
||||
None => return Ok(Redirect::to("/login").into_response()),
|
||||
};
|
||||
|
||||
let rows = list_for_user(&state.pool, user_id, 100)
|
||||
let page = aq.page.unwrap_or(1).max(1);
|
||||
|
||||
let total_count = count_for_user(&state.pool, user_id).await.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to count audit log for user");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let (current_page, total_pages, offset) = paginate(page, total_count, AUDIT_PAGE_LIMIT as u32);
|
||||
let actual_offset = i64::from(offset);
|
||||
|
||||
let rows = list_for_user(&state.pool, user_id, AUDIT_PAGE_LIMIT, actual_offset)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, "failed to load audit log for user");
|
||||
@@ -816,6 +897,9 @@ async fn audit_page(
|
||||
user_name: user.name.clone(),
|
||||
user_email: user.email.clone().unwrap_or_default(),
|
||||
entries,
|
||||
current_page,
|
||||
total_pages,
|
||||
total_count,
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
};
|
||||
|
||||
@@ -840,14 +924,9 @@ async fn account_bind_google(
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let redirect_uri = format!("{}/account/bind/google/callback", state.base_url);
|
||||
let mut cfg = state
|
||||
.google_config
|
||||
.clone()
|
||||
.ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
cfg.redirect_uri = redirect_uri;
|
||||
let st = random_state();
|
||||
if let Err(e) = session.insert(SESSION_OAUTH_STATE, &st).await {
|
||||
let config = google_cfg(&state).ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let oauth_state = random_state();
|
||||
if let Err(e) = session.insert(SESSION_OAUTH_STATE, &oauth_state).await {
|
||||
tracing::error!(error = %e, "failed to insert oauth_state for account bind flow");
|
||||
if let Err(rm) = session.remove::<bool>(SESSION_OAUTH_BIND_MODE).await {
|
||||
tracing::warn!(error = %rm, "failed to roll back oauth_bind_mode after oauth_state insert failure");
|
||||
@@ -855,34 +934,8 @@ async fn account_bind_google(
|
||||
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> {
|
||||
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
|
||||
let url = google_auth_url(config, &oauth_state);
|
||||
Ok(Redirect::to(&url).into_response())
|
||||
}
|
||||
|
||||
async fn account_unbind(
|
||||
@@ -1673,6 +1726,34 @@ fn format_audit_target(folder: &str, entry_type: &str, name: &str) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn request_client_ip_ignores_forwarded_headers_without_trusted_proxy() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("x-forwarded-for", "203.0.113.10".parse().unwrap());
|
||||
|
||||
let ip = request_client_ip_with_trust_proxy(
|
||||
&headers,
|
||||
ConnectInfo(SocketAddr::from(([127, 0, 0, 1], 9315))),
|
||||
false,
|
||||
);
|
||||
|
||||
assert_eq!(ip.as_deref(), Some("127.0.0.1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_client_ip_uses_valid_forwarded_header_with_trusted_proxy() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("x-forwarded-for", "203.0.113.10, 10.0.0.1".parse().unwrap());
|
||||
|
||||
let ip = request_client_ip_with_trust_proxy(
|
||||
&headers,
|
||||
ConnectInfo(SocketAddr::from(([127, 0, 0, 1], 9315))),
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(ip.as_deref(), Some("203.0.113.10"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_ui_lang_prefers_zh_cn_over_en_fallback() {
|
||||
let mut headers = HeaderMap::new();
|
||||
@@ -1691,4 +1772,29 @@ mod tests {
|
||||
|
||||
assert!(matches!(request_ui_lang(&headers), UiLang::ZhTw));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paginate_clamps_page_before_computing_offset() {
|
||||
let (current_page, total_pages, offset) = paginate(100, 12, 10);
|
||||
|
||||
assert_eq!(current_page, 2);
|
||||
assert_eq!(total_pages, 2);
|
||||
assert_eq!(offset, 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paginate_handles_large_page_without_overflow() {
|
||||
let (current_page, total_pages, offset) = paginate(u32::MAX, 1, ENTRIES_PAGE_LIMIT);
|
||||
|
||||
assert_eq!(current_page, 1);
|
||||
assert_eq!(total_pages, 1);
|
||||
assert_eq!(offset, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paginate_saturates_large_total_count() {
|
||||
let (_, total_pages, _) = paginate(1, i64::MAX, ENTRIES_PAGE_LIMIT);
|
||||
|
||||
assert_eq!(total_pages, u32::MAX.div_ceil(ENTRIES_PAGE_LIMIT));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,7 +50,25 @@
|
||||
.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: 20px; }
|
||||
.card-title-row {
|
||||
display: flex; align-items: center; flex-wrap: wrap; gap: 8px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.card-title { font-size: 20px; font-weight: 600; margin: 0; }
|
||||
.card-title-count {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 24px;
|
||||
padding: 0 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
background: var(--bg);
|
||||
color: var(--text-muted);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
}
|
||||
.empty { color: var(--text-muted); font-size: 14px; padding: 20px 0; }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th, td { text-align: left; vertical-align: top; padding: 12px 10px; border-top: 1px solid var(--border); }
|
||||
@@ -84,6 +102,24 @@
|
||||
}
|
||||
.detail { max-width: none; }
|
||||
}
|
||||
.pagination {
|
||||
display: flex; align-items: center; gap: 8px; margin-top: 20px;
|
||||
justify-content: center; padding: 12px 0;
|
||||
}
|
||||
.page-btn {
|
||||
padding: 6px 14px; border-radius: 6px; border: 1px solid var(--border);
|
||||
background: var(--surface); color: var(--text); text-decoration: none;
|
||||
font-size: 13px; cursor: pointer;
|
||||
}
|
||||
.page-btn:hover { background: var(--surface2); }
|
||||
.page-btn-disabled {
|
||||
padding: 6px 14px; border-radius: 6px; border: 1px solid var(--border);
|
||||
background: var(--surface); color: var(--text-muted); font-size: 13px;
|
||||
opacity: 0.5; cursor: not-allowed;
|
||||
}
|
||||
.page-info {
|
||||
color: var(--text-muted); font-size: 13px; font-family: 'JetBrains Mono', monospace;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -113,7 +149,10 @@
|
||||
|
||||
<main class="main">
|
||||
<section class="card">
|
||||
<div class="card-title" data-i18n="auditTitle">我的审计</div>
|
||||
<div class="card-title-row">
|
||||
<div class="card-title" data-i18n="auditTitle">我的审计</div>
|
||||
<span class="card-title-count">{{ total_count }}</span>
|
||||
</div>
|
||||
|
||||
{% if entries.is_empty() %}
|
||||
<div class="empty" data-i18n="emptyAudit">暂无审计记录。</div>
|
||||
@@ -138,6 +177,22 @@
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{% if total_count > 0 %}
|
||||
<div class="pagination">
|
||||
{% if current_page > 1 %}
|
||||
<a href="?page={{ current_page - 1 }}" class="page-btn" data-i18n="prevPage">上一页</a>
|
||||
{% else %}
|
||||
<span class="page-btn page-btn-disabled" data-i18n="prevPage">上一页</span>
|
||||
{% endif %}
|
||||
<span class="page-info">{{ current_page }} / {{ total_pages }}</span>
|
||||
{% if current_page < total_pages %}
|
||||
<a href="?page={{ current_page + 1 }}" class="page-btn" data-i18n="nextPage">下一页</a>
|
||||
{% else %}
|
||||
<span class="page-btn page-btn-disabled" data-i18n="nextPage">下一页</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</section>
|
||||
</main>
|
||||
@@ -147,9 +202,9 @@
|
||||
<script>
|
||||
(function () {
|
||||
I18N_PAGE = {
|
||||
'zh-CN': { pageTitle: 'Secrets — 审计', auditTitle: '我的审计', emptyAudit: '暂无审计记录。', colTime: '时间', colAction: '动作', colTarget: '目标', colDetail: '详情' },
|
||||
'zh-TW': { pageTitle: 'Secrets — 審計', auditTitle: '我的審計', emptyAudit: '暫無審計記錄。', colTime: '時間', colAction: '動作', colTarget: '目標', colDetail: '詳情' },
|
||||
en: { pageTitle: 'Secrets — Audit', auditTitle: 'My audit', emptyAudit: 'No audit records.', colTime: 'Time', colAction: 'Action', colTarget: 'Target', colDetail: 'Detail' }
|
||||
'zh-CN': { pageTitle: 'Secrets — 审计', auditTitle: '我的审计', emptyAudit: '暂无审计记录。', colTime: '时间', colAction: '动作', colTarget: '目标', colDetail: '详情', prevPage: '上一页', nextPage: '下一页' },
|
||||
'zh-TW': { pageTitle: 'Secrets — 審計', auditTitle: '我的審計', emptyAudit: '暫無審計記錄。', colTime: '時間', colAction: '動作', colTarget: '目標', colDetail: '詳情', prevPage: '上一頁', nextPage: '下一頁' },
|
||||
en: { pageTitle: 'Secrets — Audit', auditTitle: 'My audit', emptyAudit: 'No audit records.', colTime: 'Time', colAction: 'Action', colTarget: 'Target', colDetail: 'Detail', prevPage: 'Previous', nextPage: 'Next' }
|
||||
};
|
||||
|
||||
window.applyPageLang = function () {
|
||||
|
||||
@@ -350,6 +350,24 @@
|
||||
}
|
||||
.detail, .notes-scroll, .secret-list { max-width: none; }
|
||||
}
|
||||
.pagination {
|
||||
display: flex; align-items: center; gap: 8px; margin-top: 20px;
|
||||
justify-content: center; padding: 12px 0;
|
||||
}
|
||||
.page-btn {
|
||||
padding: 6px 14px; border-radius: 6px; border: 1px solid var(--border);
|
||||
background: var(--surface); color: var(--text); text-decoration: none;
|
||||
font-size: 13px; cursor: pointer;
|
||||
}
|
||||
.page-btn:hover { background: var(--surface2); }
|
||||
.page-btn-disabled {
|
||||
padding: 6px 14px; border-radius: 6px; border: 1px solid var(--border);
|
||||
background: var(--surface); color: var(--text-muted); font-size: 13px;
|
||||
opacity: 0.5; cursor: not-allowed;
|
||||
}
|
||||
.page-info {
|
||||
color: var(--text-muted); font-size: 13px; font-family: 'JetBrains Mono', monospace;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -456,6 +474,22 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{% if total_count > 0 %}
|
||||
<div class="pagination">
|
||||
{% if current_page > 1 %}
|
||||
<a href="?{% if !filter_folder.is_empty() %}folder={{ filter_folder | urlencode }}&{% endif %}{% if !filter_type.is_empty() %}type={{ filter_type | urlencode }}&{% endif %}{% if !filter_name.is_empty() %}name={{ filter_name | urlencode }}&{% endif %}page={{ current_page - 1 }}" class="page-btn" data-i18n="prevPage">上一页</a>
|
||||
{% else %}
|
||||
<span class="page-btn page-btn-disabled" data-i18n="prevPage">上一页</span>
|
||||
{% endif %}
|
||||
<span class="page-info">{{ current_page }} / {{ total_pages }}</span>
|
||||
{% if current_page < total_pages %}
|
||||
<a href="?{% if !filter_folder.is_empty() %}folder={{ filter_folder | urlencode }}&{% endif %}{% if !filter_type.is_empty() %}type={{ filter_type | urlencode }}&{% endif %}{% if !filter_name.is_empty() %}name={{ filter_name | urlencode }}&{% endif %}page={{ current_page + 1 }}" class="page-btn" data-i18n="nextPage">下一页</a>
|
||||
{% else %}
|
||||
<span class="page-btn page-btn-disabled" data-i18n="nextPage">下一页</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</section>
|
||||
</main>
|
||||
@@ -554,7 +588,9 @@ var SECRET_TYPE_OPTIONS = JSON.parse(document.getElementById('secret-type-option
|
||||
secretNameCheckError: '校验失败,请重试',
|
||||
secretNameFixBeforeSave: '请先修复密文名称校验问题后再保存',
|
||||
secretTypePlaceholder: '选择类型',
|
||||
secretTypeInvalid: '类型不能为空'
|
||||
secretTypeInvalid: '类型不能为空',
|
||||
prevPage: '上一页',
|
||||
nextPage: '下一页',
|
||||
},
|
||||
'zh-TW': {
|
||||
pageTitle: 'Secrets — 條目',
|
||||
@@ -610,7 +646,9 @@ var SECRET_TYPE_OPTIONS = JSON.parse(document.getElementById('secret-type-option
|
||||
secretNameCheckError: '校驗失敗,請重試',
|
||||
secretNameFixBeforeSave: '請先修復密文名稱校驗問題後再儲存',
|
||||
secretTypePlaceholder: '選擇類型',
|
||||
secretTypeInvalid: '類型不能為空'
|
||||
secretTypeInvalid: '類型不能為空',
|
||||
prevPage: '上一頁',
|
||||
nextPage: '下一頁',
|
||||
},
|
||||
en: {
|
||||
pageTitle: 'Secrets — Entries',
|
||||
@@ -666,7 +704,9 @@ var SECRET_TYPE_OPTIONS = JSON.parse(document.getElementById('secret-type-option
|
||||
secretNameCheckError: 'Validation failed, please retry',
|
||||
secretNameFixBeforeSave: 'Fix secret name validation errors before saving',
|
||||
secretTypePlaceholder: 'Select type',
|
||||
secretTypeInvalid: 'Type cannot be empty'
|
||||
secretTypeInvalid: 'Type cannot be empty',
|
||||
prevPage: 'Previous',
|
||||
nextPage: 'Next'
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -31,7 +31,23 @@ GOOGLE_CLIENT_SECRET=
|
||||
# ─── 日志(可选)──────────────────────────────────────────────────────
|
||||
# RUST_LOG=secrets_mcp=debug
|
||||
|
||||
# ─── 注意 ─────────────────────────────────────────────────────────────
|
||||
# SERVER_MASTER_KEY 已不再需要。
|
||||
# 新架构(E2EE)中,加密密钥由用户密码短语在客户端本地派生,服务端不持有原始密钥。
|
||||
# 仅在需要迁移旧版 wrapped_key 数据时临时启用。
|
||||
# ─── 数据库连接池(可选)──────────────────────────────────────────────
|
||||
# 最大连接数,默认 10
|
||||
# SECRETS_DATABASE_POOL_SIZE=10
|
||||
# 获取连接超时秒数,默认 5
|
||||
# SECRETS_DATABASE_ACQUIRE_TIMEOUT=5
|
||||
|
||||
# ─── 限流(可选)──────────────────────────────────────────────────────
|
||||
# 全局限流速率(req/s),默认 100
|
||||
# RATE_LIMIT_GLOBAL_PER_SECOND=100
|
||||
# 全局限流突发量,默认 200
|
||||
# RATE_LIMIT_GLOBAL_BURST=200
|
||||
# 单 IP 限流速率(req/s),默认 20
|
||||
# RATE_LIMIT_IP_PER_SECOND=20
|
||||
# 单 IP 限流突发量,默认 40
|
||||
# RATE_LIMIT_IP_BURST=40
|
||||
|
||||
# ─── 代理信任(可选)─────────────────────────────────────────────────
|
||||
# 设为 1/true/yes 时从 X-Forwarded-For / X-Real-IP 提取客户端 IP
|
||||
# 仅在反代环境下启用,否则客户端可伪造 IP 绕过限流
|
||||
# TRUST_PROXY=1
|
||||
|
||||
@@ -11,7 +11,7 @@ tag="secrets-mcp-${version}"
|
||||
echo "==> 当前 secrets-mcp 版本: ${version}"
|
||||
echo "==> 检查是否已存在 tag: ${tag}"
|
||||
|
||||
if git rev-parse "refs/tags/${tag}" >/dev/null 2>&1; then
|
||||
if jj log --no-graph --revisions "tag(${tag})" --limit 1 >/dev/null 2>&1; then
|
||||
echo "提示: 已存在 tag ${tag},将按重复构建处理,不阻断检查。"
|
||||
echo "如需创建新的发布版本,请先 bump crates/secrets-mcp/Cargo.toml 中的 version。"
|
||||
else
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
#!/bin/bash
|
||||
# 同步测试环境数据到生产环境
|
||||
# 用法: ./scripts/sync-test-to-prod.sh
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# PostgreSQL 客户端工具路径 (Homebrew libpq)
|
||||
export PATH="/opt/homebrew/opt/libpq/bin:$PATH"
|
||||
|
||||
# SSL 配置
|
||||
export PGSSLMODE=verify-full
|
||||
export PGSSLROOTCERT=/etc/ssl/cert.pem
|
||||
|
||||
# 测试环境
|
||||
TEST_DB="postgres://postgres:Voson_2026_Pg18!@db.refining.ltd:5432/secrets-nn-test"
|
||||
|
||||
# 生产环境
|
||||
PROD_DB="postgres://postgres:Voson_2026_Pg18!@db.refining.ltd:5432/secrets-nn-prod"
|
||||
|
||||
echo "========================================="
|
||||
echo " 测试环境 -> 生产环境 数据同步"
|
||||
echo "========================================="
|
||||
echo ""
|
||||
|
||||
# 确认操作
|
||||
read -p "⚠️ 此操作将覆盖生产环境数据,确认继续? (yes/no): " confirm
|
||||
if [ "$confirm" != "yes" ]; then
|
||||
echo "已取消"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "步骤 1/4: 导出测试环境数据..."
|
||||
TEMP_DIR=$(mktemp -d)
|
||||
trap "rm -rf $TEMP_DIR" EXIT
|
||||
|
||||
# 导出测试环境数据(不含审计日志和历史记录)
|
||||
pg_dump "$TEST_DB" \
|
||||
--table=entries \
|
||||
--table=secrets \
|
||||
--table=entry_secrets \
|
||||
--table=users \
|
||||
--table=oauth_accounts \
|
||||
--data-only \
|
||||
--column-inserts \
|
||||
--no-owner \
|
||||
--no-privileges \
|
||||
> "$TEMP_DIR/test_data.sql"
|
||||
|
||||
echo "✓ 测试数据已导出到临时文件"
|
||||
echo " 文件大小: $(du -h "$TEMP_DIR/test_data.sql" | cut -f1)"
|
||||
|
||||
echo ""
|
||||
echo "步骤 2/4: 备份当前生产数据..."
|
||||
pg_dump "$PROD_DB" \
|
||||
--table=entries \
|
||||
--table=secrets \
|
||||
--table=entry_secrets \
|
||||
--table=users \
|
||||
--table=oauth_accounts \
|
||||
--data-only \
|
||||
--column-inserts \
|
||||
--no-owner \
|
||||
--no-privileges \
|
||||
> "$TEMP_DIR/prod_backup_$(date +%Y%m%d_%H%M%S).sql"
|
||||
|
||||
echo "✓ 生产数据已备份"
|
||||
|
||||
echo ""
|
||||
echo "步骤 3/4: 清空生产环境目标表..."
|
||||
psql "$PROD_DB" <<'SQL'
|
||||
TRUNCATE TABLE entry_secrets CASCADE;
|
||||
TRUNCATE TABLE secrets CASCADE;
|
||||
TRUNCATE TABLE entries CASCADE;
|
||||
SQL
|
||||
|
||||
echo "✓ 生产环境目标表已清空"
|
||||
|
||||
echo ""
|
||||
echo "步骤 4/4: 导入测试数据到生产环境..."
|
||||
psql "$PROD_DB" -f "$TEMP_DIR/test_data.sql" 2>&1 | tail -20
|
||||
|
||||
echo ""
|
||||
echo "验证数据..."
|
||||
echo "生产环境数据统计:"
|
||||
psql "$PROD_DB" -c "SELECT 'users' as table_name, count(*) FROM users UNION ALL SELECT 'entries', count(*) FROM entries UNION ALL SELECT 'secrets', count(*) FROM secrets UNION ALL SELECT 'entry_secrets', count(*) FROM entry_secrets UNION ALL SELECT 'oauth_accounts', count(*) FROM oauth_accounts ORDER BY table_name;"
|
||||
|
||||
echo ""
|
||||
echo "========================================="
|
||||
echo " ✓ 数据同步完成!"
|
||||
echo "========================================="
|
||||
echo ""
|
||||
echo "提示:"
|
||||
echo " - 生产数据备份已保存在临时目录"
|
||||
echo " - 临时文件将在脚本退出后自动删除"
|
||||
Reference in New Issue
Block a user