Compare commits

...

4 Commits

Author SHA1 Message Date
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
11 changed files with 831 additions and 84 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`)。
## 项目结构 ## 项目结构
@@ -111,7 +112,7 @@ oauth_accounts (
- 错误:业务层 `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`)保持同步,鉴权以请求扩展中的用户上下文为准。
@@ -153,7 +154,7 @@ 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`。 |

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.10" version = "0.2.0"
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

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "secrets-mcp" name = "secrets-mcp"
version = "0.1.10" version = "0.2.0"
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,249 @@
use std::net::SocketAddr;
use std::time::Instant;
use axum::{
body::{Body, Bytes, to_bytes},
extract::{ConnectInfo, Request},
http::{
HeaderMap, Method,
header::{CONTENT_LENGTH, CONTENT_TYPE, USER_AGENT},
},
middleware::Next,
response::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");
// Reconstruct with empty body; request was consumed — return 500.
// This branch is highly unlikely in practice.
let resp = next.run(Request::from_parts(parts, Body::empty())).await;
return resp;
}
}
}
}
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.
@@ -250,14 +299,29 @@ struct EnvMapInput {
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. Returns entries with metadata and \
secret field names (not values). Use secrets_get to decrypt secret values." 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 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_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,
@@ -274,7 +338,7 @@ impl SecretsService {
}, },
) )
.await .await
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?; .map_err(|e| mcp_err_internal_logged("secrets_search", 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,22 +610,44 @@ 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)?; 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,
@@ -485,22 +657,39 @@ impl SecretsService {
user_id, 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,
@@ -512,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,
@@ -545,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,
@@ -581,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)]))
} }
@@ -594,8 +839,12 @@ 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. \

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,
@@ -324,11 +381,25 @@ where
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,
@@ -346,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("/")
} }
@@ -360,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()),
}; };
@@ -387,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()),
}; };
@@ -435,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
@@ -444,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())
} }
@@ -488,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,
@@ -528,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() {
@@ -572,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);
} }
@@ -604,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 }))
} }
@@ -621,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> {

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
# ─── 服务地址 ───────────────────────────────────────────────────────── # ─── 服务地址 ─────────────────────────────────────────────────────────