Compare commits

..

9 Commits

Author SHA1 Message Date
voson
1e597559a2 feat(core): FK for user_id columns; MCP search requires user
All checks were successful
Secrets MCP — Build & Release / 检查 / 构建 / 发版 (push) Successful in 3m10s
Secrets MCP — Build & Release / 部署 secrets-mcp (push) Successful in 5s
- Add fk_entries_user_id, fk_entries_history_user_id, fk_audit_log_user_id (ON DELETE SET NULL)
- Add scripts/cleanup-orphan-user-ids.sql for pre-deploy orphan user_id cleanup
- Remove deprecated SERVER_MASTER_KEY / per-user key wrap helpers from secrets-core
- secrets-mcp: require authenticated user for secrets_search; improve body-read failure response
- Bump secrets-mcp to 0.2.1

Made-with: Cursor
2026-03-22 15:40:02 +08:00
voson
e3ca43ca3f release(secrets-mcp): 0.2.0
All checks were successful
Secrets MCP — Build & Release / 检查 / 构建 / 发版 (push) Successful in 3m12s
Secrets MCP — Build & Release / 部署 secrets-mcp (push) Successful in 5s
- 日志时间戳使用本地时区(chrono RFC3339 + 偏移)
- MCP tools / Web 路由与行为调整
- 新增 static/llms.txt、robots.txt;文档与 deploy 示例同步

Made-with: Cursor
2026-03-22 14:44:00 +08:00
voson
0b57605103 feat(secrets-mcp): MCP 请求日志、探测 404 与资源元数据
All checks were successful
Secrets MCP — Build & Release / 检查 / 构建 / 发版 (push) Successful in 3m10s
Secrets MCP — Build & Release / 部署 secrets-mcp (push) Successful in 5s
- 新增 logging 中间件:记录 client_ip、ua、JSON-RPC、tool 等
- tools 各入口/出口结构化日志
- 探测型 404(/.well-known、GET /mcp)降为 debug
- /.well-known/oauth-protected-resource 最小元数据
- secrets-mcp 0.1.11

Made-with: Cursor
2026-03-21 17:57:10 +08:00
voson
8b191937cd docs(AGENTS): 精简提交/推送规则第4条
Made-with: Cursor
2026-03-21 16:56:06 +08:00
voson
11c936a5b8 docs(AGENTS): 明确提交/推送前必须检查版本号与运行 fmt/clippy/test
Made-with: Cursor
2026-03-21 16:48:47 +08:00
voson
b6349dd1c8 chore(secrets-mcp): bump version to 0.1.10
All checks were successful
Secrets MCP — Build & Release / 检查 / 构建 / 发版 (push) Successful in 2m57s
Secrets MCP — Build & Release / 部署 secrets-mcp (push) Successful in 5s
Made-with: Cursor
2026-03-21 16:46:33 +08:00
voson
f720983328 refactor(db): 移除无意义 actor,修复 history 多租户与模型
Some checks failed
Secrets MCP — Build & Release / 部署 secrets-mcp (push) Has been cancelled
Secrets MCP — Build & Release / 检查 / 构建 / 发版 (push) Has started running
- 删除 entries_history / audit_log / secrets_history 的 actor 列及写入逻辑
- MCP secrets_history 透传当前 user_id
- Entry 增加 user_id,search 查询不再用伪 UUID
- 迁移:保留 users.api_key,从 api_keys 表回退时生成新明文 key 并删表
- 文档:audit_log auth 语义、API Key 存储说明

Made-with: Cursor
2026-03-21 16:45:50 +08:00
voson
7bd0603dc6 chore(secrets-mcp): bump version to 0.1.9
All checks were successful
Secrets MCP — Build & Release / 检查 / 构建 / 发版 (push) Successful in 2m47s
Secrets MCP — Build & Release / 部署 secrets-mcp (push) Successful in 5s
Made-with: Cursor
2026-03-21 12:25:38 +08:00
voson
17a95bea5b refactor(audit): 移除旧格式兼容,user_id 统一走列字段
Some checks failed
Secrets MCP — Build & Release / 部署 secrets-mcp (push) Has been cancelled
Secrets MCP — Build & Release / 检查 / 构建 / 发版 (push) Has been cancelled
- audit_log 查询去掉 detail->>'user_id' 回退分支
- login_detail 不再冗余写入 user_id 到 detail JSON
- 迁移 SQL 去掉多余的 ALTER TABLE ADD COLUMN

Made-with: Cursor
2026-03-21 12:24:00 +08:00
19 changed files with 1006 additions and 237 deletions

View File

