Compare commits
5 Commits
secrets-mc
...
secrets-mc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53d53ff96a | ||
|
|
cab234cfcb | ||
|
|
e0fee639c1 | ||
|
|
7c53bfb782 | ||
|
|
63cb3a8216 |
@@ -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",
|
||||
|
||||
2
Cargo.lock
generated
2
Cargo.lock
generated
@@ -2066,7 +2066,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "secrets-mcp"
|
||||
version = "0.5.5"
|
||||
version = "0.5.8"
|
||||
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
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::str::FromStr;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use serde_json::Value;
|
||||
use serde_json::{Map, Value};
|
||||
use sqlx::PgPool;
|
||||
use sqlx::postgres::{PgConnectOptions, PgPoolOptions, PgSslMode};
|
||||
|
||||
@@ -562,4 +562,75 @@ pub async fn snapshot_secret_history(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub const ENTRY_HISTORY_SECRETS_KEY: &str = "__secrets_snapshot_v1";
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct EntrySecretSnapshot {
|
||||
pub name: String,
|
||||
#[serde(rename = "type")]
|
||||
pub secret_type: String,
|
||||
pub encrypted_hex: String,
|
||||
}
|
||||
|
||||
pub async fn metadata_with_secret_snapshot(
|
||||
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
entry_id: uuid::Uuid,
|
||||
metadata: &Value,
|
||||
) -> Result<Value> {
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct Row {
|
||||
name: String,
|
||||
#[sqlx(rename = "type")]
|
||||
secret_type: String,
|
||||
encrypted: Vec<u8>,
|
||||
}
|
||||
|
||||
let rows: Vec<Row> = sqlx::query_as(
|
||||
"SELECT s.name, s.type, s.encrypted \
|
||||
FROM entry_secrets es \
|
||||
JOIN secrets s ON s.id = es.secret_id \
|
||||
WHERE es.entry_id = $1 \
|
||||
ORDER BY s.name ASC",
|
||||
)
|
||||
.bind(entry_id)
|
||||
.fetch_all(&mut **tx)
|
||||
.await?;
|
||||
|
||||
let snapshots: Vec<EntrySecretSnapshot> = rows
|
||||
.into_iter()
|
||||
.map(|r| EntrySecretSnapshot {
|
||||
name: r.name,
|
||||
secret_type: r.secret_type,
|
||||
encrypted_hex: ::hex::encode(r.encrypted),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut merged = match metadata.clone() {
|
||||
Value::Object(obj) => obj,
|
||||
_ => Map::new(),
|
||||
};
|
||||
merged.insert(
|
||||
ENTRY_HISTORY_SECRETS_KEY.to_string(),
|
||||
serde_json::to_value(snapshots)?,
|
||||
);
|
||||
Ok(Value::Object(merged))
|
||||
}
|
||||
|
||||
pub fn strip_secret_snapshot_from_metadata(metadata: &Value) -> Value {
|
||||
let mut m = match metadata.clone() {
|
||||
Value::Object(obj) => obj,
|
||||
_ => return metadata.clone(),
|
||||
};
|
||||
m.remove(ENTRY_HISTORY_SECRETS_KEY);
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
pub fn entry_secret_snapshot_from_metadata(metadata: &Value) -> Option<Vec<EntrySecretSnapshot>> {
|
||||
let Value::Object(map) = metadata else {
|
||||
return None;
|
||||
};
|
||||
let raw = map.get(ENTRY_HISTORY_SECRETS_KEY)?;
|
||||
serde_json::from_value(raw.clone()).ok()
|
||||
}
|
||||
|
||||
// ── DB helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -223,8 +223,16 @@ pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) ->
|
||||
.await?
|
||||
};
|
||||
|
||||
if let Some(ref ex) = existing
|
||||
&& let Err(e) = db::snapshot_entry_history(
|
||||
if let Some(ref ex) = existing {
|
||||
let history_metadata =
|
||||
match db::metadata_with_secret_snapshot(&mut tx, ex.id, &ex.metadata).await {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "failed to build secret snapshot for entry history");
|
||||
ex.metadata.clone()
|
||||
}
|
||||
};
|
||||
if let Err(e) = db::snapshot_entry_history(
|
||||
&mut tx,
|
||||
db::EntrySnapshotParams {
|
||||
entry_id: ex.id,
|
||||
@@ -235,12 +243,13 @@ pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) ->
|
||||
version: ex.version,
|
||||
action: "add",
|
||||
tags: &ex.tags,
|
||||
metadata: &ex.metadata,
|
||||
metadata: &history_metadata,
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to snapshot entry history before upsert");
|
||||
{
|
||||
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),
|
||||
@@ -303,26 +312,6 @@ pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) ->
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
|
||||
if existing.is_none()
|
||||
&& let Err(e) = db::snapshot_entry_history(
|
||||
&mut tx,
|
||||
db::EntrySnapshotParams {
|
||||
entry_id,
|
||||
user_id: params.user_id,
|
||||
folder: params.folder,
|
||||
entry_type,
|
||||
name: params.name,
|
||||
version: current_entry_version,
|
||||
action: "create",
|
||||
tags: params.tags,
|
||||
metadata: &metadata,
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to snapshot entry history on create");
|
||||
}
|
||||
|
||||
if existing.is_some() {
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct ExistingField {
|
||||
@@ -432,6 +421,35 @@ pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) ->
|
||||
}
|
||||
}
|
||||
|
||||
if existing.is_none() {
|
||||
let history_metadata =
|
||||
match db::metadata_with_secret_snapshot(&mut tx, entry_id, &metadata).await {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "failed to build secret snapshot for entry history");
|
||||
metadata.clone()
|
||||
}
|
||||
};
|
||||
if let Err(e) = db::snapshot_entry_history(
|
||||
&mut tx,
|
||||
db::EntrySnapshotParams {
|
||||
entry_id,
|
||||
user_id: params.user_id,
|
||||
folder: params.folder,
|
||||
entry_type,
|
||||
name: params.name,
|
||||
version: current_entry_version,
|
||||
action: "create",
|
||||
tags: params.tags,
|
||||
metadata: &history_metadata,
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to snapshot entry history on create");
|
||||
}
|
||||
}
|
||||
|
||||
crate::audit::log_tx(
|
||||
&mut tx,
|
||||
params.user_id,
|
||||
|
||||
@@ -441,6 +441,15 @@ async fn snapshot_and_delete(
|
||||
row: &EntryRow,
|
||||
user_id: Option<Uuid>,
|
||||
) -> Result<()> {
|
||||
let history_metadata = match db::metadata_with_secret_snapshot(tx, row.id, &row.metadata).await
|
||||
{
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "failed to build secret snapshot for entry history");
|
||||
row.metadata.clone()
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = db::snapshot_entry_history(
|
||||
tx,
|
||||
db::EntrySnapshotParams {
|
||||
@@ -452,7 +461,7 @@ async fn snapshot_and_delete(
|
||||
version: row.version,
|
||||
action: "delete",
|
||||
tags: &row.tags,
|
||||
metadata: &row.metadata,
|
||||
metadata: &history_metadata,
|
||||
},
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -31,8 +31,11 @@ pub async fn run(
|
||||
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",
|
||||
"SELECT DISTINCT ON (version) version, action, created_at \
|
||||
FROM entries_history \
|
||||
WHERE entry_id = $1 \
|
||||
ORDER BY version DESC, id DESC \
|
||||
LIMIT $2",
|
||||
)
|
||||
.bind(entry.id)
|
||||
.bind(limit as i64)
|
||||
|
||||
@@ -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!(
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use anyhow::Result;
|
||||
use serde_json::Value;
|
||||
use sqlx::PgPool;
|
||||
@@ -122,7 +124,7 @@ pub async fn run(
|
||||
sqlx::query_as(
|
||||
"SELECT folder, type, version, action, tags, metadata \
|
||||
FROM entries_history \
|
||||
WHERE entry_id = $1 AND version = $2 ORDER BY id DESC LIMIT 1",
|
||||
WHERE entry_id = $1 AND version = $2 ORDER BY id ASC LIMIT 1",
|
||||
)
|
||||
.bind(entry_id)
|
||||
.bind(ver)
|
||||
@@ -149,6 +151,9 @@ pub async fn run(
|
||||
)
|
||||
})?;
|
||||
|
||||
let snap_secret_snapshot = db::entry_secret_snapshot_from_metadata(&snap.metadata);
|
||||
let snap_metadata = db::strip_secret_snapshot_from_metadata(&snap.metadata);
|
||||
|
||||
let _ = master_key;
|
||||
|
||||
let mut tx = pool.begin().await?;
|
||||
@@ -176,6 +181,15 @@ pub async fn run(
|
||||
.await?;
|
||||
|
||||
let live_entry_id = if let Some(ref lr) = live {
|
||||
let history_metadata =
|
||||
match db::metadata_with_secret_snapshot(&mut tx, lr.id, &lr.metadata).await {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "failed to build secret snapshot for entry history");
|
||||
lr.metadata.clone()
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = db::snapshot_entry_history(
|
||||
&mut tx,
|
||||
db::EntrySnapshotParams {
|
||||
@@ -187,7 +201,7 @@ pub async fn run(
|
||||
version: lr.version,
|
||||
action: "rollback",
|
||||
tags: &lr.tags,
|
||||
metadata: &lr.metadata,
|
||||
metadata: &history_metadata,
|
||||
},
|
||||
)
|
||||
.await
|
||||
@@ -228,11 +242,13 @@ 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(&snap_metadata)
|
||||
.bind(lr.id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
@@ -250,7 +266,7 @@ pub async fn run(
|
||||
.bind(&snap.entry_type)
|
||||
.bind(name)
|
||||
.bind(&snap.tags)
|
||||
.bind(&snap.metadata)
|
||||
.bind(&snap_metadata)
|
||||
.bind(snap.version)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?
|
||||
@@ -264,16 +280,16 @@ pub async fn run(
|
||||
.bind(&snap.entry_type)
|
||||
.bind(name)
|
||||
.bind(&snap.tags)
|
||||
.bind(&snap.metadata)
|
||||
.bind(&snap_metadata)
|
||||
.bind(snap.version)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?
|
||||
}
|
||||
};
|
||||
|
||||
// In N:N mode, rollback restores entry metadata/tags only.
|
||||
// Secret snapshots are kept for audit but secret linkage/content is not rewritten here.
|
||||
let _ = live_entry_id;
|
||||
if let Some(secret_snapshot) = snap_secret_snapshot {
|
||||
restore_entry_secrets(&mut tx, live_entry_id, user_id, &secret_snapshot).await?;
|
||||
}
|
||||
|
||||
crate::audit::log_tx(
|
||||
&mut tx,
|
||||
@@ -298,3 +314,144 @@ pub async fn run(
|
||||
restored_version: snap.version,
|
||||
})
|
||||
}
|
||||
|
||||
async fn restore_entry_secrets(
|
||||
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
entry_id: Uuid,
|
||||
user_id: Option<Uuid>,
|
||||
snapshot: &[db::EntrySecretSnapshot],
|
||||
) -> Result<()> {
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct LinkedSecret {
|
||||
id: Uuid,
|
||||
name: String,
|
||||
encrypted: Vec<u8>,
|
||||
}
|
||||
|
||||
let linked: Vec<LinkedSecret> = sqlx::query_as(
|
||||
"SELECT s.id, s.name, s.encrypted \
|
||||
FROM entry_secrets es \
|
||||
JOIN secrets s ON s.id = es.secret_id \
|
||||
WHERE es.entry_id = $1",
|
||||
)
|
||||
.bind(entry_id)
|
||||
.fetch_all(&mut **tx)
|
||||
.await?;
|
||||
|
||||
let target_names: HashSet<&str> = snapshot.iter().map(|s| s.name.as_str()).collect();
|
||||
|
||||
for s in &linked {
|
||||
if target_names.contains(s.name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
if let Err(e) = db::snapshot_secret_history(
|
||||
tx,
|
||||
db::SecretSnapshotParams {
|
||||
secret_id: s.id,
|
||||
name: &s.name,
|
||||
encrypted: &s.encrypted,
|
||||
action: "rollback",
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to snapshot secret before rollback unlink");
|
||||
}
|
||||
|
||||
sqlx::query("DELETE FROM entry_secrets WHERE entry_id = $1 AND secret_id = $2")
|
||||
.bind(entry_id)
|
||||
.bind(s.id)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
|
||||
sqlx::query(
|
||||
"DELETE FROM secrets s \
|
||||
WHERE s.id = $1 \
|
||||
AND NOT EXISTS (SELECT 1 FROM entry_secrets es WHERE es.secret_id = s.id)",
|
||||
)
|
||||
.bind(s.id)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
}
|
||||
|
||||
for snap in snapshot {
|
||||
let encrypted = ::hex::decode(&snap.encrypted_hex).map_err(|e| {
|
||||
anyhow::anyhow!("invalid secret snapshot data for '{}': {}", snap.name, e)
|
||||
})?;
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct ExistingSecret {
|
||||
id: Uuid,
|
||||
encrypted: Vec<u8>,
|
||||
}
|
||||
|
||||
let existing: Option<ExistingSecret> = if let Some(uid) = user_id {
|
||||
sqlx::query_as("SELECT id, encrypted FROM secrets WHERE user_id = $1 AND name = $2")
|
||||
.bind(uid)
|
||||
.bind(&snap.name)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_as("SELECT id, encrypted FROM secrets WHERE user_id IS NULL AND name = $1")
|
||||
.bind(&snap.name)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?
|
||||
};
|
||||
|
||||
let secret_id = if let Some(ex) = existing {
|
||||
if ex.encrypted != encrypted
|
||||
&& let Err(e) = db::snapshot_secret_history(
|
||||
tx,
|
||||
db::SecretSnapshotParams {
|
||||
secret_id: ex.id,
|
||||
name: &snap.name,
|
||||
encrypted: &ex.encrypted,
|
||||
action: "rollback",
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to snapshot secret before rollback restore");
|
||||
}
|
||||
sqlx::query(
|
||||
"UPDATE secrets SET type = $1, encrypted = $2, version = version + 1, updated_at = NOW() \
|
||||
WHERE id = $3",
|
||||
)
|
||||
.bind(&snap.secret_type)
|
||||
.bind(&encrypted)
|
||||
.bind(ex.id)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
ex.id
|
||||
} else if let Some(uid) = user_id {
|
||||
sqlx::query_scalar(
|
||||
"INSERT INTO secrets (user_id, name, type, encrypted) VALUES ($1, $2, $3, $4) RETURNING id",
|
||||
)
|
||||
.bind(uid)
|
||||
.bind(&snap.name)
|
||||
.bind(&snap.secret_type)
|
||||
.bind(&encrypted)
|
||||
.fetch_one(&mut **tx)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_scalar(
|
||||
"INSERT INTO secrets (user_id, name, type, encrypted) VALUES (NULL, $1, $2, $3) RETURNING id",
|
||||
)
|
||||
.bind(&snap.name)
|
||||
.bind(&snap.secret_type)
|
||||
.bind(&encrypted)
|
||||
.fetch_one(&mut **tx)
|
||||
.await?
|
||||
};
|
||||
|
||||
sqlx::query(
|
||||
"INSERT INTO entry_secrets (entry_id, secret_id) VALUES ($1, $2) ON CONFLICT DO NOTHING",
|
||||
)
|
||||
.bind(entry_id)
|
||||
.bind(secret_id)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -112,6 +112,15 @@ pub async fn run(
|
||||
}
|
||||
};
|
||||
|
||||
let history_metadata =
|
||||
match db::metadata_with_secret_snapshot(&mut tx, row.id, &row.metadata).await {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "failed to build secret snapshot for entry history");
|
||||
row.metadata.clone()
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = db::snapshot_entry_history(
|
||||
&mut tx,
|
||||
db::EntrySnapshotParams {
|
||||
@@ -123,7 +132,7 @@ pub async fn run(
|
||||
version: row.version,
|
||||
action: "update",
|
||||
tags: &row.tags,
|
||||
metadata: &row.metadata,
|
||||
metadata: &history_metadata,
|
||||
},
|
||||
)
|
||||
.await
|
||||
@@ -481,6 +490,15 @@ pub async fn update_fields_by_id(
|
||||
}
|
||||
};
|
||||
|
||||
let history_metadata =
|
||||
match db::metadata_with_secret_snapshot(&mut tx, row.id, &row.metadata).await {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "failed to build secret snapshot for entry history");
|
||||
row.metadata.clone()
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = db::snapshot_entry_history(
|
||||
&mut tx,
|
||||
db::EntrySnapshotParams {
|
||||
@@ -492,7 +510,7 @@ pub async fn update_fields_by_id(
|
||||
version: row.version,
|
||||
action: "update",
|
||||
tags: &row.tags,
|
||||
metadata: &row.metadata,
|
||||
metadata: &history_metadata,
|
||||
},
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -76,6 +76,52 @@ pub async fn find_or_create_user(pool: &PgPool, profile: OAuthProfile) -> Result
|
||||
Ok((user, true))
|
||||
}
|
||||
|
||||
/// Re-encrypt all of a user's secrets from `old_key` to `new_key` and update the key metadata.
|
||||
///
|
||||
/// Runs entirely inside a single database transaction: if any secret fails to re-encrypt
|
||||
/// the whole operation is rolled back, leaving the database unchanged.
|
||||
pub async fn change_user_key(
|
||||
pool: &PgPool,
|
||||
user_id: Uuid,
|
||||
old_key: &[u8; 32],
|
||||
new_key: &[u8; 32],
|
||||
new_salt: &[u8],
|
||||
new_key_check: &[u8],
|
||||
new_key_params: &Value,
|
||||
) -> Result<()> {
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
let secrets: Vec<(uuid::Uuid, Vec<u8>)> =
|
||||
sqlx::query_as("SELECT id, encrypted FROM secrets WHERE user_id = $1 FOR UPDATE")
|
||||
.bind(user_id)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
|
||||
for (id, encrypted) in &secrets {
|
||||
let plaintext = crate::crypto::decrypt(old_key, encrypted)?;
|
||||
let new_encrypted = crate::crypto::encrypt(new_key, &plaintext)?;
|
||||
sqlx::query("UPDATE secrets SET encrypted = $1, updated_at = NOW() WHERE id = $2")
|
||||
.bind(&new_encrypted)
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE users SET key_salt = $1, key_check = $2, key_params = $3, updated_at = NOW() \
|
||||
WHERE id = $4",
|
||||
)
|
||||
.bind(new_salt)
|
||||
.bind(new_key_check)
|
||||
.bind(new_key_params)
|
||||
.bind(user_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Store the PBKDF2 salt, key_check, and params for a user's passphrase setup.
|
||||
pub async fn update_user_key_setup(
|
||||
pool: &PgPool,
|
||||
@@ -200,10 +246,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 +262,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.5"
|
||||
version = "0.5.8"
|
||||
edition.workspace = true
|
||||
|
||||
[[bin]]
|
||||
|
||||
@@ -1,25 +1,28 @@
|
||||
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},
|
||||
header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, USER_AGENT},
|
||||
},
|
||||
middleware::Next,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
|
||||
use crate::auth::AuthUser;
|
||||
|
||||
/// Axum middleware that logs structured info for every HTTP request.
|
||||
///
|
||||
/// All requests: method, path, status, latency_ms, client_ip, user_agent.
|
||||
/// POST /mcp requests: additionally parses JSON-RPC body for jsonrpc_method,
|
||||
/// tool_name, jsonrpc_id, mcp_session, batch_size.
|
||||
/// tool_name, jsonrpc_id, mcp_session, batch_size, tool_args (non-sensitive
|
||||
/// arguments only), plus masked auth_key / enc_key fingerprints and user_id
|
||||
/// for diagnosing header forwarding issues.
|
||||
///
|
||||
/// Sensitive headers (Authorization, X-Encryption-Key) and secret values
|
||||
/// are never logged.
|
||||
/// Sensitive headers (Authorization, X-Encryption-Key) are never logged in
|
||||
/// full — only short fingerprints are emitted.
|
||||
pub async fn request_logging_middleware(req: Request, next: Next) -> Response {
|
||||
let method = req.method().clone();
|
||||
let path = req.uri().path().to_string();
|
||||
@@ -33,6 +36,10 @@ pub async fn request_logging_middleware(req: Request, next: Next) -> Response {
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(|s| s.to_string());
|
||||
|
||||
// Capture header fingerprints before consuming the request.
|
||||
let auth_key = mask_bearer(req.headers());
|
||||
let enc_key = mask_enc_key(req.headers());
|
||||
|
||||
let is_mcp_post = path.starts_with("/mcp") && method == Method::POST;
|
||||
let is_json = header_str(req.headers(), CONTENT_TYPE)
|
||||
.map(|ct| ct.contains("application/json"))
|
||||
@@ -46,6 +53,11 @@ pub async fn request_logging_middleware(req: Request, next: Next) -> Response {
|
||||
let cap = content_len.unwrap_or(0);
|
||||
if cap <= 512 * 1024 {
|
||||
let (parts, body) = req.into_parts();
|
||||
// user_id is available after auth middleware has run (injected into extensions).
|
||||
let user_id = parts
|
||||
.extensions
|
||||
.get::<AuthUser>()
|
||||
.map(|a| a.user_id.to_string());
|
||||
match to_bytes(body, 512 * 1024).await {
|
||||
Ok(bytes) => {
|
||||
let rpc = parse_jsonrpc_meta(&bytes);
|
||||
@@ -62,6 +74,9 @@ pub async fn request_logging_middleware(req: Request, next: Next) -> Response {
|
||||
ua.as_deref(),
|
||||
content_len,
|
||||
mcp_session.as_deref(),
|
||||
auth_key.as_deref(),
|
||||
&enc_key,
|
||||
user_id.as_deref(),
|
||||
&rpc,
|
||||
);
|
||||
return resp;
|
||||
@@ -78,6 +93,9 @@ pub async fn request_logging_middleware(req: Request, next: Next) -> Response {
|
||||
ua = ua.as_deref(),
|
||||
content_length = content_len,
|
||||
mcp_session = mcp_session.as_deref(),
|
||||
auth_key = auth_key.as_deref(),
|
||||
enc_key = enc_key.as_str(),
|
||||
user_id = user_id.as_deref(),
|
||||
"mcp request",
|
||||
);
|
||||
return (
|
||||
@@ -160,6 +178,9 @@ fn log_mcp_request(
|
||||
ua: Option<&str>,
|
||||
content_length: Option<u64>,
|
||||
mcp_session: Option<&str>,
|
||||
auth_key: Option<&str>,
|
||||
enc_key: &str,
|
||||
user_id: Option<&str>,
|
||||
rpc: &JsonRpcMeta,
|
||||
) {
|
||||
tracing::info!(
|
||||
@@ -175,18 +196,94 @@ fn log_mcp_request(
|
||||
tool = rpc.tool_name.as_deref(),
|
||||
jsonrpc_id = rpc.request_id.as_deref(),
|
||||
batch_size = rpc.batch_size,
|
||||
tool_args = rpc.tool_args.as_deref(),
|
||||
auth_key,
|
||||
enc_key,
|
||||
user_id,
|
||||
"mcp request",
|
||||
);
|
||||
}
|
||||
|
||||
// ── Sensitive header masking ──────────────────────────────────────────────────
|
||||
|
||||
/// Mask a Bearer token: emit only the first 12 characters followed by `…`.
|
||||
/// Returns `None` if the Authorization header is absent or not a Bearer token.
|
||||
/// Example: `sk_90c88844e4e5…`
|
||||
fn mask_bearer(headers: &HeaderMap) -> Option<String> {
|
||||
let val = headers.get(AUTHORIZATION)?.to_str().ok()?;
|
||||
let token = val.strip_prefix("Bearer ")?.trim();
|
||||
if token.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if token.len() > 12 {
|
||||
Some(format!("{}…", &token[..12]))
|
||||
} else {
|
||||
Some(token.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Fingerprint the X-Encryption-Key header.
|
||||
///
|
||||
/// Emits first 4 chars, last 4 chars, and raw byte length, e.g. `146b…5516(64)`.
|
||||
/// Returns `"absent"` when the header is missing. Reveals enough to confirm
|
||||
/// which key arrived and whether it was truncated or padded, without revealing
|
||||
/// the full value.
|
||||
fn mask_enc_key(headers: &HeaderMap) -> String {
|
||||
match headers
|
||||
.get("x-encryption-key")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
{
|
||||
Some(val) => {
|
||||
let raw_len = val.len();
|
||||
let t = val.trim();
|
||||
let len = t.len();
|
||||
if len >= 8 {
|
||||
let prefix = &t[..4];
|
||||
let suffix = &t[len - 4..];
|
||||
if raw_len != len {
|
||||
// Trailing/leading whitespace detected — extra diagnostic.
|
||||
format!("{prefix}…{suffix}({len}, raw={raw_len})")
|
||||
} else {
|
||||
format!("{prefix}…{suffix}({len})")
|
||||
}
|
||||
} else {
|
||||
format!("…({len})")
|
||||
}
|
||||
}
|
||||
None => "absent".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
// ── JSON-RPC body parsing ─────────────────────────────────────────────────────
|
||||
|
||||
/// Safe (non-sensitive) argument keys that may be included verbatim in logs.
|
||||
/// Keys NOT in this list (e.g. `secrets`, `secrets_obj`, `meta_obj`,
|
||||
/// `encryption_key`) are silently dropped.
|
||||
const SAFE_ARG_KEYS: &[&str] = &[
|
||||
"id",
|
||||
"name",
|
||||
"name_query",
|
||||
"folder",
|
||||
"type",
|
||||
"entry_type",
|
||||
"field",
|
||||
"query",
|
||||
"tags",
|
||||
"limit",
|
||||
"offset",
|
||||
"format",
|
||||
"dry_run",
|
||||
"prefix",
|
||||
];
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct JsonRpcMeta {
|
||||
request_id: Option<String>,
|
||||
rpc_method: Option<String>,
|
||||
tool_name: Option<String>,
|
||||
batch_size: Option<usize>,
|
||||
/// Non-sensitive tool call arguments for diagnostic logging.
|
||||
tool_args: Option<String>,
|
||||
}
|
||||
|
||||
fn parse_jsonrpc_meta(bytes: &Bytes) -> JsonRpcMeta {
|
||||
@@ -216,12 +313,47 @@ fn parse_single(value: &serde_json::Value) -> JsonRpcMeta {
|
||||
.pointer("/params/name")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
let tool_args = extract_tool_args(value);
|
||||
|
||||
JsonRpcMeta {
|
||||
request_id,
|
||||
rpc_method,
|
||||
tool_name,
|
||||
batch_size: None,
|
||||
tool_args,
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract a compact summary of non-sensitive tool arguments for logging.
|
||||
/// Only keys listed in `SAFE_ARG_KEYS` are included.
|
||||
fn extract_tool_args(value: &serde_json::Value) -> Option<String> {
|
||||
let args = value.pointer("/params/arguments")?;
|
||||
let obj = args.as_object()?;
|
||||
let pairs: Vec<String> = obj
|
||||
.iter()
|
||||
.filter(|(k, v)| SAFE_ARG_KEYS.contains(&k.as_str()) && !v.is_null())
|
||||
.map(|(k, v)| format!("{}={}", k, summarize_value(v)))
|
||||
.collect();
|
||||
if pairs.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(pairs.join(" "))
|
||||
}
|
||||
}
|
||||
|
||||
/// Produce a short, log-safe representation of a JSON value.
|
||||
fn summarize_value(v: &serde_json::Value) -> String {
|
||||
match v {
|
||||
serde_json::Value::String(s) => {
|
||||
if s.len() > 64 {
|
||||
format!("\"{}…\"", &s[..64])
|
||||
} else {
|
||||
format!("\"{s}\"")
|
||||
}
|
||||
}
|
||||
serde_json::Value::Array(arr) => format!("[…{}]", arr.len()),
|
||||
serde_json::Value::Object(_) => "{…}".to_string(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,18 +377,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()
|
||||
}
|
||||
|
||||
@@ -187,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 ──────────────────────────────────────────────────────────
|
||||
|
||||
@@ -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
|
||||
@@ -274,6 +265,18 @@ impl SecretsService {
|
||||
rmcp::ErrorData::invalid_request("Invalid X-Encryption-Key header value", None)
|
||||
})?;
|
||||
let trimmed = hex_str.trim();
|
||||
// Debug-level fingerprint: helps diagnose header forwarding issues
|
||||
// (e.g. Cursor Chat MCP truncating or transforming the key value)
|
||||
// without revealing the full secret.
|
||||
tracing::debug!(
|
||||
raw_len = hex_str.len(),
|
||||
trimmed_len = trimmed.len(),
|
||||
key_prefix = trimmed.get(..8).unwrap_or(trimmed),
|
||||
key_suffix = trimmed
|
||||
.get(trimmed.len().saturating_sub(8)..)
|
||||
.unwrap_or(trimmed),
|
||||
"X-Encryption-Key received",
|
||||
);
|
||||
if trimmed.len() != 64 {
|
||||
tracing::warn!(
|
||||
got_len = trimmed.len(),
|
||||
@@ -298,7 +301,51 @@ impl SecretsService {
|
||||
.map_err(mcp_err_invalid_encryption_key_logged)
|
||||
}
|
||||
|
||||
/// Require both user_id and encryption key.
|
||||
/// Extract the encryption key, preferring an explicit argument value over
|
||||
/// the X-Encryption-Key HTTP header.
|
||||
///
|
||||
/// `arg_key` is the optional `encryption_key` field from the tool's input
|
||||
/// struct. When present, it is used directly and the header is ignored.
|
||||
/// This allows MCP clients that cannot reliably forward custom HTTP headers
|
||||
/// (e.g. Cursor Chat) to pass the key as a normal tool argument.
|
||||
fn extract_enc_key_or_arg(
|
||||
ctx: &RequestContext<RoleServer>,
|
||||
arg_key: Option<&str>,
|
||||
) -> Result<[u8; 32], rmcp::ErrorData> {
|
||||
if let Some(hex_str) = arg_key {
|
||||
let trimmed = hex_str.trim();
|
||||
tracing::debug!(
|
||||
source = "argument",
|
||||
raw_len = hex_str.len(),
|
||||
trimmed_len = trimmed.len(),
|
||||
key_prefix = trimmed.get(..8).unwrap_or(trimmed),
|
||||
key_suffix = trimmed
|
||||
.get(trimmed.len().saturating_sub(8)..)
|
||||
.unwrap_or(trimmed),
|
||||
"X-Encryption-Key received",
|
||||
);
|
||||
if trimmed.len() != 64 {
|
||||
return Err(rmcp::ErrorData::invalid_request(
|
||||
format!(
|
||||
"encryption_key must be exactly 64 hex characters (32-byte key), got {}.",
|
||||
trimmed.len()
|
||||
),
|
||||
None,
|
||||
));
|
||||
}
|
||||
if !trimmed.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return Err(rmcp::ErrorData::invalid_request(
|
||||
"encryption_key contains non-hexadecimal characters.",
|
||||
None,
|
||||
));
|
||||
}
|
||||
return secrets_core::crypto::extract_key_from_hex(trimmed)
|
||||
.map_err(mcp_err_invalid_encryption_key_logged);
|
||||
}
|
||||
Self::extract_enc_key(ctx)
|
||||
}
|
||||
|
||||
/// Require both user_id and encryption key (header only, no arg fallback).
|
||||
fn require_user_and_key(
|
||||
ctx: &RequestContext<RoleServer>,
|
||||
) -> Result<(Uuid, [u8; 32]), rmcp::ErrorData> {
|
||||
@@ -306,6 +353,17 @@ impl SecretsService {
|
||||
let key = Self::extract_enc_key(ctx)?;
|
||||
Ok((user_id, key))
|
||||
}
|
||||
|
||||
/// Require both user_id and encryption key, preferring an explicit argument
|
||||
/// value over the X-Encryption-Key header.
|
||||
fn require_user_and_key_or_arg(
|
||||
ctx: &RequestContext<RoleServer>,
|
||||
arg_key: Option<&str>,
|
||||
) -> Result<(Uuid, [u8; 32]), rmcp::ErrorData> {
|
||||
let user_id = Self::require_user_id(ctx)?;
|
||||
let key = Self::extract_enc_key_or_arg(ctx, arg_key)?;
|
||||
Ok((user_id, key))
|
||||
}
|
||||
}
|
||||
|
||||
// ── Tool parameter types ──────────────────────────────────────────────────────
|
||||
@@ -379,6 +437,10 @@ struct GetSecretInput {
|
||||
id: String,
|
||||
#[schemars(description = "Specific field to retrieve. If omitted, returns all fields.")]
|
||||
field: Option<String>,
|
||||
#[schemars(description = "Encryption key as a 64-char hex string. \
|
||||
If provided, takes priority over the X-Encryption-Key HTTP header. \
|
||||
Use this when the MCP client cannot reliably forward custom headers.")]
|
||||
encryption_key: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
@@ -425,6 +487,10 @@ struct AddInput {
|
||||
)]
|
||||
#[serde(default, deserialize_with = "deser::option_vec_string_from_string")]
|
||||
link_secret_names: Option<Vec<String>>,
|
||||
#[schemars(description = "Encryption key as a 64-char hex string. \
|
||||
If provided, takes priority over the X-Encryption-Key HTTP header. \
|
||||
Use this when the MCP client cannot reliably forward custom headers.")]
|
||||
encryption_key: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
@@ -486,6 +552,10 @@ struct UpdateInput {
|
||||
)]
|
||||
#[serde(default, deserialize_with = "deser::option_vec_string_from_string")]
|
||||
unlink_secret_names: Option<Vec<String>>,
|
||||
#[schemars(description = "Encryption key as a 64-char hex string. \
|
||||
If provided, takes priority over the X-Encryption-Key HTTP header. \
|
||||
Use this when the MCP client cannot reliably forward custom headers.")]
|
||||
encryption_key: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
@@ -558,6 +628,10 @@ struct ExportInput {
|
||||
query: Option<String>,
|
||||
#[schemars(description = "Export format: 'json' (default), 'toml', 'yaml'")]
|
||||
format: Option<String>,
|
||||
#[schemars(description = "Encryption key as a 64-char hex string. \
|
||||
If provided, takes priority over the X-Encryption-Key HTTP header. \
|
||||
Use this when the MCP client cannot reliably forward custom headers.")]
|
||||
encryption_key: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
@@ -581,6 +655,10 @@ struct EnvMapInput {
|
||||
Example: entry 'aliyun', field 'access_key_id' → ALIYUN_ACCESS_KEY_ID \
|
||||
(or PREFIX_ALIYUN_ACCESS_KEY_ID with prefix set).")]
|
||||
prefix: Option<String>,
|
||||
#[schemars(description = "Encryption key as a 64-char hex string. \
|
||||
If provided, takes priority over the X-Encryption-Key HTTP header. \
|
||||
Use this when the MCP client cannot reliably forward custom headers.")]
|
||||
encryption_key: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
@@ -885,7 +963,8 @@ impl SecretsService {
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, rmcp::ErrorData> {
|
||||
let t = Instant::now();
|
||||
let (user_id, user_key) = Self::require_user_and_key(&ctx)?;
|
||||
let (user_id, user_key) =
|
||||
Self::require_user_and_key_or_arg(&ctx, input.encryption_key.as_deref())?;
|
||||
let entry_id = parse_uuid(&input.id)?;
|
||||
tracing::info!(
|
||||
tool = "secrets_get",
|
||||
@@ -939,7 +1018,8 @@ impl SecretsService {
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, rmcp::ErrorData> {
|
||||
let t = Instant::now();
|
||||
let (user_id, user_key) = Self::require_user_and_key(&ctx)?;
|
||||
let (user_id, user_key) =
|
||||
Self::require_user_and_key_or_arg(&ctx, input.encryption_key.as_deref())?;
|
||||
tracing::info!(
|
||||
tool = "secrets_add",
|
||||
?user_id,
|
||||
@@ -1033,7 +1113,8 @@ impl SecretsService {
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, rmcp::ErrorData> {
|
||||
let t = Instant::now();
|
||||
let (user_id, user_key) = Self::require_user_and_key(&ctx)?;
|
||||
let (user_id, user_key) =
|
||||
Self::require_user_and_key_or_arg(&ctx, input.encryption_key.as_deref())?;
|
||||
tracing::info!(
|
||||
tool = "secrets_update",
|
||||
?user_id,
|
||||
@@ -1142,7 +1223,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()
|
||||
@@ -1172,9 +1253,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())
|
||||
@@ -1187,11 +1268,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",
|
||||
@@ -1218,7 +1299,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,
|
||||
@@ -1230,9 +1311,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())
|
||||
@@ -1243,10 +1324,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",
|
||||
@@ -1327,7 +1408,8 @@ impl SecretsService {
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, rmcp::ErrorData> {
|
||||
let t = Instant::now();
|
||||
let (user_id, user_key) = Self::require_user_and_key(&ctx)?;
|
||||
let (user_id, user_key) =
|
||||
Self::require_user_and_key_or_arg(&ctx, input.encryption_key.as_deref())?;
|
||||
let tags = input.tags.unwrap_or_default();
|
||||
let format = input.format.as_deref().unwrap_or("json");
|
||||
tracing::info!(
|
||||
@@ -1396,7 +1478,8 @@ impl SecretsService {
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, rmcp::ErrorData> {
|
||||
let t = Instant::now();
|
||||
let (user_id, user_key) = Self::require_user_and_key(&ctx)?;
|
||||
let (user_id, user_key) =
|
||||
Self::require_user_and_key_or_arg(&ctx, input.encryption_key.as_deref())?;
|
||||
let tags = input.tags.unwrap_or_default();
|
||||
let only_fields = input.only_fields.unwrap_or_default();
|
||||
tracing::info!(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use askama::Template;
|
||||
use chrono::SecondsFormat;
|
||||
use std::net::SocketAddr;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
|
||||
use axum::{
|
||||
Json, Router,
|
||||
@@ -25,7 +25,7 @@ use secrets_core::service::{
|
||||
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,
|
||||
OAuthProfile, bind_oauth_account, change_user_key, find_or_create_user, get_user_by_id,
|
||||
unbind_oauth_account, update_user_key_setup,
|
||||
},
|
||||
};
|
||||
@@ -176,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());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -234,13 +253,10 @@ 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))
|
||||
.route("/api/key-change", post(api_key_change))
|
||||
.route("/api/apikey", get(api_apikey_get))
|
||||
.route("/api/apikey/regenerate", post(api_apikey_regenerate))
|
||||
.route(
|
||||
@@ -909,14 +925,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");
|
||||
@@ -924,34 +935,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(
|
||||
@@ -1056,6 +1041,20 @@ async fn api_key_setup(
|
||||
.await
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
// Guard: if a passphrase is already configured, reject and direct to /api/key-change
|
||||
let user = get_user_by_id(&state.pool, user_id)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, %user_id, "failed to load user for key-setup guard");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
if user.key_salt.is_some() {
|
||||
tracing::warn!(%user_id, "key-setup called but passphrase already configured; use /api/key-change");
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
|
||||
let salt = hex::decode_hex(&body.salt).map_err(|e| {
|
||||
tracing::warn!(error = %e, "invalid hex in key-setup salt");
|
||||
StatusCode::BAD_REQUEST
|
||||
@@ -1080,6 +1079,103 @@ async fn api_key_setup(
|
||||
Ok(Json(KeySetupResponse { ok: true }))
|
||||
}
|
||||
|
||||
// ── Change passphrase (re-encrypts all secrets) ───────────────────────────────
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct KeyChangeRequest {
|
||||
/// Old derived key as 64-char hex — used to decrypt existing secrets
|
||||
old_key: String,
|
||||
/// New derived key as 64-char hex — used to re-encrypt secrets
|
||||
new_key: String,
|
||||
/// New 32-byte hex salt
|
||||
salt: String,
|
||||
/// New key_check: AES-256-GCM of KEY_CHECK_PLAINTEXT with the new key (hex)
|
||||
key_check: String,
|
||||
/// New key derivation parameters
|
||||
params: serde_json::Value,
|
||||
}
|
||||
|
||||
async fn api_key_change(
|
||||
State(state): State<AppState>,
|
||||
session: Session,
|
||||
Json(body): Json<KeyChangeRequest>,
|
||||
) -> Result<Json<KeySetupResponse>, StatusCode> {
|
||||
let user_id = current_user_id(&session)
|
||||
.await
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
let user = get_user_by_id(&state.pool, user_id)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, %user_id, "failed to load user for key-change");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
// Must have an existing passphrase to change
|
||||
let existing_key_check = user.key_check.ok_or_else(|| {
|
||||
tracing::warn!(%user_id, "key-change called but no passphrase configured; use /api/key-setup");
|
||||
StatusCode::BAD_REQUEST
|
||||
})?;
|
||||
|
||||
// Validate and decode old key
|
||||
let old_key_bytes = secrets_core::crypto::extract_key_from_hex(&body.old_key).map_err(|e| {
|
||||
tracing::warn!(error = %e, "invalid old_key hex in key-change");
|
||||
StatusCode::BAD_REQUEST
|
||||
})?;
|
||||
|
||||
// Verify old_key against the stored key_check
|
||||
let plaintext = secrets_core::crypto::decrypt(&old_key_bytes, &existing_key_check).map_err(|_| {
|
||||
tracing::warn!(%user_id, "key-change rejected: old_key does not match stored key_check");
|
||||
StatusCode::UNAUTHORIZED
|
||||
})?;
|
||||
if plaintext != b"secrets-mcp-key-check" {
|
||||
tracing::warn!(%user_id, "key-change rejected: decrypted key_check content mismatch");
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
// Validate and decode new key
|
||||
let new_key_bytes = secrets_core::crypto::extract_key_from_hex(&body.new_key).map_err(|e| {
|
||||
tracing::warn!(error = %e, "invalid new_key hex in key-change");
|
||||
StatusCode::BAD_REQUEST
|
||||
})?;
|
||||
|
||||
// Decode new salt and key_check
|
||||
let new_salt = hex::decode_hex(&body.salt).map_err(|e| {
|
||||
tracing::warn!(error = %e, "invalid hex in key-change salt");
|
||||
StatusCode::BAD_REQUEST
|
||||
})?;
|
||||
if new_salt.len() != 32 {
|
||||
tracing::warn!(
|
||||
salt_len = new_salt.len(),
|
||||
"key-change salt must be 32 bytes"
|
||||
);
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
let new_key_check = hex::decode_hex(&body.key_check).map_err(|e| {
|
||||
tracing::warn!(error = %e, "invalid hex in key-change key_check");
|
||||
StatusCode::BAD_REQUEST
|
||||
})?;
|
||||
|
||||
change_user_key(
|
||||
&state.pool,
|
||||
user_id,
|
||||
&old_key_bytes,
|
||||
&new_key_bytes,
|
||||
&new_salt,
|
||||
&new_key_check,
|
||||
&body.params,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(error = %e, %user_id, "failed to change user key");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
tracing::info!(%user_id, secrets_count = "(see service log)", "passphrase changed and secrets re-encrypted");
|
||||
Ok(Json(KeySetupResponse { ok: true }))
|
||||
}
|
||||
|
||||
// ── API Key management ────────────────────────────────────────────────────────
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -1742,6 +1838,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();
|
||||
|
||||
@@ -305,6 +305,17 @@
|
||||
<div class="modal-bd" id="change-modal">
|
||||
<div class="modal">
|
||||
<h3 data-i18n="changeTitle">更换密码</h3>
|
||||
<div class="field">
|
||||
<label data-i18n="labelCurrent">当前密码</label>
|
||||
<div class="pw-field">
|
||||
<input type="password" id="change-pass-old" data-i18n-ph="phCurrent" autocomplete="current-password">
|
||||
<button type="button" class="pw-toggle" data-target="change-pass-old" aria-pressed="false"
|
||||
onclick="togglePwVisibility(this)" aria-label="">
|
||||
<span class="pw-icon pw-icon-show" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span>
|
||||
<span class="pw-icon pw-icon-hide hidden" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg></span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label data-i18n="labelNew">新密码</label>
|
||||
<div class="pw-field">
|
||||
@@ -345,8 +356,10 @@ const T = {
|
||||
labelPassphrase: '加密密码',
|
||||
labelConfirm: '确认密码',
|
||||
labelNew: '新密码',
|
||||
labelCurrent: '当前密码',
|
||||
phPassphrase: '输入密码…',
|
||||
phConfirm: '再次输入…',
|
||||
phCurrent: '输入当前密码…',
|
||||
btnSetup: '设置并获取配置',
|
||||
btnUnlock: '解锁并获取配置',
|
||||
setupNote: '密码不会上传服务器。遗忘后数据将无法恢复。',
|
||||
@@ -354,6 +367,7 @@ const T = {
|
||||
errShort: '密码至少需要 8 个字符。',
|
||||
errMismatch: '两次输入不一致。',
|
||||
errWrong: '密码错误,请重试。',
|
||||
errWrongOld: '当前密码错误,请重试。',
|
||||
unlockedTitle: 'MCP 配置',
|
||||
tabMcp: 'Cursor、Claude Code、Codex、Gemini CLI',
|
||||
tabOpencode: 'OpenCode',
|
||||
@@ -379,8 +393,10 @@ const T = {
|
||||
labelPassphrase: '加密密碼',
|
||||
labelConfirm: '確認密碼',
|
||||
labelNew: '新密碼',
|
||||
labelCurrent: '目前密碼',
|
||||
phPassphrase: '輸入密碼…',
|
||||
phConfirm: '再次輸入…',
|
||||
phCurrent: '輸入目前密碼…',
|
||||
btnSetup: '設定並取得設定',
|
||||
btnUnlock: '解鎖並取得設定',
|
||||
setupNote: '密碼不會上傳伺服器。遺忘後資料將無法復原。',
|
||||
@@ -388,6 +404,7 @@ const T = {
|
||||
errShort: '密碼至少需要 8 個字元。',
|
||||
errMismatch: '兩次輸入不一致。',
|
||||
errWrong: '密碼錯誤,請重試。',
|
||||
errWrongOld: '目前密碼錯誤,請重試。',
|
||||
unlockedTitle: 'MCP 設定',
|
||||
tabMcp: 'Cursor、Claude Code、Codex、Gemini CLI',
|
||||
tabOpencode: 'OpenCode',
|
||||
@@ -413,8 +430,10 @@ const T = {
|
||||
labelPassphrase: 'Encryption password',
|
||||
labelConfirm: 'Confirm password',
|
||||
labelNew: 'New password',
|
||||
labelCurrent: 'Current password',
|
||||
phPassphrase: 'Enter password…',
|
||||
phConfirm: 'Repeat password…',
|
||||
phCurrent: 'Enter current password…',
|
||||
btnSetup: 'Set up & get config',
|
||||
btnUnlock: 'Unlock & get config',
|
||||
setupNote: 'Your password never leaves this device. If forgotten, encrypted data cannot be recovered.',
|
||||
@@ -422,6 +441,7 @@ const T = {
|
||||
errShort: 'Password must be at least 8 characters.',
|
||||
errMismatch: 'Passwords do not match.',
|
||||
errWrong: 'Incorrect password, please try again.',
|
||||
errWrongOld: 'Current password is incorrect, please try again.',
|
||||
unlockedTitle: 'MCP Config',
|
||||
tabMcp: 'Cursor, Claude Code, Codex, Gemini CLI',
|
||||
tabOpencode: 'OpenCode',
|
||||
@@ -832,14 +852,16 @@ async function confirmRegenerate() {
|
||||
// ── Change passphrase modal ────────────────────────────────────────────────────
|
||||
|
||||
function openChangeModal() {
|
||||
document.getElementById('change-pass-old').value = '';
|
||||
document.getElementById('change-pass1').value = '';
|
||||
document.getElementById('change-pass2').value = '';
|
||||
document.getElementById('change-pass-old').type = 'password';
|
||||
document.getElementById('change-pass1').type = 'password';
|
||||
document.getElementById('change-pass2').type = 'password';
|
||||
document.getElementById('change-error').style.display = 'none';
|
||||
document.getElementById('change-modal').classList.add('open');
|
||||
syncPwToggleI18n();
|
||||
setTimeout(() => document.getElementById('change-pass1').focus(), 50);
|
||||
setTimeout(() => document.getElementById('change-pass-old').focus(), 50);
|
||||
}
|
||||
|
||||
function closeChangeModal() {
|
||||
@@ -847,11 +869,13 @@ function closeChangeModal() {
|
||||
}
|
||||
|
||||
async function doChange() {
|
||||
const passOld = document.getElementById('change-pass-old').value;
|
||||
const pass1 = document.getElementById('change-pass1').value;
|
||||
const pass2 = document.getElementById('change-pass2').value;
|
||||
const errEl = document.getElementById('change-error');
|
||||
errEl.style.display = 'none';
|
||||
|
||||
if (!passOld) { showErr(errEl, t('errEmpty')); return; }
|
||||
if (!pass1) { showErr(errEl, t('errEmpty')); return; }
|
||||
if (pass1.length < 8) { showErr(errEl, t('errShort')); return; }
|
||||
if (pass1 !== pass2) { showErr(errEl, t('errMismatch')); return; }
|
||||
@@ -860,24 +884,39 @@ async function doChange() {
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = '<span class="spinner" style="border-top-color:#0d1117"></span>';
|
||||
try {
|
||||
const salt = crypto.getRandomValues(new Uint8Array(32));
|
||||
const cryptoKey = await deriveKey(pass1, salt, true);
|
||||
const keyCheckHex = await encryptKeyCheck(cryptoKey);
|
||||
const hexKey = await exportKeyHex(cryptoKey);
|
||||
// Fetch current salt to derive old key for verification
|
||||
const saltResp = await fetchAuth('/api/key-salt');
|
||||
if (!saltResp.ok) throw new Error('HTTP ' + saltResp.status);
|
||||
const saltData = await saltResp.json();
|
||||
if (!saltData.has_passphrase) throw new Error('No passphrase configured');
|
||||
|
||||
const resp = await fetchAuth('/api/key-setup', {
|
||||
// Derive old key and verify it
|
||||
const oldCryptoKey = await deriveKey(passOld, hexToBytes(saltData.salt), true);
|
||||
const validOld = await verifyKeyCheck(oldCryptoKey, saltData.key_check);
|
||||
if (!validOld) { showErr(errEl, t('errWrongOld')); return; }
|
||||
const oldHexKey = await exportKeyHex(oldCryptoKey);
|
||||
|
||||
// Derive new key
|
||||
const newSalt = crypto.getRandomValues(new Uint8Array(32));
|
||||
const newCryptoKey = await deriveKey(pass1, newSalt, true);
|
||||
const newKeyCheckHex = await encryptKeyCheck(newCryptoKey);
|
||||
const newHexKey = await exportKeyHex(newCryptoKey);
|
||||
|
||||
const resp = await fetchAuth('/api/key-change', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
salt: bytesToHex(salt),
|
||||
key_check: keyCheckHex,
|
||||
old_key: oldHexKey,
|
||||
new_key: newHexKey,
|
||||
salt: bytesToHex(newSalt),
|
||||
key_check: newKeyCheckHex,
|
||||
params: { alg: 'pbkdf2-sha256', iterations: PBKDF2_ITERATIONS }
|
||||
})
|
||||
});
|
||||
if (!resp.ok) throw new Error('HTTP ' + resp.status);
|
||||
|
||||
currentEncKey = hexKey;
|
||||
sessionStorage.setItem('enc_key', hexKey);
|
||||
currentEncKey = newHexKey;
|
||||
sessionStorage.setItem('enc_key', newHexKey);
|
||||
renderRealConfig();
|
||||
closeChangeModal();
|
||||
} catch (e) {
|
||||
|
||||
@@ -30,3 +30,24 @@ GOOGLE_CLIENT_SECRET=
|
||||
|
||||
# ─── 日志(可选)──────────────────────────────────────────────────────
|
||||
# RUST_LOG=secrets_mcp=debug
|
||||
|
||||
# ─── 数据库连接池(可选)──────────────────────────────────────────────
|
||||
# 最大连接数,默认 10
|
||||
# SECRETS_DATABASE_POOL_SIZE=10
|
||||
# 获取连接超时秒数,默认 5
|
||||
# SECRETS_DATABASE_ACQUIRE_TIMEOUT=5
|
||||
|
||||
# ─── 限流(可选)──────────────────────────────────────────────────────
|
||||
# 全局限流速率(req/s),默认 100
|
||||
# RATE_LIMIT_GLOBAL_PER_SECOND=100
|
||||
# 全局限流突发量,默认 200
|
||||
# RATE_LIMIT_GLOBAL_BURST=200
|
||||
# 单 IP 限流速率(req/s),默认 20
|
||||
# RATE_LIMIT_IP_PER_SECOND=20
|
||||
# 单 IP 限流突发量,默认 40
|
||||
# RATE_LIMIT_IP_BURST=40
|
||||
|
||||
# ─── 代理信任(可选)─────────────────────────────────────────────────
|
||||
# 设为 1/true/yes 时从 X-Forwarded-For / X-Real-IP 提取客户端 IP
|
||||
# 仅在反代环境下启用,否则客户端可伪造 IP 绕过限流
|
||||
# TRUST_PROXY=1
|
||||
|
||||
@@ -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