@@ -2,12 +2,13 @@
本仓库为 **MCP SaaS**`secrets-core`(业务与持久化)+ `secrets-mcp`Streamable HTTP MCP、Web、OAuth、API Key。对外入口见 `crates/secrets-mcp` 本仓库为 **MCP SaaS**`secrets-core`(业务与持久化)+ `secrets-mcp`Streamable HTTP MCP、Web、OAuth、API Key。对外入口见 `crates/secrets-mcp`
## 提交 / 发版硬规则(优先于下文) ## 提交 / 推送硬规则(优先于下文)
**每次提交和推送前必须执行以下检查,无论是否明确「发版」:**
1. 涉及 `crates/**`、根目录 `Cargo.toml`/`Cargo.lock``secrets-mcp` 行为变更的提交,默认视为**需要发版**,除非明确说明「本次不发版」。 1. 涉及 `crates/**`、根目录 `Cargo.toml`/`Cargo.lock``secrets-mcp` 行为变更的提交,默认视为**需要发版**,除非明确说明「本次不发版」。
2. 发版前检查 `crates/secrets-mcp/Cargo.toml``version`,再查 tag`git tag -l 'secrets-mcp-*'` 2. 提交前检查 `crates/secrets-mcp/Cargo.toml``version`,再查 tag`git tag -l 'secrets-mcp-*'`若当前版本对应 tag 已存在且有代码变更,**必须 bump 版本号**并 `cargo build` 同步 `Cargo.lock`
3. 若当前版本对应 tag 已存在,默认允许复用现有 tag 继续构建;仅在需要新的发布版本时再 bump `version``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`
4. 提交前优先运行 `./scripts/release-check.sh`(版本/tag + `fmt` + `clippy --locked` + `test --locked`)。
## 项目结构 ## 项目结构
@@ -28,7 +29,7 @@ secrets/
- **建议库名**`secrets-mcp`(专用实例,与历史库名区分)。 - **建议库名**`secrets-mcp`(专用实例,与历史库名区分)。
- **连接**:环境变量 **`SECRETS_DATABASE_URL`**(本分支无本地配置文件路径)。 - **连接**:环境变量 **`SECRETS_DATABASE_URL`**(本分支无本地配置文件路径)。
- **表**`entries`(含 `user_id`)、`secrets``entries_history``secrets_history``audit_log``users``oauth_accounts``api_keys`,首次连接 **auto-migrate** - **表**`entries`(含 `user_id`)、`secrets``entries_history``secrets_history``audit_log``users``oauth_accounts`,首次连接 **auto-migrate**
### 表结构(摘录) ### 表结构(摘录)
@@ -60,7 +61,7 @@ secrets (
) )
``` ```
### users / oauth_accounts / api_keys ### users / oauth_accounts
```sql ```sql
users ( users (
@@ -71,6 +72,7 @@ users (
key_salt BYTEA, -- PBKDF2 salt32B首次设置密码短语时写入 key_salt BYTEA, -- PBKDF2 salt32B首次设置密码短语时写入
key_check BYTEA, -- 派生密钥加密已知常量,用于验证密码短语 key_check BYTEA, -- 派生密钥加密已知常量,用于验证密码短语
key_params JSONB, -- 算法参数,如 {"alg":"pbkdf2-sha256","iterations":600000} key_params JSONB, -- 算法参数,如 {"alg":"pbkdf2-sha256","iterations":600000}
api_key TEXT UNIQUE, -- MCP Bearer token当前实现为明文存储
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
) )
@@ -83,21 +85,11 @@ oauth_accounts (
... ...
UNIQUE(provider, provider_id) UNIQUE(provider, provider_id)
) )
api_keys (
id UUID PRIMARY KEY DEFAULT uuidv7(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name VARCHAR(256) NOT NULL,
key_hash VARCHAR(64) NOT NULL UNIQUE,
key_prefix VARCHAR(12) NOT NULL,
last_used_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
``` ```
### audit_log / history ### audit_log / history
与迁移脚本一致:`audit_log``entries_history``secrets_history` 用于审计与时间旅行恢复;字段定义见 `crates/secrets-core/src/db.rs``migrate` SQL。 与迁移脚本一致:`audit_log``entries_history``secrets_history` 用于审计与时间旅行恢复;字段定义见 `crates/secrets-core/src/db.rs``migrate` SQL。`audit_log` 中普通业务事件的 `namespace/kind/name` 对应 entry 坐标;登录类事件固定使用 `namespace='auth'`,此时 `kind/name` 表示认证目标而非 entry 身份。
### 字段职责 ### 字段职责
@@ -120,7 +112,7 @@ api_keys (
- 错误:业务层 `anyhow::Result`,避免生产路径 `unwrap()` - 错误:业务层 `anyhow::Result`,避免生产路径 `unwrap()`
- 异步:`tokio` + `sqlx` async。 - 异步:`tokio` + `sqlx` async。
- SQL`sqlx::query` / `query_as` 参数绑定;动态 WHERE 仍须用占位符绑定。 - SQL`sqlx::query` / `query_as` 参数绑定;动态 WHERE 仍须用占位符绑定。
- 日志:运维用 `tracing`;面向用户的 Web 响应走 axum handler。 - 日志:运维用 `tracing`;面向用户的 Web 响应走 axum handler。tracing 字段风格:变量名即字段名时用简写(`%var``?var``var`),否则用显式形式(`field = %expr`)。
- 审计:写操作成功后尽量 `audit::log_tx`;失败可 `warn`,不掩盖主错误。 - 审计:写操作成功后尽量 `audit::log_tx`;失败可 `warn`,不掩盖主错误。
- 加密:密钥由用户密码短语通过 **PBKDF2-SHA256600k 次)** 在客户端派生,服务端只存 `key_salt`/`key_check`/`key_params`不持有原始密钥。Web 客户端在浏览器本地完成加解密MCP 客户端通过 `X-Encryption-Key` 请求头传递密钥,服务端临时解密后返回明文。 - 加密:密钥由用户密码短语通过 **PBKDF2-SHA256600k 次)** 在客户端派生,服务端只存 `key_salt`/`key_check`/`key_params`不持有原始密钥。Web 客户端在浏览器本地完成加解密MCP 客户端通过 `X-Encryption-Key` 请求头传递密钥,服务端临时解密后返回明文。
- MCPtools 参数与 JSON Schema`schemars`)保持同步,鉴权以请求扩展中的用户上下文为准。 - MCPtools 参数与 JSON Schema`schemars`)保持同步,鉴权以请求扩展中的用户上下文为准。
@@ -162,9 +154,8 @@ git tag -l 'secrets-mcp-*'
|------|------| |------|------|
| `SECRETS_DATABASE_URL` | **必填**。PostgreSQL URL。 | | `SECRETS_DATABASE_URL` | **必填**。PostgreSQL URL。 |
| `BASE_URL` | 对外基址OAuth 回调 `${BASE_URL}/auth/google/callback`。 | | `BASE_URL` | 对外基址OAuth 回调 `${BASE_URL}/auth/google/callback`。 |
| `SECRETS_MCP_BIND` | 监听地址,默认 `0.0.0.0:9315`。 | | `SECRETS_MCP_BIND` | 监听地址,默认 `127.0.0.1:9315`(容器/远程直接暴露时需改为 `0.0.0.0:9315`。 |
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | 可选;仅运行时配置。 | | `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | 可选;仅运行时配置。 |
| `RUST_LOG` | 如 `secrets_mcp=debug`。 | | `RUST_LOG` | 如 `secrets_mcp=debug`。 |
| `USER` | 若写入审计 `actor`,由运行环境提供。 |
> `SERVER_MASTER_KEY` 已不再需要。新架构下密钥由用户密码短语在客户端派生,服务端不持有。 > `SERVER_MASTER_KEY` 已不再需要。新架构下密钥由用户密码短语在客户端派生,服务端不持有。

40
Cargo.lock generated
View File

@@ -1809,6 +1809,25 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "rmp"
version = "0.8.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c"
dependencies = [
"num-traits",
]
[[package]]
name = "rmp-serde"
version = "1.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155"
dependencies = [
"rmp",
"serde",
]
[[package]] [[package]]
name = "rsa" name = "rsa"
version = "0.9.10" version = "0.9.10"
@@ -1949,7 +1968,7 @@ dependencies = [
[[package]] [[package]]
name = "secrets-mcp" name = "secrets-mcp"
version = "0.1.8" version = "0.2.1"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"askama", "askama",
@@ -1967,10 +1986,12 @@ dependencies = [
"serde_json", "serde_json",
"sha2", "sha2",
"sqlx", "sqlx",
"time",
"tokio", "tokio",
"tower", "tower",
"tower-http", "tower-http",
"tower-sessions", "tower-sessions",
"tower-sessions-sqlx-store-chrono",
"tracing", "tracing",
"tracing-subscriber", "tracing-subscriber",
"urlencoding", "urlencoding",
@@ -2700,6 +2721,7 @@ dependencies = [
"tower", "tower",
"tower-layer", "tower-layer",
"tower-service", "tower-service",
"tracing",
] ]
[[package]] [[package]]
@@ -2765,6 +2787,22 @@ dependencies = [
"tower-sessions-core", "tower-sessions-core",
] ]
[[package]]
name = "tower-sessions-sqlx-store-chrono"
version = "0.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b295c8fc08db03246e92773c5e10119b72db6bc4240112135bebb0e49670804f"
dependencies = [
"async-trait",
"axum",
"chrono",
"rmp-serde",
"sqlx",
"thiserror",
"time",
"tower-sessions-core",
]
[[package]] [[package]]
name = "tracing" name = "tracing"
version = "0.1.44" version = "0.1.44"

View File

@@ -19,7 +19,7 @@ cargo build --release -p secrets-mcp
|------|------| |------|------|
| `SECRETS_DATABASE_URL` | **必填**。PostgreSQL 连接串(建议专用库,如 `secrets-mcp`)。 | | `SECRETS_DATABASE_URL` | **必填**。PostgreSQL 连接串(建议专用库,如 `secrets-mcp`)。 |
| `BASE_URL` | 对外访问基址OAuth 回调为 `{BASE_URL}/auth/google/callback`。默认 `http://localhost:9315`。 | | `BASE_URL` | 对外访问基址OAuth 回调为 `{BASE_URL}/auth/google/callback`。默认 `http://localhost:9315`。 |
| `SECRETS_MCP_BIND` | 监听地址,默认 `0.0.0.0:9315`反代时常为 `127.0.0.1:9315`。 | | `SECRETS_MCP_BIND` | 监听地址,默认 `127.0.0.1:9315`。容器内或直接对外暴露端口时请改为 `0.0.0.0:9315`反代时常为 `127.0.0.1:9315`。 |
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | 可选;不配置则无 Google 登录入口。运行时从环境读取,勿写入 CI、勿打入二进制。 | | `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | 可选;不配置则无 Google 登录入口。运行时从环境读取,勿写入 CI、勿打入二进制。 |
```bash ```bash
@@ -77,7 +77,7 @@ flowchart LR
### 敏感数据传输 ### 敏感数据传输
- **OAuth `client_secret`** 只存服务端环境变量,不发给浏览器 - **OAuth `client_secret`** 只存服务端环境变量,不发给浏览器
- **API Key** 创建时原始 key 仅展示一次,库中只存 SHA-256 哈希 - **API Key** 当前存放在 `users.api_key`Dashboard 会明文展示并可重置
- **X-Encryption-Key** 随 MCP 请求经 TLS 传输,服务端仅在请求处理期间持有(不持久化) - **X-Encryption-Key** 随 MCP 请求经 TLS 传输,服务端仅在请求处理期间持有(不持久化)
- **生产环境必须走 HTTPS/TLS** - **生产环境必须走 HTTPS/TLS**
@@ -121,7 +121,7 @@ flowchart LR
## 数据模型 ## 数据模型
主表 **`entries`**`namespace``kind``name``tags``metadata`,多租户时带 `user_id`+ 子表 **`secrets`**(每行一个加密字段:`field_name``encrypted`)。另有 `entries_history``secrets_history``audit_log`,以及 **`users`**(含 `key_salt``key_check``key_params`)、**`oauth_accounts`**、**`api_keys`**。首次连库自动迁移建表。 主表 **`entries`**`namespace``kind``name``tags``metadata`,多租户时带 `user_id`+ 子表 **`secrets`**(每行一个加密字段:`field_name``encrypted`)。另有 `entries_history``secrets_history``audit_log`,以及 **`users`**(含 `key_salt``key_check``key_params``api_key`)、**`oauth_accounts`**。首次连库自动迁移建表。
| 位置 | 字段 | 说明 | | 位置 | 字段 | 说明 |
|------|------|------| |------|------|------|
@@ -142,9 +142,10 @@ flowchart LR
## 审计日志 ## 审计日志
`add``update``delete` 等写操作写入 **`audit_log`**(操作类型、对象、摘要,不含 secret 明文)。 `add``update``delete` 等写操作写入 **`audit_log`**(操作类型、对象、摘要,不含 secret 明文)。
其中业务条目事件使用 `[namespace/kind] name` 语义;登录类事件使用 `namespace='auth'`,此时 `kind/name` 表示认证目标(例如 `oauth/google`),不表示某条 secrets entry。
```sql ```sql
SELECT action, namespace, kind, name, actor, detail, created_at SELECT action, namespace, kind, name, detail, created_at
FROM audit_log FROM audit_log
ORDER BY created_at DESC ORDER BY created_at DESC
LIMIT 20; LIMIT 20;

View File

@@ -5,19 +5,8 @@ use uuid::Uuid;
pub const ACTION_LOGIN: &str = "login"; pub const ACTION_LOGIN: &str = "login";
pub const NAMESPACE_AUTH: &str = "auth"; pub const NAMESPACE_AUTH: &str = "auth";
/// Return the current OS user as the audit actor (falls back to empty string). fn login_detail(provider: &str, client_ip: Option<&str>, user_agent: Option<&str>) -> Value {
pub fn current_actor() -> String {
std::env::var("USER").unwrap_or_default()
}
fn login_detail(
user_id: Uuid,
provider: &str,
client_ip: Option<&str>,
user_agent: Option<&str>,
) -> Value {
json!({ json!({
"user_id": user_id,
"provider": provider, "provider": provider,
"client_ip": client_ip, "client_ip": client_ip,
"user_agent": user_agent, "user_agent": user_agent,
@@ -33,11 +22,10 @@ pub async fn log_login(
client_ip: Option<&str>, client_ip: Option<&str>,
user_agent: Option<&str>, user_agent: Option<&str>,
) { ) {
let actor = current_actor(); let detail = login_detail(provider, client_ip, user_agent);
let detail = login_detail(user_id, provider, client_ip, user_agent);
let result: Result<_, sqlx::Error> = sqlx::query( let result: Result<_, sqlx::Error> = sqlx::query(
"INSERT INTO audit_log (user_id, action, namespace, kind, name, detail, actor) \ "INSERT INTO audit_log (user_id, action, namespace, kind, name, detail) \
VALUES ($1, $2, $3, $4, $5, $6, $7)", VALUES ($1, $2, $3, $4, $5, $6)",
) )
.bind(user_id) .bind(user_id)
.bind(ACTION_LOGIN) .bind(ACTION_LOGIN)
@@ -45,14 +33,13 @@ pub async fn log_login(
.bind(kind) .bind(kind)
.bind(provider) .bind(provider)
.bind(&detail) .bind(&detail)
.bind(&actor)
.execute(pool) .execute(pool)
.await; .await;
if let Err(e) = result { if let Err(e) = result {
tracing::warn!(error = %e, kind, provider, "failed to write login audit log"); tracing::warn!(error = %e, kind, provider, "failed to write login audit log");
} else { } else {
tracing::debug!(kind, provider, ?user_id, actor, "login audit logged"); tracing::debug!(kind, provider, ?user_id, "login audit logged");
} }
} }
@@ -66,10 +53,9 @@ pub async fn log_tx(
name: &str, name: &str,
detail: Value, detail: Value,
) { ) {
let actor = current_actor();
let result: Result<_, sqlx::Error> = sqlx::query( let result: Result<_, sqlx::Error> = sqlx::query(
"INSERT INTO audit_log (user_id, action, namespace, kind, name, detail, actor) \ "INSERT INTO audit_log (user_id, action, namespace, kind, name, detail) \
VALUES ($1, $2, $3, $4, $5, $6, $7)", VALUES ($1, $2, $3, $4, $5, $6)",
) )
.bind(user_id) .bind(user_id)
.bind(action) .bind(action)
@@ -77,14 +63,13 @@ pub async fn log_tx(
.bind(kind) .bind(kind)
.bind(name) .bind(name)
.bind(&detail) .bind(&detail)
.bind(&actor)
.execute(&mut **tx) .execute(&mut **tx)
.await; .await;
if let Err(e) = result { if let Err(e) = result {
tracing::warn!(error = %e, "failed to write audit log"); tracing::warn!(error = %e, "failed to write audit log");
} else { } else {
tracing::debug!(action, namespace, kind, name, actor, "audit logged"); tracing::debug!(action, namespace, kind, name, "audit logged");
} }
} }
@@ -94,10 +79,8 @@ mod tests {
#[test] #[test]
fn login_detail_includes_expected_fields() { fn login_detail_includes_expected_fields() {
let user_id = Uuid::nil(); let detail = login_detail("google", Some("127.0.0.1"), Some("Mozilla/5.0"));
let detail = login_detail(user_id, "google", Some("127.0.0.1"), Some("Mozilla/5.0"));
assert_eq!(detail["user_id"], json!(user_id));
assert_eq!(detail["provider"], "google"); assert_eq!(detail["provider"], "google");
assert_eq!(detail["client_ip"], "127.0.0.1"); assert_eq!(detail["client_ip"], "127.0.0.1");
assert_eq!(detail["user_agent"], "Mozilla/5.0"); assert_eq!(detail["user_agent"], "Mozilla/5.0");

View File

@@ -55,35 +55,6 @@ pub fn decrypt_json(master_key: &[u8; 32], data: &[u8]) -> Result<Value> {
serde_json::from_slice(&bytes).context("deserialize decrypted JSON") serde_json::from_slice(&bytes).context("deserialize decrypted JSON")
} }
// ─── Per-user key management (DEPRECATED — kept only for migration) ───────────
/// Generate a new random 32-byte per-user encryption key.
#[allow(dead_code)]
pub fn generate_user_key() -> [u8; 32] {
use aes_gcm::aead::rand_core::RngCore;
let mut key = [0u8; 32];
OsRng.fill_bytes(&mut key);
key
}
/// Wrap a per-user key with the server master key using AES-256-GCM.
#[allow(dead_code)]
pub fn wrap_user_key(server_master_key: &[u8; 32], user_key: &[u8; 32]) -> Result<Vec<u8>> {
encrypt(server_master_key, user_key.as_ref())
}
/// Unwrap a per-user key using the server master key.
#[allow(dead_code)]
pub fn unwrap_user_key(server_master_key: &[u8; 32], wrapped: &[u8]) -> Result<[u8; 32]> {
let bytes = decrypt(server_master_key, wrapped)?;
if bytes.len() != 32 {
bail!("unwrapped user key has unexpected length {}", bytes.len());
}
let mut key = [0u8; 32];
key.copy_from_slice(&bytes);
Ok(key)
}
// ─── Client-supplied key extraction ────────────────────────────────────────── // ─── Client-supplied key extraction ──────────────────────────────────────────
/// Parse a 64-char hex string (from X-Encryption-Key header) into a 32-byte key. /// Parse a 64-char hex string (from X-Encryption-Key header) into a 32-byte key.
@@ -100,33 +71,6 @@ pub fn extract_key_from_hex(hex_str: &str) -> Result<[u8; 32]> {
Ok(key) Ok(key)
} }
// ─── Server master key ────────────────────────────────────────────────────────
/// Load the server master key from `SERVER_MASTER_KEY` environment variable (64 hex chars).
pub fn load_master_key_auto() -> Result<[u8; 32]> {
let hex_str = std::env::var("SERVER_MASTER_KEY").map_err(|_| {
anyhow::anyhow!(
"SERVER_MASTER_KEY is not set. \
Generate one with: openssl rand -hex 32"
)
})?;
if hex_str.is_empty() {
bail!("SERVER_MASTER_KEY is set but empty");
}
let bytes = hex::decode_hex(hex_str.trim())?;
if bytes.len() != 32 {
bail!(
"SERVER_MASTER_KEY must be 64 hex chars (32 bytes), got {} bytes",
bytes.len()
);
}
let mut key = [0u8; 32];
key.copy_from_slice(&bytes);
Ok(key)
}
// ─── Public hex helpers ─────────────────────────────────────────────────────── // ─── Public hex helpers ───────────────────────────────────────────────────────
pub mod hex { pub mod hex {
@@ -186,22 +130,4 @@ mod tests {
let dec = decrypt_json(&key, &enc).unwrap(); let dec = decrypt_json(&key, &enc).unwrap();
assert_eq!(dec, value); assert_eq!(dec, value);
} }
#[test]
fn user_key_wrap_unwrap_roundtrip() {
let server_key = [0xABu8; 32];
let user_key = [0xCDu8; 32];
let wrapped = wrap_user_key(&server_key, &user_key).unwrap();
let unwrapped = unwrap_user_key(&server_key, &wrapped).unwrap();
assert_eq!(unwrapped, user_key);
}
#[test]
fn user_key_wrap_wrong_server_key_fails() {
let server_key1 = [0xABu8; 32];
let server_key2 = [0xEFu8; 32];
let user_key = [0xCDu8; 32];
let wrapped = wrap_user_key(&server_key1, &user_key).unwrap();
assert!(unwrap_user_key(&server_key2, &wrapped).is_err());
}
} }

View File

@@ -3,8 +3,6 @@ use serde_json::Value;
use sqlx::PgPool; use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions; use sqlx::postgres::PgPoolOptions;
use crate::audit::current_actor;
pub async fn create_pool(database_url: &str) -> Result<PgPool> { pub async fn create_pool(database_url: &str) -> Result<PgPool> {
tracing::debug!("connecting to database"); tracing::debug!("connecting to database");
let pool = PgPoolOptions::new() let pool = PgPoolOptions::new()
@@ -73,11 +71,9 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
kind VARCHAR(64) NOT NULL, kind VARCHAR(64) NOT NULL,
name VARCHAR(256) NOT NULL, name VARCHAR(256) NOT NULL,
detail JSONB NOT NULL DEFAULT '{}', detail JSONB NOT NULL DEFAULT '{}',
actor VARCHAR(128) NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
); );
ALTER TABLE audit_log ADD COLUMN IF NOT EXISTS user_id UUID;
CREATE INDEX IF NOT EXISTS idx_audit_log_created ON audit_log(created_at DESC); CREATE INDEX IF NOT EXISTS idx_audit_log_created ON audit_log(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_audit_log_ns_kind ON audit_log(namespace, kind); CREATE INDEX IF NOT EXISTS idx_audit_log_ns_kind ON audit_log(namespace, kind);
CREATE INDEX IF NOT EXISTS idx_audit_log_user_id ON audit_log(user_id) WHERE user_id IS NOT NULL; CREATE INDEX IF NOT EXISTS idx_audit_log_user_id ON audit_log(user_id) WHERE user_id IS NOT NULL;
@@ -93,7 +89,6 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
action VARCHAR(16) NOT NULL, action VARCHAR(16) NOT NULL,
tags TEXT[] NOT NULL DEFAULT '{}', tags TEXT[] NOT NULL DEFAULT '{}',
metadata JSONB NOT NULL DEFAULT '{}', metadata JSONB NOT NULL DEFAULT '{}',
actor VARCHAR(128) NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
); );
@@ -106,6 +101,7 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
ALTER TABLE entries_history ADD COLUMN IF NOT EXISTS user_id UUID; ALTER TABLE entries_history ADD COLUMN IF NOT EXISTS user_id UUID;
CREATE INDEX IF NOT EXISTS idx_entries_history_user_id CREATE INDEX IF NOT EXISTS idx_entries_history_user_id
ON entries_history(user_id) WHERE user_id IS NOT NULL; ON entries_history(user_id) WHERE user_id IS NOT NULL;
ALTER TABLE entries_history DROP COLUMN IF EXISTS actor;
-- ── secrets_history: field-level snapshot ──────────────────────────────── -- ── secrets_history: field-level snapshot ────────────────────────────────
CREATE TABLE IF NOT EXISTS secrets_history ( CREATE TABLE IF NOT EXISTS secrets_history (
@@ -116,7 +112,6 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
field_name VARCHAR(256) NOT NULL, field_name VARCHAR(256) NOT NULL,
encrypted BYTEA NOT NULL DEFAULT '\x', encrypted BYTEA NOT NULL DEFAULT '\x',
action VARCHAR(16) NOT NULL, action VARCHAR(16) NOT NULL,
actor VARCHAR(128) NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
); );
@@ -125,6 +120,12 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
CREATE INDEX IF NOT EXISTS idx_secrets_history_secret_id CREATE INDEX IF NOT EXISTS idx_secrets_history_secret_id
ON secrets_history(secret_id); ON secrets_history(secret_id);
-- Drop redundant actor column (derivable via entries_history JOIN)
ALTER TABLE secrets_history DROP COLUMN IF EXISTS actor;
-- Drop redundant actor column; user_id already identifies the business user
ALTER TABLE audit_log DROP COLUMN IF EXISTS actor;
-- ── users ───────────────────────────────────────────────────────────────── -- ── users ─────────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS users ( CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY DEFAULT uuidv7(), id UUID PRIMARY KEY DEFAULT uuidv7(),
@@ -155,14 +156,110 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
CREATE INDEX IF NOT EXISTS idx_oauth_accounts_user ON oauth_accounts(user_id); CREATE INDEX IF NOT EXISTS idx_oauth_accounts_user ON oauth_accounts(user_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_oauth_accounts_user_provider CREATE UNIQUE INDEX IF NOT EXISTS idx_oauth_accounts_user_provider
ON oauth_accounts(user_id, provider); ON oauth_accounts(user_id, provider);
-- FK: user_id columns -> users(id) (nullable = legacy rows; ON DELETE SET NULL)
DO $$ BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint WHERE conname = 'fk_entries_user_id'
) THEN
ALTER TABLE entries
ADD CONSTRAINT fk_entries_user_id
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL;
END IF;
END $$;
DO $$ BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint WHERE conname = 'fk_entries_history_user_id'
) THEN
ALTER TABLE entries_history
ADD CONSTRAINT fk_entries_history_user_id
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL;
END IF;
END $$;
DO $$ BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint WHERE conname = 'fk_audit_log_user_id'
) THEN
ALTER TABLE audit_log
ADD CONSTRAINT fk_audit_log_user_id
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL;
END IF;
END $$;
"#, "#,
) )
.execute(pool) .execute(pool)
.await?; .await?;
restore_plaintext_api_keys(pool).await?;
tracing::debug!("migrations complete"); tracing::debug!("migrations complete");
Ok(()) Ok(())
} }
async fn restore_plaintext_api_keys(pool: &PgPool) -> Result<()> {
let has_users_api_key: bool = sqlx::query_scalar(
"SELECT EXISTS (
SELECT 1
FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'users'
AND column_name = 'api_key'
)",
)
.fetch_one(pool)
.await?;
if !has_users_api_key {
sqlx::query("ALTER TABLE users ADD COLUMN api_key TEXT")
.execute(pool)
.await?;
sqlx::query("CREATE UNIQUE INDEX IF NOT EXISTS idx_users_api_key ON users(api_key) WHERE api_key IS NOT NULL")
.execute(pool)
.await?;
}
let has_api_keys_table: bool = sqlx::query_scalar(
"SELECT EXISTS (
SELECT 1
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'api_keys'
)",
)
.fetch_one(pool)
.await?;
if !has_api_keys_table {
return Ok(());
}
#[derive(sqlx::FromRow)]
struct UserWithoutKey {
id: uuid::Uuid,
}
let users_without_key: Vec<UserWithoutKey> =
sqlx::query_as("SELECT DISTINCT user_id AS id FROM api_keys WHERE user_id NOT IN (SELECT id FROM users WHERE api_key IS NOT NULL)")
.fetch_all(pool)
.await?;
for user in users_without_key {
let new_key = crate::service::api_key::generate_api_key();
sqlx::query("UPDATE users SET api_key = $1 WHERE id = $2")
.bind(&new_key)
.bind(user.id)
.execute(pool)
.await?;
}
sqlx::query("DROP TABLE IF EXISTS api_keys")
.execute(pool)
.await?;
Ok(())
}
// ── Entry-level history snapshot ───────────────────────────────────────────── // ── Entry-level history snapshot ─────────────────────────────────────────────
pub struct EntrySnapshotParams<'a> { pub struct EntrySnapshotParams<'a> {
@@ -181,11 +278,10 @@ pub async fn snapshot_entry_history(
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
p: EntrySnapshotParams<'_>, p: EntrySnapshotParams<'_>,
) -> Result<()> { ) -> Result<()> {
let actor = current_actor();
sqlx::query( sqlx::query(
"INSERT INTO entries_history \ "INSERT INTO entries_history \
(entry_id, namespace, kind, name, version, action, tags, metadata, actor, user_id) \ (entry_id, namespace, kind, name, version, action, tags, metadata, user_id) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)", VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)",
) )
.bind(p.entry_id) .bind(p.entry_id)
.bind(p.namespace) .bind(p.namespace)
@@ -195,7 +291,6 @@ pub async fn snapshot_entry_history(
.bind(p.action) .bind(p.action)
.bind(p.tags) .bind(p.tags)
.bind(p.metadata) .bind(p.metadata)
.bind(&actor)
.bind(p.user_id) .bind(p.user_id)
.execute(&mut **tx) .execute(&mut **tx)
.await?; .await?;
@@ -217,11 +312,10 @@ pub async fn snapshot_secret_history(
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
p: SecretSnapshotParams<'_>, p: SecretSnapshotParams<'_>,
) -> Result<()> { ) -> Result<()> {
let actor = current_actor();
sqlx::query( sqlx::query(
"INSERT INTO secrets_history \ "INSERT INTO secrets_history \
(entry_id, secret_id, entry_version, field_name, encrypted, action, actor) \ (entry_id, secret_id, entry_version, field_name, encrypted, action) \
VALUES ($1, $2, $3, $4, $5, $6, $7)", VALUES ($1, $2, $3, $4, $5, $6)",
) )
.bind(p.entry_id) .bind(p.entry_id)
.bind(p.secret_id) .bind(p.secret_id)
@@ -229,7 +323,6 @@ pub async fn snapshot_secret_history(
.bind(p.field_name) .bind(p.field_name)
.bind(p.encrypted) .bind(p.encrypted)
.bind(p.action) .bind(p.action)
.bind(&actor)
.execute(&mut **tx) .execute(&mut **tx)
.await?; .await?;
Ok(()) Ok(())

View File

@@ -9,6 +9,7 @@ use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize, sqlx::FromRow)] #[derive(Debug, Serialize, Deserialize, sqlx::FromRow)]
pub struct Entry { pub struct Entry {
pub id: Uuid, pub id: Uuid,
pub user_id: Option<Uuid>,
pub namespace: String, pub namespace: String,
pub kind: String, pub kind: String,
pub name: String, pub name: String,
@@ -184,7 +185,6 @@ pub struct AuditLogEntry {
pub kind: String, pub kind: String,
pub name: String, pub name: String,
pub detail: Value, pub detail: Value,
pub actor: String,
pub created_at: DateTime<Utc>, pub created_at: DateTime<Utc>,
} }

View File

@@ -8,9 +8,9 @@ pub async fn list_for_user(pool: &PgPool, user_id: Uuid, limit: i64) -> Result<V
let limit = limit.clamp(1, 200); let limit = limit.clamp(1, 200);
let rows = sqlx::query_as( let rows = sqlx::query_as(
"SELECT id, user_id, action, namespace, kind, name, detail, actor, created_at \ "SELECT id, user_id, action, namespace, kind, name, detail, created_at \
FROM audit_log \ FROM audit_log \
WHERE user_id = $1 OR (user_id IS NULL AND detail->>'user_id' = $1::text) \ WHERE user_id = $1 \
ORDER BY created_at DESC, id DESC \ ORDER BY created_at DESC, id DESC \
LIMIT $2", LIMIT $2",
) )

View File

@@ -7,7 +7,6 @@ use uuid::Uuid;
pub struct HistoryEntry { pub struct HistoryEntry {
pub version: i64, pub version: i64,
pub action: String, pub action: String,
pub actor: String,
pub created_at: String, pub created_at: String,
} }
@@ -23,13 +22,12 @@ pub async fn run(
struct Row { struct Row {
version: i64, version: i64,
action: String, action: String,
actor: String,
created_at: chrono::DateTime<chrono::Utc>, created_at: chrono::DateTime<chrono::Utc>,
} }
let rows: Vec<Row> = if let Some(uid) = user_id { let rows: Vec<Row> = if let Some(uid) = user_id {
sqlx::query_as( sqlx::query_as(
"SELECT version, action, actor, created_at FROM entries_history \ "SELECT version, action, created_at FROM entries_history \
WHERE namespace = $1 AND kind = $2 AND name = $3 AND user_id = $4 \ WHERE namespace = $1 AND kind = $2 AND name = $3 AND user_id = $4 \
ORDER BY id DESC LIMIT $5", ORDER BY id DESC LIMIT $5",
) )
@@ -42,7 +40,7 @@ pub async fn run(
.await? .await?
} else { } else {
sqlx::query_as( sqlx::query_as(
"SELECT version, action, actor, created_at FROM entries_history \ "SELECT version, action, created_at FROM entries_history \
WHERE namespace = $1 AND kind = $2 AND name = $3 AND user_id IS NULL \ WHERE namespace = $1 AND kind = $2 AND name = $3 AND user_id IS NULL \
ORDER BY id DESC LIMIT $4", ORDER BY id DESC LIMIT $4",
) )
@@ -59,7 +57,6 @@ pub async fn run(
.map(|r| HistoryEntry { .map(|r| HistoryEntry {
version: r.version, version: r.version,
action: r.action, action: r.action,
actor: r.actor,
created_at: r.created_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(), created_at: r.created_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
}) })
.collect()) .collect())

View File

@@ -131,7 +131,7 @@ async fn fetch_entries_paged(pool: &PgPool, a: &SearchParams<'_>) -> Result<Vec<
}; };
let sql = format!( let sql = format!(
"SELECT id, COALESCE(user_id, '00000000-0000-0000-0000-000000000000'::uuid) AS user_id, \ "SELECT id, user_id, \
namespace, kind, name, tags, metadata, version, created_at, updated_at \ namespace, kind, name, tags, metadata, version, created_at, updated_at \
FROM entries {where_clause} ORDER BY {order} LIMIT ${limit_idx} OFFSET ${offset_idx}" FROM entries {where_clause} ORDER BY {order} LIMIT ${limit_idx} OFFSET ${offset_idx}"
); );
@@ -212,8 +212,7 @@ pub async fn fetch_secrets_for_entries(
#[derive(sqlx::FromRow)] #[derive(sqlx::FromRow)]
struct EntryRaw { struct EntryRaw {
id: Uuid, id: Uuid,
#[allow(dead_code)] // Selected for row shape; Entry model has no user_id field user_id: Option<Uuid>,
user_id: Uuid,
namespace: String, namespace: String,
kind: String, kind: String,
name: String, name: String,
@@ -228,6 +227,7 @@ impl From<EntryRaw> for Entry {
fn from(r: EntryRaw) -> Self { fn from(r: EntryRaw) -> Self {
Entry { Entry {
id: r.id, id: r.id,
user_id: r.user_id,
namespace: r.namespace, namespace: r.namespace,
kind: r.kind, kind: r.kind,
name: r.name, name: r.name,

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "secrets-mcp" name = "secrets-mcp"
version = "0.1.8" version = "0.2.1"
edition.workspace = true edition.workspace = true
[[bin]] [[bin]]
@@ -17,8 +17,10 @@ rmcp = { version = "1", features = ["server", "macros", "transport-streamable-ht
axum = "0.8" axum = "0.8"
axum-extra = { version = "0.10", features = ["typed-header"] } axum-extra = { version = "0.10", features = ["typed-header"] }
tower = "0.5" tower = "0.5"
tower-http = { version = "0.6", features = ["cors"] } tower-http = { version = "0.6", features = ["cors", "trace"] }
tower-sessions = "0.14" tower-sessions = "0.14"
tower-sessions-sqlx-store-chrono = { version = "0.14", features = ["postgres"] }
time = "0.3"
# OAuth (manual token exchange via reqwest) # OAuth (manual token exchange via reqwest)
reqwest.workspace = true reqwest.workspace = true

View File

@@ -0,0 +1,262 @@
use std::net::SocketAddr;
use std::time::Instant;
use axum::{
body::{Body, Bytes, to_bytes},
extract::{ConnectInfo, Request},
http::{
HeaderMap, Method, StatusCode,
header::{CONTENT_LENGTH, CONTENT_TYPE, USER_AGENT},
},
middleware::Next,
response::{IntoResponse, Response},
};
/// Axum middleware that logs structured info for every HTTP request.
///
/// All requests: method, path, status, latency_ms, client_ip, user_agent.
/// POST /mcp requests: additionally parses JSON-RPC body for jsonrpc_method,
/// tool_name, jsonrpc_id, mcp_session, batch_size.
///
/// Sensitive headers (Authorization, X-Encryption-Key) and secret values
/// are never logged.
pub async fn request_logging_middleware(req: Request, next: Next) -> Response {
let method = req.method().clone();
let path = req.uri().path().to_string();
let ip = client_ip(&req);
let ua = header_str(req.headers(), USER_AGENT);
let content_len = header_str(req.headers(), CONTENT_LENGTH).and_then(|v| v.parse::<u64>().ok());
let mcp_session = req
.headers()
.get("mcp-session-id")
.or_else(|| req.headers().get("x-mcp-session"))
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string());
let is_mcp_post = path.starts_with("/mcp") && method == Method::POST;
let is_json = header_str(req.headers(), CONTENT_TYPE)
.map(|ct| ct.contains("application/json"))
.unwrap_or(false);
let start = Instant::now();
// For MCP JSON-RPC POST requests, buffer body to extract JSON-RPC metadata.
// We cap at 512 KiB to avoid buffering large payloads.
if is_mcp_post && is_json {
let cap = content_len.unwrap_or(0);
if cap <= 512 * 1024 {
let (parts, body) = req.into_parts();
match to_bytes(body, 512 * 1024).await {
Ok(bytes) => {
let rpc = parse_jsonrpc_meta(&bytes);
let req = Request::from_parts(parts, Body::from(bytes));
let resp = next.run(req).await;
let status = resp.status().as_u16();
let elapsed = start.elapsed().as_millis();
log_mcp_request(
&method,
&path,
status,
elapsed,
ip.as_deref(),
ua.as_deref(),
content_len,
mcp_session.as_deref(),
&rpc,
);
return resp;
}
Err(e) => {
tracing::warn!(path, error = %e, "failed to buffer MCP request body for logging");
let elapsed = start.elapsed().as_millis();
tracing::info!(
method = method.as_str(),
path,
status = StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
elapsed_ms = elapsed,
client_ip = ip.as_deref(),
ua = ua.as_deref(),
content_length = content_len,
mcp_session = mcp_session.as_deref(),
"mcp request",
);
return (
StatusCode::INTERNAL_SERVER_ERROR,
"failed to read request body",
)
.into_response();
}
}
}
}
let resp = next.run(req).await;
let status = resp.status().as_u16();
let elapsed = start.elapsed().as_millis();
// Known client probe patterns that legitimately 404 — downgrade to debug to
// avoid noise in production logs. These are:
// • GET /.well-known/* — OAuth/OIDC discovery by MCP clients (RFC 8414 / RFC 9728)
// • GET /mcp → 404 — old SSE-transport compatibility probe by clients
let is_expected_probe_404 = status == 404
&& (path.starts_with("/.well-known/")
|| (method == Method::GET && path.starts_with("/mcp")));
if is_expected_probe_404 {
tracing::debug!(
method = method.as_str(),
path,
status,
elapsed_ms = elapsed,
client_ip = ip.as_deref(),
ua = ua.as_deref(),
"probe request (not found — expected)",
);
} else {
log_http_request(
&method,
&path,
status,
elapsed,
ip.as_deref(),
ua.as_deref(),
content_len,
);
}
resp
}
// ── Logging helpers ───────────────────────────────────────────────────────────
fn log_http_request(
method: &Method,
path: &str,
status: u16,
elapsed_ms: u128,
client_ip: Option<&str>,
ua: Option<&str>,
content_length: Option<u64>,
) {
tracing::info!(
method = method.as_str(),
path,
status,
elapsed_ms,
client_ip,
ua,
content_length,
"http request",
);
}
#[allow(clippy::too_many_arguments)]
fn log_mcp_request(
method: &Method,
path: &str,
status: u16,
elapsed_ms: u128,
client_ip: Option<&str>,
ua: Option<&str>,
content_length: Option<u64>,
mcp_session: Option<&str>,
rpc: &JsonRpcMeta,
) {
tracing::info!(
method = method.as_str(),
path,
status,
elapsed_ms,
client_ip,
ua,
content_length,
mcp_session,
jsonrpc = rpc.rpc_method.as_deref(),
tool = rpc.tool_name.as_deref(),
jsonrpc_id = rpc.request_id.as_deref(),
batch_size = rpc.batch_size,
"mcp request",
);
}
// ── JSON-RPC body parsing ─────────────────────────────────────────────────────
#[derive(Debug, Default)]
struct JsonRpcMeta {
request_id: Option<String>,
rpc_method: Option<String>,
tool_name: Option<String>,
batch_size: Option<usize>,
}
fn parse_jsonrpc_meta(bytes: &Bytes) -> JsonRpcMeta {
let Ok(value) = serde_json::from_slice::<serde_json::Value>(bytes) else {
return JsonRpcMeta::default();
};
if let Some(arr) = value.as_array() {
// Batch request: summarise method(s) from first element only
let first = arr.first().map(parse_single).unwrap_or_default();
return JsonRpcMeta {
batch_size: Some(arr.len()),
..first
};
}
parse_single(&value)
}
fn parse_single(value: &serde_json::Value) -> JsonRpcMeta {
let request_id = value.get("id").and_then(json_to_string);
let rpc_method = value
.get("method")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
let tool_name = value
.pointer("/params/name")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
JsonRpcMeta {
request_id,
rpc_method,
tool_name,
batch_size: None,
}
}
fn json_to_string(value: &serde_json::Value) -> Option<String> {
match value {
serde_json::Value::Null => None,
serde_json::Value::String(s) => Some(s.clone()),
serde_json::Value::Number(n) => Some(n.to_string()),
serde_json::Value::Bool(b) => Some(b.to_string()),
other => Some(other.to_string()),
}
}
// ── Header helpers ────────────────────────────────────────────────────────────
fn header_str(headers: &HeaderMap, name: impl axum::http::header::AsHeaderName) -> Option<String> {
headers
.get(name)
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string())
}
fn client_ip(req: &Request) -> Option<String> {
if let Some(first) = req
.headers()
.get("x-forwarded-for")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.split(',').next())
{
let s = first.trim();
if !s.is_empty() {
return Some(s.to_string());
}
}
req.extensions()
.get::<ConnectInfo<SocketAddr>>()
.map(|c| c.ip().to_string())
}

View File

@@ -1,4 +1,5 @@
mod auth; mod auth;
mod logging;
mod oauth; mod oauth;
mod tools; mod tools;
mod web; mod web;
@@ -14,8 +15,11 @@ use rmcp::transport::streamable_http_server::{
use sqlx::PgPool; use sqlx::PgPool;
use tower_http::cors::{Any, CorsLayer}; use tower_http::cors::{Any, CorsLayer};
use tower_sessions::cookie::SameSite; use tower_sessions::cookie::SameSite;
use tower_sessions::{MemoryStore, SessionManagerLayer}; use tower_sessions::session_store::ExpiredDeletion;
use tower_sessions::{Expiry, SessionManagerLayer};
use tower_sessions_sqlx_store_chrono::PostgresStore;
use tracing_subscriber::EnvFilter; use tracing_subscriber::EnvFilter;
use tracing_subscriber::fmt::time::FormatTime;
use secrets_core::config::resolve_db_url; use secrets_core::config::resolve_db_url;
use secrets_core::db::{create_pool, migrate}; use secrets_core::db::{create_pool, migrate};
@@ -46,14 +50,30 @@ fn load_oauth_config(prefix: &str, base_url: &str, path: &str) -> Option<OAuthCo
}) })
} }
/// Log line timestamps in the process local timezone (honors `TZ` / system zone).
#[derive(Clone, Copy, Default)]
struct LocalRfc3339Time;
impl FormatTime for LocalRfc3339Time {
fn format_time(&self, w: &mut tracing_subscriber::fmt::format::Writer<'_>) -> std::fmt::Result {
write!(
w,
"{}",
chrono::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, false)
)
}
}
#[tokio::main] #[tokio::main]
async fn main() -> Result<()> { async fn main() -> Result<()> {
// Load .env if present // Load .env if present
let _ = dotenvy::dotenv(); let _ = dotenvy::dotenv();
tracing_subscriber::fmt() tracing_subscriber::fmt()
.with_timer(LocalRfc3339Time)
.with_env_filter( .with_env_filter(
EnvFilter::try_from_default_env().unwrap_or_else(|_| "secrets_mcp=info".into()), EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "secrets_mcp=info,tower_http=info".into()),
) )
.init(); .init();
@@ -70,7 +90,8 @@ async fn main() -> Result<()> {
// ── Configuration ───────────────────────────────────────────────────────── // ── Configuration ─────────────────────────────────────────────────────────
let base_url = load_env_var("BASE_URL").unwrap_or_else(|| "http://localhost:9315".to_string()); let base_url = load_env_var("BASE_URL").unwrap_or_else(|| "http://localhost:9315".to_string());
let bind_addr = load_env_var("SECRETS_MCP_BIND").unwrap_or_else(|| "0.0.0.0:9315".to_string()); let bind_addr =
load_env_var("SECRETS_MCP_BIND").unwrap_or_else(|| "127.0.0.1:9315".to_string());
// ── OAuth providers ─────────────────────────────────────────────────────── // ── OAuth providers ───────────────────────────────────────────────────────
let google_config = load_oauth_config("GOOGLE", &base_url, "/auth/google/callback"); let google_config = load_oauth_config("GOOGLE", &base_url, "/auth/google/callback");
@@ -81,12 +102,23 @@ async fn main() -> Result<()> {
); );
} }
// ── Session store ───────────────────────────────────────────────────────── // ── Session store (PostgreSQL-backed) ─────────────────────────────────────
let session_store = MemoryStore::default(); let session_store = PostgresStore::new(pool.clone());
session_store
.migrate()
.await
.context("failed to run session table migration")?;
// Prune expired rows every hour; task is aborted when the server shuts down.
let session_cleanup = tokio::spawn(
session_store
.clone()
.continuously_delete_expired(tokio::time::Duration::from_secs(3600)),
);
// Strict would drop the session cookie on redirect from Google → our origin (cross-site nav). // Strict would drop the session cookie on redirect from Google → our origin (cross-site nav).
let session_layer = SessionManagerLayer::new(session_store) let session_layer = SessionManagerLayer::new(session_store)
.with_secure(base_url.starts_with("https://")) .with_secure(base_url.starts_with("https://"))
.with_same_site(SameSite::Lax); .with_same_site(SameSite::Lax)
.with_expiry(Expiry::OnInactivity(time::Duration::days(14)));
// ── App state ───────────────────────────────────────────────────────────── // ── App state ─────────────────────────────────────────────────────────────
let app_state = AppState { let app_state = AppState {
@@ -120,6 +152,9 @@ async fn main() -> Result<()> {
let router = Router::new() let router = Router::new()
.merge(web::web_router()) .merge(web::web_router())
.nest_service("/mcp", mcp_service) .nest_service("/mcp", mcp_service)
.layer(axum::middleware::from_fn(
logging::request_logging_middleware,
))
.layer(axum::middleware::from_fn_with_state( .layer(axum::middleware::from_fn_with_state(
pool, pool,
auth::bearer_auth_middleware, auth::bearer_auth_middleware,
@@ -144,6 +179,7 @@ async fn main() -> Result<()> {
.await .await
.context("server error")?; .context("server error")?;
session_cleanup.abort();
Ok(()) Ok(())
} }

View File

@@ -1,4 +1,5 @@
use std::sync::Arc; use std::sync::Arc;
use std::time::Instant;
use anyhow::Result; use anyhow::Result;
use rmcp::{ use rmcp::{
@@ -16,6 +17,7 @@ use serde::Deserialize;
use sqlx::PgPool; use sqlx::PgPool;
use uuid::Uuid; use uuid::Uuid;
use secrets_core::models::ExportFormat;
use secrets_core::service::{ use secrets_core::service::{
add::{AddParams, run as svc_add}, add::{AddParams, run as svc_add},
delete::{DeleteParams, run as svc_delete}, delete::{DeleteParams, run as svc_delete},
@@ -29,6 +31,32 @@ use secrets_core::service::{
use crate::auth::AuthUser; use crate::auth::AuthUser;
// ── MCP client-facing errors (no internal details) ───────────────────────────
fn mcp_err_missing_http_parts() -> rmcp::ErrorData {
rmcp::ErrorData::internal_error("Invalid MCP request context.", None)
}
fn mcp_err_internal_logged(
tool: &'static str,
user_id: Option<Uuid>,
err: impl std::fmt::Display,
) -> rmcp::ErrorData {
tracing::warn!(tool, ?user_id, error = %err, "tool call failed");
rmcp::ErrorData::internal_error(
"Request failed due to a server error. Check service logs if you need details.",
None,
)
}
fn mcp_err_invalid_encryption_key_logged(err: impl std::fmt::Display) -> rmcp::ErrorData {
tracing::warn!(error = %err, "invalid X-Encryption-Key");
rmcp::ErrorData::invalid_request(
"Invalid X-Encryption-Key: must be exactly 64 hexadecimal characters (32-byte key).",
None,
)
}
// ── Shared state ────────────────────────────────────────────────────────────── // ── Shared state ──────────────────────────────────────────────────────────────
#[derive(Clone)] #[derive(Clone)]
@@ -50,7 +78,7 @@ impl SecretsService {
let parts = ctx let parts = ctx
.extensions .extensions
.get::<http::request::Parts>() .get::<http::request::Parts>()
.ok_or_else(|| rmcp::ErrorData::internal_error("Missing HTTP parts", None))?; .ok_or_else(mcp_err_missing_http_parts)?;
Ok(parts.extensions.get::<AuthUser>().map(|a| a.user_id)) Ok(parts.extensions.get::<AuthUser>().map(|a| a.user_id))
} }
@@ -59,7 +87,7 @@ impl SecretsService {
let parts = ctx let parts = ctx
.extensions .extensions
.get::<http::request::Parts>() .get::<http::request::Parts>()
.ok_or_else(|| rmcp::ErrorData::internal_error("Missing HTTP parts", None))?; .ok_or_else(mcp_err_missing_http_parts)?;
parts parts
.extensions .extensions
.get::<AuthUser>() .get::<AuthUser>()
@@ -73,7 +101,7 @@ impl SecretsService {
let parts = ctx let parts = ctx
.extensions .extensions
.get::<http::request::Parts>() .get::<http::request::Parts>()
.ok_or_else(|| rmcp::ErrorData::internal_error("Missing HTTP parts", None))?; .ok_or_else(mcp_err_missing_http_parts)?;
let hex_str = parts let hex_str = parts
.headers .headers
.get("x-encryption-key") .get("x-encryption-key")
@@ -88,8 +116,29 @@ impl SecretsService {
.map_err(|_| { .map_err(|_| {
rmcp::ErrorData::invalid_request("Invalid X-Encryption-Key header value", None) rmcp::ErrorData::invalid_request("Invalid X-Encryption-Key header value", None)
})?; })?;
let trimmed = hex_str.trim();
if trimmed.len() != 64 {
tracing::warn!(
got_len = trimmed.len(),
"X-Encryption-Key has wrong length after trim"
);
return Err(rmcp::ErrorData::invalid_request(
format!(
"X-Encryption-Key must be exactly 64 hex characters (32-byte key), got {} characters.",
trimmed.len()
),
None,
));
}
if !trimmed.chars().all(|c| c.is_ascii_hexdigit()) {
tracing::warn!("X-Encryption-Key contains non-hexadecimal characters");
return Err(rmcp::ErrorData::invalid_request(
"X-Encryption-Key contains non-hexadecimal characters.",
None,
));
}
secrets_core::crypto::extract_key_from_hex(hex_str) secrets_core::crypto::extract_key_from_hex(hex_str)
.map_err(|e| rmcp::ErrorData::invalid_request(e.to_string(), None)) .map_err(mcp_err_invalid_encryption_key_logged)
} }
/// Require both user_id and encryption key. /// Require both user_id and encryption key.
@@ -249,15 +298,30 @@ struct EnvMapInput {
#[tool_router] #[tool_router]
impl SecretsService { impl SecretsService {
#[tool( #[tool(
description = "Search entries in the secrets store. Returns entries with metadata and \ description = "Search entries in the secrets store. Requires Bearer API key. Returns \
secret field names (not values). Use secrets_get to decrypt secret values." entries with metadata and secret field names (not values). Use secrets_get to decrypt secret values.",
annotations(
title = "Search Secrets",
read_only_hint = true,
idempotent_hint = true
)
)] )]
async fn secrets_search( async fn secrets_search(
&self, &self,
Parameters(input): Parameters<SearchInput>, Parameters(input): Parameters<SearchInput>,
ctx: RequestContext<RoleServer>, ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, rmcp::ErrorData> { ) -> Result<CallToolResult, rmcp::ErrorData> {
let user_id = Self::user_id_from_ctx(&ctx)?; let t = Instant::now();
let user_id = Self::require_user_id(&ctx)?;
tracing::info!(
tool = "secrets_search",
?user_id,
namespace = input.namespace.as_deref(),
kind = input.kind.as_deref(),
name = input.name.as_deref(),
query = input.query.as_deref(),
"tool call start",
);
let tags = input.tags.unwrap_or_default(); let tags = input.tags.unwrap_or_default();
let result = svc_search( let result = svc_search(
&self.pool, &self.pool,
@@ -270,11 +334,11 @@ impl SecretsService {
sort: input.sort.as_deref().unwrap_or("name"), sort: input.sort.as_deref().unwrap_or("name"),
limit: input.limit.unwrap_or(20), limit: input.limit.unwrap_or(20),
offset: input.offset.unwrap_or(0), offset: input.offset.unwrap_or(0),
user_id, user_id: Some(user_id),
}, },
) )
.await .await
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?; .map_err(|e| mcp_err_internal_logged("secrets_search", Some(user_id), e))?;
let summary = input.summary.unwrap_or(false); let summary = input.summary.unwrap_or(false);
let entries: Vec<serde_json::Value> = result let entries: Vec<serde_json::Value> = result
@@ -312,6 +376,14 @@ impl SecretsService {
}) })
.collect(); .collect();
let count = entries.len();
tracing::info!(
tool = "secrets_search",
?user_id,
result_count = 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(&entries).unwrap_or_else(|_| "[]".to_string());
Ok(CallToolResult::success(vec![Content::text(json)])) Ok(CallToolResult::success(vec![Content::text(json)]))
} }
@@ -319,14 +391,29 @@ impl SecretsService {
#[tool( #[tool(
description = "Get decrypted secret field values for an entry. Requires your \ description = "Get decrypted secret field values for an entry. Requires your \
encryption key via X-Encryption-Key header (64 hex chars, PBKDF2-derived). \ encryption key via X-Encryption-Key header (64 hex chars, PBKDF2-derived). \
Returns all fields, or a specific field if 'field' is provided." Returns all fields, or a specific field if 'field' is provided.",
annotations(
title = "Get Secret Values",
read_only_hint = true,
idempotent_hint = true
)
)] )]
async fn secrets_get( async fn secrets_get(
&self, &self,
Parameters(input): Parameters<GetSecretInput>, Parameters(input): Parameters<GetSecretInput>,
ctx: RequestContext<RoleServer>, ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, rmcp::ErrorData> { ) -> 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(&ctx)?;
tracing::info!(
tool = "secrets_get",
?user_id,
namespace = %input.namespace,
kind = %input.kind,
name = %input.name,
field = input.field.as_deref(),
"tool call start",
);
if let Some(field_name) = &input.field { if let Some(field_name) = &input.field {
let value = get_secret_field( let value = get_secret_field(
@@ -339,8 +426,14 @@ impl SecretsService {
Some(user_id), Some(user_id),
) )
.await .await
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?; .map_err(|e| mcp_err_internal_logged("secrets_get", Some(user_id), e))?;
tracing::info!(
tool = "secrets_get",
?user_id,
elapsed_ms = t.elapsed().as_millis(),
"tool call ok",
);
let result = serde_json::json!({ field_name: value }); let result = serde_json::json!({ field_name: value });
let json = serde_json::to_string_pretty(&result).unwrap_or_default(); let json = serde_json::to_string_pretty(&result).unwrap_or_default();
Ok(CallToolResult::success(vec![Content::text(json)])) Ok(CallToolResult::success(vec![Content::text(json)]))
@@ -354,8 +447,16 @@ impl SecretsService {
Some(user_id), Some(user_id),
) )
.await .await
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?; .map_err(|e| mcp_err_internal_logged("secrets_get", Some(user_id), e))?;
let count = secrets.len();
tracing::info!(
tool = "secrets_get",
?user_id,
field_count = count,
elapsed_ms = t.elapsed().as_millis(),
"tool call ok",
);
let json = serde_json::to_string_pretty(&secrets).unwrap_or_default(); let json = serde_json::to_string_pretty(&secrets).unwrap_or_default();
Ok(CallToolResult::success(vec![Content::text(json)])) Ok(CallToolResult::success(vec![Content::text(json)]))
} }
@@ -364,14 +465,24 @@ impl SecretsService {
#[tool( #[tool(
description = "Add or upsert an entry with metadata and encrypted secret fields. \ description = "Add or upsert an entry with metadata and encrypted secret fields. \
Requires X-Encryption-Key header. \ Requires X-Encryption-Key header. \
Meta and secret values use 'key=value', 'key=@file', or 'key:=<json>' format." Meta and secret values use 'key=value', 'key=@file', or 'key:=<json>' format.",
annotations(title = "Add Secret Entry")
)] )]
async fn secrets_add( async fn secrets_add(
&self, &self,
Parameters(input): Parameters<AddInput>, Parameters(input): Parameters<AddInput>,
ctx: RequestContext<RoleServer>, ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, rmcp::ErrorData> { ) -> 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(&ctx)?;
tracing::info!(
tool = "secrets_add",
?user_id,
namespace = %input.namespace,
kind = %input.kind,
name = %input.name,
"tool call start",
);
let tags = input.tags.unwrap_or_default(); let tags = input.tags.unwrap_or_default();
let meta = input.meta.unwrap_or_default(); let meta = input.meta.unwrap_or_default();
@@ -391,22 +502,41 @@ impl SecretsService {
&user_key, &user_key,
) )
.await .await
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?; .map_err(|e| mcp_err_internal_logged("secrets_add", Some(user_id), e))?;
tracing::info!(
tool = "secrets_add",
?user_id,
namespace = %input.namespace,
kind = %input.kind,
name = %input.name,
elapsed_ms = t.elapsed().as_millis(),
"tool call ok",
);
let json = serde_json::to_string_pretty(&result).unwrap_or_default(); let json = serde_json::to_string_pretty(&result).unwrap_or_default();
Ok(CallToolResult::success(vec![Content::text(json)])) Ok(CallToolResult::success(vec![Content::text(json)]))
} }
#[tool( #[tool(
description = "Incrementally update an existing entry. Requires X-Encryption-Key header. \ description = "Incrementally update an existing entry. Requires X-Encryption-Key header. \
Only the fields you specify are changed; everything else is preserved." Only the fields you specify are changed; everything else is preserved.",
annotations(title = "Update Secret Entry")
)] )]
async fn secrets_update( async fn secrets_update(
&self, &self,
Parameters(input): Parameters<UpdateInput>, Parameters(input): Parameters<UpdateInput>,
ctx: RequestContext<RoleServer>, ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, rmcp::ErrorData> { ) -> 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(&ctx)?;
tracing::info!(
tool = "secrets_update",
?user_id,
namespace = %input.namespace,
kind = %input.kind,
name = %input.name,
"tool call start",
);
let add_tags = input.add_tags.unwrap_or_default(); let add_tags = input.add_tags.unwrap_or_default();
let remove_tags = input.remove_tags.unwrap_or_default(); let remove_tags = input.remove_tags.unwrap_or_default();
@@ -432,22 +562,42 @@ impl SecretsService {
&user_key, &user_key,
) )
.await .await
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?; .map_err(|e| mcp_err_internal_logged("secrets_update", Some(user_id), e))?;
tracing::info!(
tool = "secrets_update",
?user_id,
namespace = %input.namespace,
kind = %input.kind,
name = %input.name,
elapsed_ms = t.elapsed().as_millis(),
"tool call ok",
);
let json = serde_json::to_string_pretty(&result).unwrap_or_default(); let json = serde_json::to_string_pretty(&result).unwrap_or_default();
Ok(CallToolResult::success(vec![Content::text(json)])) Ok(CallToolResult::success(vec![Content::text(json)]))
} }
#[tool( #[tool(
description = "Delete one entry (specify namespace+kind+name) or bulk delete all \ description = "Delete one entry (specify namespace+kind+name) or bulk delete all \
entries matching namespace+kind. Use dry_run=true to preview." entries matching namespace+kind. Use dry_run=true to preview.",
annotations(title = "Delete Secret Entry", destructive_hint = true)
)] )]
async fn secrets_delete( async fn secrets_delete(
&self, &self,
Parameters(input): Parameters<DeleteInput>, Parameters(input): Parameters<DeleteInput>,
ctx: RequestContext<RoleServer>, ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, rmcp::ErrorData> { ) -> Result<CallToolResult, rmcp::ErrorData> {
let t = Instant::now();
let user_id = Self::user_id_from_ctx(&ctx)?; let user_id = Self::user_id_from_ctx(&ctx)?;
tracing::info!(
tool = "secrets_delete",
?user_id,
namespace = %input.namespace,
kind = input.kind.as_deref(),
name = input.name.as_deref(),
dry_run = input.dry_run.unwrap_or(false),
"tool call start",
);
let result = svc_delete( let result = svc_delete(
&self.pool, &self.pool,
@@ -460,46 +610,86 @@ impl SecretsService {
}, },
) )
.await .await
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?; .map_err(|e| mcp_err_internal_logged("secrets_delete", user_id, e))?;
tracing::info!(
tool = "secrets_delete",
?user_id,
namespace = %input.namespace,
elapsed_ms = t.elapsed().as_millis(),
"tool call ok",
);
let json = serde_json::to_string_pretty(&result).unwrap_or_default(); let json = serde_json::to_string_pretty(&result).unwrap_or_default();
Ok(CallToolResult::success(vec![Content::text(json)])) Ok(CallToolResult::success(vec![Content::text(json)]))
} }
#[tool( #[tool(
description = "View change history for an entry. Returns a list of versions with \ description = "View change history for an entry. Returns a list of versions with \
actions and timestamps." actions and timestamps.",
annotations(
title = "View Secret History",
read_only_hint = true,
idempotent_hint = true
)
)] )]
async fn secrets_history( async fn secrets_history(
&self, &self,
Parameters(input): Parameters<HistoryInput>, Parameters(input): Parameters<HistoryInput>,
_ctx: RequestContext<RoleServer>, ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, rmcp::ErrorData> { ) -> Result<CallToolResult, rmcp::ErrorData> {
let t = Instant::now();
let user_id = Self::user_id_from_ctx(&ctx)?;
tracing::info!(
tool = "secrets_history",
?user_id,
namespace = %input.namespace,
kind = %input.kind,
name = %input.name,
"tool call start",
);
let result = svc_history( let result = svc_history(
&self.pool, &self.pool,
&input.namespace, &input.namespace,
&input.kind, &input.kind,
&input.name, &input.name,
input.limit.unwrap_or(20), input.limit.unwrap_or(20),
None, user_id,
) )
.await .await
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?; .map_err(|e| mcp_err_internal_logged("secrets_history", user_id, e))?;
tracing::info!(
tool = "secrets_history",
?user_id,
elapsed_ms = t.elapsed().as_millis(),
"tool call ok",
);
let json = serde_json::to_string_pretty(&result).unwrap_or_default(); let json = serde_json::to_string_pretty(&result).unwrap_or_default();
Ok(CallToolResult::success(vec![Content::text(json)])) Ok(CallToolResult::success(vec![Content::text(json)]))
} }
#[tool( #[tool(
description = "Rollback an entry to a previous version. Requires X-Encryption-Key header. \ description = "Rollback an entry to a previous version. Requires X-Encryption-Key header. \
Omit to_version to restore the most recent snapshot." Omit to_version to restore the most recent snapshot.",
annotations(title = "Rollback Secret Entry", destructive_hint = true)
)] )]
async fn secrets_rollback( async fn secrets_rollback(
&self, &self,
Parameters(input): Parameters<RollbackInput>, Parameters(input): Parameters<RollbackInput>,
ctx: RequestContext<RoleServer>, ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, rmcp::ErrorData> { ) -> 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(&ctx)?;
tracing::info!(
tool = "secrets_rollback",
?user_id,
namespace = %input.namespace,
kind = %input.kind,
name = %input.name,
to_version = input.to_version,
"tool call start",
);
let result = svc_rollback( let result = svc_rollback(
&self.pool, &self.pool,
@@ -511,24 +701,44 @@ impl SecretsService {
Some(user_id), Some(user_id),
) )
.await .await
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?; .map_err(|e| mcp_err_internal_logged("secrets_rollback", Some(user_id), e))?;
tracing::info!(
tool = "secrets_rollback",
?user_id,
elapsed_ms = t.elapsed().as_millis(),
"tool call ok",
);
let json = serde_json::to_string_pretty(&result).unwrap_or_default(); let json = serde_json::to_string_pretty(&result).unwrap_or_default();
Ok(CallToolResult::success(vec![Content::text(json)])) Ok(CallToolResult::success(vec![Content::text(json)]))
} }
#[tool( #[tool(
description = "Export matching entries with decrypted secrets as JSON/TOML/YAML string. \ description = "Export matching entries with decrypted secrets as JSON/TOML/YAML string. \
Requires X-Encryption-Key header. Useful for backup or data migration." Requires X-Encryption-Key header. Useful for backup or data migration.",
annotations(
title = "Export Secrets",
read_only_hint = true,
idempotent_hint = true
)
)] )]
async fn secrets_export( async fn secrets_export(
&self, &self,
Parameters(input): Parameters<ExportInput>, Parameters(input): Parameters<ExportInput>,
ctx: RequestContext<RoleServer>, ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, rmcp::ErrorData> { ) -> 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(&ctx)?;
let tags = input.tags.unwrap_or_default(); let tags = input.tags.unwrap_or_default();
let format = input.format.as_deref().unwrap_or("json"); let format = input.format.as_deref().unwrap_or("json");
tracing::info!(
tool = "secrets_export",
?user_id,
namespace = input.namespace.as_deref(),
kind = input.kind.as_deref(),
format,
"tool call start",
);
let data = svc_export( let data = svc_export(
&self.pool, &self.pool,
@@ -544,29 +754,57 @@ impl SecretsService {
Some(&user_key), Some(&user_key),
) )
.await .await
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?; .map_err(|e| mcp_err_internal_logged("secrets_export", Some(user_id), e))?;
let serialized = format let fmt = format.parse::<ExportFormat>().map_err(|e| {
.parse::<secrets_core::models::ExportFormat>() tracing::warn!(
.and_then(|fmt| fmt.serialize(&data)) tool = "secrets_export",
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?; ?user_id,
error = %e,
"invalid export format"
);
rmcp::ErrorData::invalid_request(
"Invalid export format. Use json, toml, or yaml.",
None,
)
})?;
let serialized = fmt
.serialize(&data)
.map_err(|e| mcp_err_internal_logged("secrets_export", Some(user_id), e))?;
tracing::info!(
tool = "secrets_export",
?user_id,
entry_count = data.entries.len(),
elapsed_ms = t.elapsed().as_millis(),
"tool call ok",
);
Ok(CallToolResult::success(vec![Content::text(serialized)])) Ok(CallToolResult::success(vec![Content::text(serialized)]))
} }
#[tool( #[tool(
description = "Build the environment variable map from entry secrets with decrypted \ description = "Build the environment variable map from entry secrets with decrypted \
plaintext values. Requires X-Encryption-Key header. \ plaintext values. Requires X-Encryption-Key header. \
Returns a JSON object of VAR_NAME -> plaintext_value ready for injection." Returns a JSON object of VAR_NAME -> plaintext_value ready for injection.",
annotations(title = "Build Env Map", read_only_hint = true, idempotent_hint = true)
)] )]
async fn secrets_env_map( async fn secrets_env_map(
&self, &self,
Parameters(input): Parameters<EnvMapInput>, Parameters(input): Parameters<EnvMapInput>,
ctx: RequestContext<RoleServer>, ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, rmcp::ErrorData> { ) -> 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(&ctx)?;
let tags = input.tags.unwrap_or_default(); let tags = input.tags.unwrap_or_default();
let only_fields = input.only_fields.unwrap_or_default(); let only_fields = input.only_fields.unwrap_or_default();
tracing::info!(
tool = "secrets_env_map",
?user_id,
namespace = input.namespace.as_deref(),
kind = input.kind.as_deref(),
prefix = input.prefix.as_deref().unwrap_or(""),
"tool call start",
);
let env_map = secrets_core::service::env_map::build_env_map( let env_map = secrets_core::service::env_map::build_env_map(
&self.pool, &self.pool,
@@ -580,8 +818,16 @@ impl SecretsService {
Some(user_id), Some(user_id),
) )
.await .await
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?; .map_err(|e| mcp_err_internal_logged("secrets_env_map", Some(user_id), e))?;
let entry_count = env_map.len();
tracing::info!(
tool = "secrets_env_map",
?user_id,
entry_count,
elapsed_ms = t.elapsed().as_millis(),
"tool call ok",
);
let json = serde_json::to_string_pretty(&env_map).unwrap_or_default(); let json = serde_json::to_string_pretty(&env_map).unwrap_or_default();
Ok(CallToolResult::success(vec![Content::text(json)])) Ok(CallToolResult::success(vec![Content::text(json)]))
} }
@@ -593,13 +839,17 @@ impl SecretsService {
impl ServerHandler for SecretsService { impl ServerHandler for SecretsService {
fn get_info(&self) -> InitializeResult { fn get_info(&self) -> InitializeResult {
let mut info = InitializeResult::new(ServerCapabilities::builder().enable_tools().build()); let mut info = InitializeResult::new(ServerCapabilities::builder().enable_tools().build());
info.server_info = Implementation::new("secrets-mcp", env!("CARGO_PKG_VERSION")); info.server_info = Implementation::new("secrets-mcp", env!("CARGO_PKG_VERSION"))
info.protocol_version = ProtocolVersion::V_2025_03_26; .with_title("Secrets MCP")
.with_description(
"Secure cross-device secrets and configuration management with encrypted secret fields.",
);
info.protocol_version = ProtocolVersion::V_2025_06_18;
info.instructions = Some( info.instructions = Some(
"Manage cross-device secrets and configuration securely. \ "Manage cross-device secrets and configuration securely. \
Data is encrypted with your passphrase-derived key. \ Data is encrypted with your passphrase-derived key. \
Include your 64-char hex key in the X-Encryption-Key header for all read/write operations. \ Include your 64-char hex key in the X-Encryption-Key header for all read/write operations. \
Use secrets_search to discover entries (no key needed), \ Use secrets_search to discover entries (Bearer token required; encryption key not needed), \
secrets_get to decrypt secret values, \ secrets_get to decrypt secret values, \
and secrets_add/secrets_update to write encrypted secrets." and secrets_add/secrets_update to write encrypted secrets."
.to_string(), .to_string(),

View File

@@ -76,12 +76,22 @@ fn google_cfg(state: &AppState) -> Option<&OAuthConfig> {
} }
async fn current_user_id(session: &Session) -> Option<Uuid> { async fn current_user_id(session: &Session) -> Option<Uuid> {
session match session.get::<String>(SESSION_USER_ID).await {
.get::<String>(SESSION_USER_ID) Ok(opt) => match opt {
.await Some(s) => match Uuid::parse_str(&s) {
.ok() Ok(id) => Some(id),
.flatten() Err(e) => {
.and_then(|s| Uuid::parse_str(&s).ok()) tracing::warn!(error = %e, user_id_str = %s, "invalid user_id UUID in session");
None
}
},
None => None,
},
Err(e) => {
tracing::warn!(error = %e, "failed to read user_id from session");
None
}
}
} }
fn request_client_ip(headers: &HeaderMap, connect_info: ConnectInfo<SocketAddr>) -> Option<String> { fn request_client_ip(headers: &HeaderMap, connect_info: ConnectInfo<SocketAddr>) -> Option<String> {
@@ -112,11 +122,18 @@ fn request_user_agent(headers: &HeaderMap) -> Option<String> {
pub fn web_router() -> Router<AppState> { pub fn web_router() -> Router<AppState> {
Router::new() Router::new()
.route("/robots.txt", get(robots_txt))
.route("/llms.txt", get(llms_txt))
.route("/ai.txt", get(ai_txt))
.route("/favicon.svg", get(favicon_svg)) .route("/favicon.svg", get(favicon_svg))
.route( .route(
"/favicon.ico", "/favicon.ico",
get(|| async { Redirect::permanent("/favicon.svg") }), get(|| async { Redirect::permanent("/favicon.svg") }),
) )
.route(
"/.well-known/oauth-protected-resource",
get(oauth_protected_resource_metadata),
)
.route("/", get(login_page)) .route("/", get(login_page))
.route("/auth/google", get(auth_google)) .route("/auth/google", get(auth_google))
.route("/auth/google/callback", get(auth_google_callback)) .route("/auth/google/callback", get(auth_google_callback))
@@ -135,6 +152,33 @@ pub fn web_router() -> Router<AppState> {
.route("/api/apikey/regenerate", post(api_apikey_regenerate)) .route("/api/apikey/regenerate", post(api_apikey_regenerate))
} }
fn text_asset_response(content: &'static str, content_type: &'static str) -> Response {
Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, content_type)
.header(header::CACHE_CONTROL, "public, max-age=86400")
.body(Body::from(content))
.expect("text asset response")
}
async fn robots_txt() -> Response {
text_asset_response(
include_str!("../static/robots.txt"),
"text/plain; charset=utf-8",
)
}
async fn llms_txt() -> Response {
text_asset_response(
include_str!("../static/llms.txt"),
"text/markdown; charset=utf-8",
)
}
async fn ai_txt() -> Response {
llms_txt().await
}
async fn favicon_svg() -> Response { async fn favicon_svg() -> Response {
Response::builder() Response::builder()
.status(StatusCode::OK) .status(StatusCode::OK)
@@ -173,7 +217,10 @@ async fn auth_google(
session session
.insert(SESSION_OAUTH_STATE, &oauth_state) .insert(SESSION_OAUTH_STATE, &oauth_state)
.await .await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; .map_err(|e| {
tracing::error!(error = %e, "failed to insert oauth_state into session");
StatusCode::INTERNAL_SERVER_ERROR
})?;
let url = google_auth_url(config, &oauth_state); let url = google_auth_url(config, &oauth_state);
Ok(Redirect::to(&url).into_response()) Ok(Redirect::to(&url).into_response())
@@ -247,10 +294,10 @@ where
return Ok(Redirect::to("/?error=oauth_missing_state").into_response()); return Ok(Redirect::to("/?error=oauth_missing_state").into_response());
}; };
let expected_state: Option<String> = session let expected_state: Option<String> = session.get(SESSION_OAUTH_STATE).await.map_err(|e| {
.get(SESSION_OAUTH_STATE) tracing::error!(provider, error = %e, "failed to read oauth_state from session");
.await StatusCode::INTERNAL_SERVER_ERROR
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; })?;
if expected_state.as_deref() != Some(returned_state) { if expected_state.as_deref() != Some(returned_state) {
tracing::warn!( tracing::warn!(
provider, provider,
@@ -259,7 +306,9 @@ where
); );
return Ok(Redirect::to("/?error=oauth_state").into_response()); return Ok(Redirect::to("/?error=oauth_state").into_response());
} }
session.remove::<String>(SESSION_OAUTH_STATE).await.ok(); if let Err(e) = session.remove::<String>(SESSION_OAUTH_STATE).await {
tracing::warn!(provider, error = %e, "failed to remove oauth_state from session");
}
let config = match provider { let config = match provider {
"google" => state "google" => state
@@ -276,17 +325,25 @@ where
StatusCode::INTERNAL_SERVER_ERROR StatusCode::INTERNAL_SERVER_ERROR
})?; })?;
let bind_mode: bool = session let bind_mode: bool = match session.get::<bool>(SESSION_OAUTH_BIND_MODE).await {
.get(SESSION_OAUTH_BIND_MODE) Ok(v) => v.unwrap_or(false),
.await Err(e) => {
.unwrap_or(None) tracing::error!(
.unwrap_or(false); provider,
error = %e,
"failed to read oauth_bind_mode from session"
);
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
};
if bind_mode { if bind_mode {
let user_id = current_user_id(session) let user_id = current_user_id(session)
.await .await
.ok_or(StatusCode::UNAUTHORIZED)?; .ok_or(StatusCode::UNAUTHORIZED)?;
session.remove::<bool>(SESSION_OAUTH_BIND_MODE).await.ok(); if let Err(e) = session.remove::<bool>(SESSION_OAUTH_BIND_MODE).await {
tracing::warn!(provider, error = %e, "failed to remove oauth_bind_mode from session after bind");
}
let profile = OAuthProfile { let profile = OAuthProfile {
provider: user_info.provider, provider: user_info.provider,
@@ -321,19 +378,28 @@ where
StatusCode::INTERNAL_SERVER_ERROR StatusCode::INTERNAL_SERVER_ERROR
})?; })?;
// Ensure the user has an API key (auto-creates on first login).
if let Err(e) = ensure_api_key(&state.pool, user.id).await {
tracing::warn!(error = %e, "failed to ensure api key for user");
}
session session
.insert(SESSION_USER_ID, user.id.to_string()) .insert(SESSION_USER_ID, user.id.to_string())
.await .await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; .map_err(|e| {
tracing::error!(
error = %e,
user_id = %user.id,
"failed to insert user_id into session after OAuth"
);
StatusCode::INTERNAL_SERVER_ERROR
})?;
session session
.insert(SESSION_LOGIN_PROVIDER, &provider) .insert(SESSION_LOGIN_PROVIDER, &provider)
.await .await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; .map_err(|e| {
tracing::error!(
provider,
error = %e,
"failed to insert login_provider into session after OAuth"
);
StatusCode::INTERNAL_SERVER_ERROR
})?;
log_login( log_login(
&state.pool, &state.pool,
@@ -351,7 +417,9 @@ where
// ── Logout ──────────────────────────────────────────────────────────────────── // ── Logout ────────────────────────────────────────────────────────────────────
async fn auth_logout(session: Session) -> impl IntoResponse { async fn auth_logout(session: Session) -> impl IntoResponse {
session.flush().await.ok(); if let Err(e) = session.flush().await {
tracing::warn!(error = %e, "failed to flush session on logout");
}
Redirect::to("/") Redirect::to("/")
} }
@@ -365,10 +433,10 @@ async fn dashboard(
return Ok(Redirect::to("/").into_response()); return Ok(Redirect::to("/").into_response());
}; };
let user = match get_user_by_id(&state.pool, user_id) let user = match get_user_by_id(&state.pool, user_id).await.map_err(|e| {
.await tracing::error!(error = %e, %user_id, "failed to load user for dashboard");
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? StatusCode::INTERNAL_SERVER_ERROR
{ })? {
Some(u) => u, Some(u) => u,
None => return Ok(Redirect::to("/").into_response()), None => return Ok(Redirect::to("/").into_response()),
}; };
@@ -392,10 +460,10 @@ async fn audit_page(
return Ok(Redirect::to("/").into_response()); return Ok(Redirect::to("/").into_response());
}; };
let user = match get_user_by_id(&state.pool, user_id) let user = match get_user_by_id(&state.pool, user_id).await.map_err(|e| {
.await tracing::error!(error = %e, %user_id, "failed to load user for audit page");
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? StatusCode::INTERNAL_SERVER_ERROR
{ })? {
Some(u) => u, Some(u) => u,
None => return Ok(Redirect::to("/").into_response()), None => return Ok(Redirect::to("/").into_response()),
}; };
@@ -440,7 +508,10 @@ async fn account_bind_google(
session session
.insert(SESSION_OAUTH_BIND_MODE, true) .insert(SESSION_OAUTH_BIND_MODE, true)
.await .await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; .map_err(|e| {
tracing::error!(error = %e, "failed to insert oauth_bind_mode into session");
StatusCode::INTERNAL_SERVER_ERROR
})?;
let redirect_uri = format!("{}/account/bind/google/callback", state.base_url); let redirect_uri = format!("{}/account/bind/google/callback", state.base_url);
let mut cfg = state let mut cfg = state
@@ -449,7 +520,13 @@ async fn account_bind_google(
.ok_or(StatusCode::SERVICE_UNAVAILABLE)?; .ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
cfg.redirect_uri = redirect_uri; cfg.redirect_uri = redirect_uri;
let st = random_state(); let st = random_state();
session.insert(SESSION_OAUTH_STATE, &st).await.ok(); if let Err(e) = session.insert(SESSION_OAUTH_STATE, &st).await {
tracing::error!(error = %e, "failed to insert oauth_state for account bind flow");
if let Err(rm) = session.remove::<bool>(SESSION_OAUTH_BIND_MODE).await {
tracing::warn!(error = %rm, "failed to roll back oauth_bind_mode after oauth_state insert failure");
}
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
Ok(Redirect::to(&google_auth_url(&cfg, &st)).into_response()) Ok(Redirect::to(&google_auth_url(&cfg, &st)).into_response())
} }
@@ -493,7 +570,10 @@ async fn account_unbind(
let current_login_provider = session let current_login_provider = session
.get::<String>(SESSION_LOGIN_PROVIDER) .get::<String>(SESSION_LOGIN_PROVIDER)
.await .await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; .map_err(|e| {
tracing::error!(error = %e, "failed to read login_provider from session");
StatusCode::INTERNAL_SERVER_ERROR
})?;
unbind_oauth_account( unbind_oauth_account(
&state.pool, &state.pool,
@@ -533,7 +613,10 @@ async fn api_key_salt(
let user = get_user_by_id(&state.pool, user_id) let user = get_user_by_id(&state.pool, user_id)
.await .await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? .map_err(|e| {
tracing::error!(error = %e, %user_id, "failed to load user for key-salt API");
StatusCode::INTERNAL_SERVER_ERROR
})?
.ok_or(StatusCode::UNAUTHORIZED)?; .ok_or(StatusCode::UNAUTHORIZED)?;
if user.key_salt.is_none() { if user.key_salt.is_none() {
@@ -577,10 +660,17 @@ async fn api_key_setup(
.await .await
.ok_or(StatusCode::UNAUTHORIZED)?; .ok_or(StatusCode::UNAUTHORIZED)?;
let salt = hex::decode_hex(&body.salt).map_err(|_| StatusCode::BAD_REQUEST)?; let salt = hex::decode_hex(&body.salt).map_err(|e| {
let key_check = hex::decode_hex(&body.key_check).map_err(|_| StatusCode::BAD_REQUEST)?; tracing::warn!(error = %e, "invalid hex in key-setup salt");
StatusCode::BAD_REQUEST
})?;
let key_check = hex::decode_hex(&body.key_check).map_err(|e| {
tracing::warn!(error = %e, "invalid hex in key-setup key_check");
StatusCode::BAD_REQUEST
})?;
if salt.len() != 32 { if salt.len() != 32 {
tracing::warn!(salt_len = salt.len(), "key-setup salt must be 32 bytes");
return Err(StatusCode::BAD_REQUEST); return Err(StatusCode::BAD_REQUEST);
} }
@@ -609,9 +699,10 @@ async fn api_apikey_get(
.await .await
.ok_or(StatusCode::UNAUTHORIZED)?; .ok_or(StatusCode::UNAUTHORIZED)?;
let api_key = ensure_api_key(&state.pool, user_id) let api_key = ensure_api_key(&state.pool, user_id).await.map_err(|e| {
.await tracing::error!(error = %e, %user_id, "ensure_api_key failed");
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; StatusCode::INTERNAL_SERVER_ERROR
})?;
Ok(Json(ApiKeyResponse { api_key })) Ok(Json(ApiKeyResponse { api_key }))
} }
@@ -626,11 +717,36 @@ async fn api_apikey_regenerate(
let api_key = regenerate_api_key(&state.pool, user_id) let api_key = regenerate_api_key(&state.pool, user_id)
.await .await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; .map_err(|e| {
tracing::error!(error = %e, %user_id, "regenerate_api_key failed");
StatusCode::INTERNAL_SERVER_ERROR
})?;
Ok(Json(ApiKeyResponse { api_key })) Ok(Json(ApiKeyResponse { api_key }))
} }
// ── OAuth / Well-known ────────────────────────────────────────────────────────
/// RFC 9728 — OAuth 2.0 Protected Resource Metadata.
///
/// Advertises that this server accepts Bearer tokens in the `Authorization`
/// header. We deliberately omit `authorization_servers` because this service
/// issues its own API keys (no external OAuth AS is involved). MCP clients
/// that probe this endpoint will see the resource identifier and stop looking
/// for a delegated OAuth flow.
async fn oauth_protected_resource_metadata(State(state): State<AppState>) -> impl IntoResponse {
let body = serde_json::json!({
"resource": state.base_url,
"bearer_methods_supported": ["header"],
"resource_documentation": format!("{}/dashboard", state.base_url),
});
(
StatusCode::OK,
[(header::CONTENT_TYPE, "application/json")],
axum::Json(body),
)
}
// ── Helper ──────────────────────────────────────────────────────────────────── // ── Helper ────────────────────────────────────────────────────────────────────
fn render_template<T: Template>(tmpl: T) -> Result<Response, StatusCode> { fn render_template<T: Template>(tmpl: T) -> Result<Response, StatusCode> {
@@ -642,6 +758,7 @@ fn render_template<T: Template>(tmpl: T) -> Result<Response, StatusCode> {
} }
fn format_audit_target(namespace: &str, kind: &str, name: &str) -> String { fn format_audit_target(namespace: &str, kind: &str, name: &str) -> String {
// Auth events reuse kind/name as a provider-scoped target, not an entry identity.
if namespace == "auth" { if namespace == "auth" {
format!("{}/{}", kind, name) format!("{}/{}", kind, name)
} else { } else {

View File

@@ -0,0 +1,23 @@
# Secrets MCP
> 给 AI 与自动化工具的简要说明。本站是 **secrets-mcp**Streamable HTTP **MCP**Model Context Protocol与 **Web 控制台** 的组合,用于在多租户场景下存储条目元数据与加密后的秘密字段;持久化在 PostgreSQL。用户通过 OAuth如已配置登录 WebMCP 调用使用 API Key 与加密相关请求头。
## 不应抓取或索引的内容
- **`/mcp`**MCP 流式 HTTP 端点JSON-RPC 等),**不是** HTML 文档,也不适合作为公开知识库来源。
- **`/api/*`**:会话或 API Key 相关的 HTTP API。
- **`/dashboard`、`/audit`、`/auth/*`、`/account/*`**:需浏览器会话,属于用户私有界面与 OAuth 流程。
## 给 AI 助手的实用提示
- 向用户说明连接方式时MCP 基址为 `{BASE_URL}/mcp``BASE_URL` 由部署方设置),通常需要 `Authorization: Bearer <api_key>`;读写加密秘密时还需按部署文档传递 `X-Encryption-Key` 等头(与客户端模式有关)。
- **不要编造**本实例的数据库 URL、OAuth 密钥、回调地址或任何凭据;一律以用户环境变量与运维文档为准。
- Web 端在浏览器内用密码短语派生密钥完成端到端加密MCP 路径下服务端可能在请求周期内临时使用客户端提供的密钥处理密文(架构细节见项目 README「加密架构」
## 延伸阅读
- 开源仓库中的 `README.md`、`AGENTS.md`(若可访问)包含环境变量、表结构与运维约定。
## 关于本文件
- 遵循常见的 **`/llms.txt`** 约定,便于人类与 LLM 快速了解站点性质与抓取边界;同文可在 **`/ai.txt`** 获取。

View File

@@ -0,0 +1,27 @@
# Secrets MCP — robots.txt
# 本站为需登录的私密控制台与 MCP API以下路径请勿抓取以免浪费配额并避免误索引敏感端点。
# This host serves an authenticated dashboard and machine APIs; please skip crawling the paths below.
User-agent: *
Disallow: /mcp
Disallow: /api/
Disallow: /dashboard
Disallow: /audit
Disallow: /auth/
Disallow: /account/
# 面向 AI / LLM 的机器可读站点说明Markdown/llms.txt
# Human & AI-readable site summary: /llms.txt (also /ai.txt)
User-agent: GPTBot
User-agent: Google-Extended
User-agent: anthropic-ai
User-agent: Claude-Web
User-agent: PerplexityBot
User-agent: Bytespider
Disallow: /mcp
Disallow: /api/
Disallow: /dashboard
Disallow: /audit
Disallow: /auth/
Disallow: /account/

View File

@@ -2,6 +2,7 @@
# 复制此文件为 .env 并填写真实值 # 复制此文件为 .env 并填写真实值
# ─── 数据库 ─────────────────────────────────────────────────────────── # ─── 数据库 ───────────────────────────────────────────────────────────
# Web 会话tower-sessions与业务数据共用此库启动时会自动 migrate 会话表,无需额外环境变量。
SECRETS_DATABASE_URL=postgres://postgres:PASSWORD@HOST:PORT/secrets-mcp SECRETS_DATABASE_URL=postgres://postgres:PASSWORD@HOST:PORT/secrets-mcp
# ─── 服务地址 ───────────────────────────────────────────────────────── # ─── 服务地址 ─────────────────────────────────────────────────────────

View File

@@ -0,0 +1,22 @@
-- Run against prod BEFORE deploying secrets-mcp with FK migration.
-- Requires: write access to SECRETS_DATABASE_URL.
-- Example: psql "$SECRETS_DATABASE_URL" -v ON_ERROR_STOP=1 -f scripts/cleanup-orphan-user-ids.sql
BEGIN;
UPDATE entries
SET user_id = NULL
WHERE user_id IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM users u WHERE u.id = entries.user_id);
UPDATE entries_history
SET user_id = NULL
WHERE user_id IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM users u WHERE u.id = entries_history.user_id);
UPDATE audit_log
SET user_id = NULL
WHERE user_id IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM users u WHERE u.id = audit_log.user_id);
COMMIT;