feat(web): manage MCP HTTP access from settings

This commit is contained in:
Hand Sonic authored and GitHub committed 2026-09-26 00:29:23 +08:00
1 parent 705ea7464d
commit fc0d576f6d
29 files changed
+1040 -159

No files matched your search

+5
View File
@@ -137,6 +137,11 @@ pub async fn setup(State(state): State<Arc<WebState>>, Json(body): Json<LoginReq
// Update in-memory state
*state.password_hash.write().await = Some(hash);
if state.migration_ready.load(std::sync::atomic::Ordering::Acquire) {
if let Err(error) = state.web_mcp.reload(&state.app.storage, true).await {
log::error!("Web MCP remained disabled after password setup: {error}");
}
}
// Auto-login: create session
let token = uuid::Uuid::new_v4().to_string();
+3
View File
@@ -53,6 +53,9 @@ const BLOCKED_EXACT: &[&str] = &[
"tunnel-profiles/save",
// 已存连接凭据解密出口
"app-settings/config/decrypt",
// 演示实例不得开放可访问全部连接的 MCP bearer token
"app-settings/mcp-http",
"app-settings/mcp-http/rotate-token",
// 读取服务器本地 ~/.ssh/config
"ssh/config-hosts",
// 插件数据访问授权写入(插件读取已存连接数据的许可)
+39 -51
View File
@@ -5,6 +5,7 @@ mod routes;
mod sse;
mod ssh_prompt;
mod state;
mod web_mcp;
use std::collections::{HashMap, HashSet};
use std::net::SocketAddr;
@@ -17,20 +18,21 @@ use axum::extract::DefaultBodyLimit;
use axum::http::{Request, StatusCode, Uri};
use axum::middleware;
use axum::response::{IntoResponse, Redirect, Response};
use axum::routing::{delete, get, post};
use axum::routing::{delete, get, post, put};
use axum::Router;
use dbx_core::connection::AppState;
use dbx_core::persistence::secret_codec::SecretKeyPolicy;
use dbx_core::sql_dialect::dialect_loader::{register_core_dialects, DialectPluginLoader, DialectRegistry};
use dbx_core::sql_dialect::hot_reload::DialectHotReload;
use dbx_core::storage::Storage;
use dbx_mcp::{streamable_http_router, DbxBackend, HttpAuth, LocalBackend};
use dbx_mcp::{streamable_http_router, DbxBackend, LocalBackend};
use state::WebState;
use std::sync::atomic::{AtomicBool, Ordering};
use tokio::sync::RwLock;
use tower_http::compression::predicate::{DefaultPredicate, NotForContentType, Predicate};
use tower_http::compression::CompressionLayer;
use utoipa::OpenApi;
use web_mcp::WebMcpRuntime;
const XLSX_CONTENT_TYPE: &str = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
const DATA_GRID_EXTRACTOR_BODY_LIMIT_BYTES: usize = 96 * 1024 * 1024;
@@ -106,6 +108,17 @@ async fn migration_gate(
next.run(request).await
}
async fn web_mcp_demo_gate(
state: axum::extract::State<Arc<WebState>>,
request: Request<axum::body::Body>,
next: axum::middleware::Next,
) -> Response {
if state.demo_mode {
return StatusCode::FORBIDDEN.into_response();
}
next.run(request).await
}
async fn storage_migration_ready(app: &Arc<AppState>) -> bool {
app.storage.inspect_data_migration().await.map(|status| status.is_ready()).unwrap_or(false)
}
@@ -271,54 +284,16 @@ fn mount_static_assets(mut app: Router, public_base_path: &str, source: Option<S
app
}
/// Builds the native Web MCP endpoint. It is intentionally opt-in: exposing a
/// token-bearing MCP server on a Web listener must never happen merely because
/// DBX Web itself was started.
fn web_mcp_router(web_state: &Arc<WebState>) -> Result<Option<Router>, String> {
let token = web_mcp_token()?;
let Some(token) = token else {
return Ok(None);
};
let allowed_hosts = comma_separated_env("DBX_WEB_MCP_ALLOWED_HOSTS");
if allowed_hosts.is_empty() {
return Err("DBX_WEB_MCP_ALLOWED_HOSTS is required when DBX Web MCP is enabled".into());
}
let allowed_origins = comma_separated_env("DBX_WEB_MCP_ALLOWED_ORIGINS");
let auth = HttpAuth::new(token, allowed_origins, false)?;
/// Builds the native Web MCP endpoint. The route remains mounted while the
/// feature is disabled so an authenticated settings action can enable it
/// without restarting the Web process; the shared auth middleware returns 404
/// until a token is configured.
fn web_mcp_router(web_state: &Arc<WebState>) -> Result<Router, String> {
let auth = web_state.web_mcp.auth();
let backend: Arc<dyn DbxBackend> =
Arc::new(LocalBackend::from_app_state(web_state.app.clone(), web_state.data_dir.clone()));
Ok(Some(streamable_http_router(backend, "/mcp", auth, allowed_hosts, true)))
}
fn web_mcp_token() -> Result<Option<String>, String> {
let inline_token = std::env::var("DBX_WEB_MCP_TOKEN").ok();
let token_file = std::env::var("DBX_WEB_MCP_TOKEN_FILE").ok();
match (inline_token, token_file) {
(Some(_), Some(_)) => Err("set only one of DBX_WEB_MCP_TOKEN or DBX_WEB_MCP_TOKEN_FILE".into()),
(Some(token), None) if !token.trim().is_empty() => Ok(Some(token)),
(Some(_), None) => Err("DBX_WEB_MCP_TOKEN must not be empty".into()),
(None, Some(path)) => std::fs::read_to_string(&path)
.map_err(|error| format!("failed to read DBX_WEB_MCP_TOKEN_FILE: {error}"))
.map(|token| token.trim_end_matches(['\r', '\n']).to_owned())
.and_then(|token| {
(!token.is_empty()).then_some(token).ok_or_else(|| "DBX_WEB_MCP_TOKEN_FILE is empty".into())
})
.map(Some),
(None, None) => Ok(None),
}
}
fn comma_separated_env(name: &str) -> Vec<String> {
std::env::var(name)
.ok()
.into_iter()
.flat_map(|value| {
value.split(',').map(str::trim).filter(|value| !value.is_empty()).map(ToOwned::to_owned).collect::<Vec<_>>()
})
.collect()
streamable_http_router(backend, "/mcp", auth, web_state.web_mcp.allowed_hosts(), true)
}
#[cfg(feature = "mq-admin")]
@@ -481,6 +456,13 @@ async fn serve() {
let demo_mode = demo::demo_mode_from_env();
let migration_ready = storage_migration_ready(&app_state).await;
let web_mcp = Arc::new(if migration_ready {
WebMcpRuntime::load(&app_state.storage, !password_disabled && password_hash.is_some())
.await
.expect("Invalid DBX Web MCP configuration")
} else {
WebMcpRuntime::disabled()
});
let web_state = Arc::new(WebState {
app: app_state,
data_dir,
@@ -499,6 +481,7 @@ async fn serve() {
export_files: RwLock::new(HashMap::new()),
ssh_prompts: Arc::new(ssh_prompt::SshPromptHub::new()),
migration_ready: Arc::new(AtomicBool::new(migration_ready)),
web_mcp,
});
ssh_prompt::install_web_ssh_prompt_bridge(web_state.ssh_prompts.clone());
@@ -1310,6 +1293,8 @@ async fn serve() {
get(routes::app_settings::load_mcp_global_policy).put(routes::app_settings::save_mcp_global_policy),
)
.route("/app-settings/mcp-http-status", get(routes::app_settings::load_web_mcp_http_status))
.route("/app-settings/mcp-http", put(routes::app_settings::save_web_mcp_http_settings))
.route("/app-settings/mcp-http/rotate-token", post(routes::app_settings::rotate_web_mcp_token))
.route(
"/app-settings/max-agent-turns",
get(routes::app_settings::load_max_agent_turns).put(routes::app_settings::save_max_agent_turns),
@@ -1373,10 +1358,13 @@ async fn serve() {
.layer(CompressionLayer::new().compress_when(web_compression_predicate()))
.layer(tower_http::trace::TraceLayer::new_for_http());
if let Some(mcp_router) = web_mcp_router(&web_state).expect("Invalid DBX Web MCP configuration") {
app = app.merge(mcp_router.layer(middleware::from_fn_with_state(web_state.clone(), migration_gate)));
tracing::info!("DBX Web MCP is enabled at /mcp");
}
let mcp_router = web_mcp_router(&web_state).expect("Invalid DBX Web MCP configuration");
app = app.merge(
mcp_router
.layer(middleware::from_fn_with_state(web_state.clone(), web_mcp_demo_gate))
.layer(middleware::from_fn_with_state(web_state.clone(), migration_gate)),
);
tracing::info!("DBX Web MCP endpoint is available at /mcp when enabled");
let static_dir = std::env::var_os("DBX_STATIC_DIR").map(std::path::PathBuf::from);
// DBX_STATIC_DIR always wins (frontend development); otherwise serve the
+47 -31
View File
@@ -3,6 +3,9 @@ use std::sync::Arc;
use aes_gcm::aead::Aead;
use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
use axum::extract::State;
use axum::http::header;
use axum::http::HeaderMap;
use axum::response::IntoResponse;
use axum::Json;
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use dbx_core::storage::{McpGlobalPolicy, McpGlobalPolicyState};
@@ -12,6 +15,7 @@ use sha2::Sha256;
use crate::error::AppError;
use crate::state::WebState;
use crate::web_mcp::{UpdateWebMcpRequest, WebMcpHttpStatus};
const CONFIG_PBKDF2_ITERATIONS: u32 = 100_000;
@@ -65,41 +69,53 @@ pub async fn save_mcp_global_policy(
Ok(Json(()))
}
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WebMcpHttpStatus {
pub enabled: bool,
pub endpoint_path: String,
pub token_source: Option<&'static str>,
pub allowed_hosts: Vec<String>,
pub allowed_origins: Vec<String>,
}
pub async fn load_web_mcp_http_status(State(state): State<Arc<WebState>>) -> Json<WebMcpHttpStatus> {
let token_source = match (std::env::var_os("DBX_WEB_MCP_TOKEN"), std::env::var_os("DBX_WEB_MCP_TOKEN_FILE")) {
(Some(_), None) => Some("environment"),
(None, Some(_)) => Some("file"),
_ => None,
};
pub async fn load_web_mcp_http_status(State(state): State<Arc<WebState>>) -> impl IntoResponse {
let endpoint_path =
if state.public_base_path == "/" { "/mcp".to_string() } else { format!("{}/mcp", state.public_base_path) };
Json(WebMcpHttpStatus {
enabled: token_source.is_some(),
endpoint_path,
token_source,
allowed_hosts: comma_separated_env("DBX_WEB_MCP_ALLOWED_HOSTS"),
allowed_origins: comma_separated_env("DBX_WEB_MCP_ALLOWED_ORIGINS"),
})
let management_available =
!state.password_disabled && state.password_hash.read().await.is_some() && !state.demo_mode;
let mut status = state.web_mcp.status(endpoint_path, management_available);
if state.demo_mode {
status.enabled = false;
}
web_mcp_status_response(status)
}
fn comma_separated_env(name: &str) -> Vec<String> {
std::env::var(name)
.ok()
.into_iter()
.flat_map(|value| {
value.split(',').map(str::trim).filter(|value| !value.is_empty()).map(ToOwned::to_owned).collect::<Vec<_>>()
})
.collect()
pub async fn save_web_mcp_http_settings(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(request): Json<UpdateWebMcpRequest>,
) -> Result<impl IntoResponse, AppError> {
ensure_web_mcp_management_allowed(&state, &headers).await?;
state.web_mcp.update(&state.app.storage, request).await.map_err(AppError::bad_request)?;
let endpoint_path =
if state.public_base_path == "/" { "/mcp".to_string() } else { format!("{}/mcp", state.public_base_path) };
Ok(web_mcp_status_response(state.web_mcp.status(endpoint_path, true)))
}
pub async fn rotate_web_mcp_token(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
) -> Result<impl IntoResponse, AppError> {
ensure_web_mcp_management_allowed(&state, &headers).await?;
state.web_mcp.rotate(&state.app.storage).await.map_err(AppError::bad_request)?;
let endpoint_path =
if state.public_base_path == "/" { "/mcp".to_string() } else { format!("{}/mcp", state.public_base_path) };
Ok(web_mcp_status_response(state.web_mcp.status(endpoint_path, true)))
}
fn web_mcp_status_response(status: WebMcpHttpStatus) -> impl IntoResponse {
([(header::CACHE_CONTROL, "no-store")], Json(status))
}
async fn ensure_web_mcp_management_allowed(state: &WebState, headers: &HeaderMap) -> Result<(), AppError> {
if state.demo_mode || state.password_disabled || state.password_hash.read().await.is_none() {
return Err(AppError::forbidden("Web MCP management requires password-protected DBX Web"));
}
if headers.get("x-dbx-mcp-settings").and_then(|value| value.to_str().ok()) != Some("1") {
return Err(AppError::forbidden("Web MCP management requires a same-origin settings request"));
}
Ok(())
}
#[derive(Deserialize)]
+6
View File
@@ -19,6 +19,12 @@ pub async fn start(
Ok(report) => {
let ready =
state.app.storage.inspect_data_migration().await.map(|status| status.is_ready()).unwrap_or(false);
if ready {
let allow_managed = !state.password_disabled && state.password_hash.read().await.is_some();
if let Err(error) = state.web_mcp.reload(&state.app.storage, allow_managed).await {
log::error!("Web MCP remained disabled after data migration: {error}");
}
}
state.migration_ready.store(ready, std::sync::atomic::Ordering::Release);
Ok(Json(report))
}
+1
View File
@@ -1574,6 +1574,7 @@ mod tests {
export_files: RwLock::new(HashMap::new()),
ssh_prompts: Arc::new(crate::ssh_prompt::SshPromptHub::new()),
migration_ready: Arc::new(std::sync::atomic::AtomicBool::new(true)),
web_mcp: Arc::new(crate::web_mcp::WebMcpRuntime::disabled()),
});
(state, dir)
}
+2
View File
@@ -48,6 +48,7 @@ pub struct WebState {
pub export_files: RwLock<HashMap<String, WebExportFile>>,
pub ssh_prompts: Arc<crate::ssh_prompt::SshPromptHub>,
pub migration_ready: Arc<AtomicBool>,
pub web_mcp: Arc<crate::web_mcp::WebMcpRuntime>,
}
impl WebState {
@@ -76,6 +77,7 @@ impl WebState {
export_files: RwLock::new(HashMap::new()),
ssh_prompts: Arc::new(crate::ssh_prompt::SshPromptHub::new()),
migration_ready: Arc::new(AtomicBool::new(true)),
web_mcp: Arc::new(crate::web_mcp::WebMcpRuntime::disabled()),
}
}
}
+417
View File
@@ -0,0 +1,417 @@
use std::{env, sync::RwLock};
use dbx_core::storage::{Storage, WebMcpSettings};
use dbx_mcp::HttpAuth;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
const SECRET_NAMESPACE: &str = "dbx.global";
const SECRET_KEY: &str = "web_mcp_token";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TokenSource {
Environment,
File,
Managed,
None,
}
struct DeploymentConfig {
token: String,
source: TokenSource,
allowed_hosts: Vec<String>,
allowed_origins: Vec<String>,
}
impl TokenSource {
fn as_str(self) -> Option<&'static str> {
match self {
Self::Environment => Some("environment"),
Self::File => Some("file"),
Self::Managed => Some("managed"),
Self::None => None,
}
}
}
#[derive(Clone, Debug)]
struct RuntimeState {
settings: WebMcpSettings,
source: TokenSource,
token: Option<String>,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WebMcpHttpStatus {
pub enabled: bool,
pub endpoint_path: String,
pub token_source: Option<&'static str>,
pub allowed_hosts: Vec<String>,
pub allowed_origins: Vec<String>,
pub deployment_managed: bool,
pub management_available: bool,
/// Only Web-managed tokens are returned to the authenticated settings UI.
/// Deployment-provided secrets are never echoed back by the API.
pub access_token: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateWebMcpRequest {
pub enabled: bool,
#[serde(default)]
pub allowed_hosts: Vec<String>,
#[serde(default)]
pub allowed_origins: Vec<String>,
#[serde(default)]
pub rotate_token: bool,
}
pub struct WebMcpRuntime {
auth: HttpAuth,
state: RwLock<RuntimeState>,
operation_lock: tokio::sync::Mutex<()>,
}
impl WebMcpRuntime {
pub async fn load(storage: &Storage, allow_managed: bool) -> Result<Self, String> {
Self::load_with_deployment(storage, deployment_config()?, allow_managed).await
}
async fn load_with_deployment(
storage: &Storage,
deployment: Option<DeploymentConfig>,
allow_managed: bool,
) -> Result<Self, String> {
if deployment.is_none() && !allow_managed {
return Ok(Self::disabled());
}
let (token, source, settings) = match deployment {
Some(deployment) => {
let settings = WebMcpSettings {
enabled: true,
allowed_hosts: deployment.allowed_hosts,
allowed_origins: deployment.allowed_origins,
};
(Some(deployment.token), deployment.source, settings)
}
None => {
let managed_settings = storage.load_web_mcp_settings().await?;
let token = if managed_settings.enabled {
storage.get_secret(SECRET_NAMESPACE, SECRET_KEY).await?
} else {
None
};
let source = if managed_settings.enabled { TokenSource::Managed } else { TokenSource::None };
(token, source, managed_settings)
}
};
validate_settings(&settings, token.as_deref())?;
let auth = HttpAuth::new_with_hosts(
token.clone(),
settings.allowed_hosts.clone(),
settings.allowed_origins.clone(),
false,
)?;
Ok(Self {
auth,
state: RwLock::new(RuntimeState { settings, source, token }),
operation_lock: tokio::sync::Mutex::new(()),
})
}
pub fn disabled() -> Self {
Self {
auth: HttpAuth::new_with_hosts(None, Vec::<String>::new(), Vec::<String>::new(), false).unwrap(),
state: RwLock::new(RuntimeState {
settings: WebMcpSettings::default(),
source: TokenSource::None,
token: None,
}),
operation_lock: tokio::sync::Mutex::new(()),
}
}
pub fn auth(&self) -> HttpAuth {
self.auth.clone()
}
pub async fn reload(&self, storage: &Storage, allow_managed: bool) -> Result<(), String> {
let _guard = self.operation_lock.lock().await;
let refreshed = Self::load(storage, allow_managed).await?;
let state = refreshed.state.into_inner().unwrap_or_else(|error| error.into_inner());
self.auth.reconfigure(
state.token.clone(),
state.settings.allowed_hosts.clone(),
state.settings.allowed_origins.clone(),
)?;
*self.state.write().unwrap_or_else(|error| error.into_inner()) = state;
Ok(())
}
pub fn allowed_hosts(&self) -> Vec<String> {
self.state.read().unwrap_or_else(|error| error.into_inner()).settings.allowed_hosts.clone()
}
pub fn status(&self, endpoint_path: String, management_available: bool) -> WebMcpHttpStatus {
let state = self.state.read().unwrap_or_else(|error| error.into_inner());
let managed = state.source == TokenSource::Managed;
WebMcpHttpStatus {
enabled: state.settings.enabled && state.token.is_some(),
endpoint_path,
token_source: state.source.as_str(),
allowed_hosts: state.settings.allowed_hosts.clone(),
allowed_origins: state.settings.allowed_origins.clone(),
deployment_managed: matches!(state.source, TokenSource::Environment | TokenSource::File),
management_available,
access_token: if managed && management_available { state.token.clone() } else { None },
}
}
pub async fn update(&self, storage: &Storage, request: UpdateWebMcpRequest) -> Result<(), String> {
let _guard = self.operation_lock.lock().await;
self.update_locked(storage, request).await
}
async fn update_locked(&self, storage: &Storage, request: UpdateWebMcpRequest) -> Result<(), String> {
if matches!(
self.state.read().unwrap_or_else(|error| error.into_inner()).source,
TokenSource::Environment | TokenSource::File
) {
return Err("DBX Web MCP is managed by deployment environment configuration".to_string());
}
let settings = WebMcpSettings {
enabled: request.enabled,
allowed_hosts: normalize_list(request.allowed_hosts),
allowed_origins: normalize_list(request.allowed_origins),
};
let current_token = storage.get_secret(SECRET_NAMESPACE, SECRET_KEY).await?;
let token = if settings.enabled {
if request.rotate_token || current_token.is_none() {
Some(generate_token())
} else {
current_token
}
} else {
None
};
validate_settings(&settings, token.as_deref())?;
storage.save_web_mcp_credentials(&settings, token.as_deref()).await?;
self.auth.reconfigure(token.clone(), settings.allowed_hosts.clone(), settings.allowed_origins.clone())?;
*self.state.write().unwrap_or_else(|error| error.into_inner()) = RuntimeState {
settings,
source: if token.is_some() { TokenSource::Managed } else { TokenSource::None },
token,
};
Ok(())
}
pub async fn rotate(&self, storage: &Storage) -> Result<(), String> {
let _guard = self.operation_lock.lock().await;
let settings = self.state.read().unwrap_or_else(|error| error.into_inner()).settings.clone();
if !settings.enabled {
return Err("DBX Web MCP is not enabled".to_string());
}
self.update_locked(
storage,
UpdateWebMcpRequest {
enabled: true,
allowed_hosts: settings.allowed_hosts,
allowed_origins: settings.allowed_origins,
rotate_token: true,
},
)
.await
}
}
fn deployment_config() -> Result<Option<DeploymentConfig>, String> {
let inline = env::var("DBX_WEB_MCP_TOKEN").ok();
let file = env::var("DBX_WEB_MCP_TOKEN_FILE").ok();
let token_and_source = match (inline, file) {
(Some(_), Some(_)) => Err("set only one of DBX_WEB_MCP_TOKEN or DBX_WEB_MCP_TOKEN_FILE".to_string()),
(Some(token), None) => validate_token(token).map(|token| Some((token, TokenSource::Environment))),
(None, Some(path)) => std::fs::read_to_string(&path)
.map_err(|error| format!("failed to read DBX_WEB_MCP_TOKEN_FILE: {error}"))
.map(|token| token.trim_end_matches(['\r', '\n']).to_string())
.and_then(validate_token)
.map(|token| Some((token, TokenSource::File))),
(None, None) => Ok(None),
}?;
Ok(token_and_source.map(|(token, source)| DeploymentConfig {
token,
source,
allowed_hosts: comma_separated_env("DBX_WEB_MCP_ALLOWED_HOSTS"),
allowed_origins: comma_separated_env("DBX_WEB_MCP_ALLOWED_ORIGINS"),
}))
}
fn validate_settings(settings: &WebMcpSettings, token: Option<&str>) -> Result<(), String> {
if settings.enabled && token.is_none() {
return Err("DBX Web MCP is enabled but no token is configured".to_string());
}
if settings.enabled && settings.allowed_hosts.is_empty() {
return Err("DBX_WEB_MCP_ALLOWED_HOSTS or a Web MCP allowed Host is required".to_string());
}
HttpAuth::new_with_hosts(
token.map(ToOwned::to_owned),
settings.allowed_hosts.clone(),
settings.allowed_origins.clone(),
false,
)?;
Ok(())
}
fn validate_token(token: String) -> Result<String, String> {
if token.is_empty() || token.contains(char::is_whitespace) {
return Err("MCP HTTP bearer token must be non-empty and contain no whitespace".to_string());
}
Ok(token)
}
fn generate_token() -> String {
format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple())
}
fn normalize_list(values: Vec<String>) -> Vec<String> {
let mut normalized = values
.into_iter()
.flat_map(|value| value.split([',', '\n']).map(str::trim).map(ToOwned::to_owned).collect::<Vec<_>>())
.filter(|value| !value.is_empty())
.collect::<Vec<_>>();
normalized.sort();
normalized.dedup();
normalized
}
fn comma_separated_env(name: &str) -> Vec<String> {
normalize_list(env::var(name).ok().into_iter().collect())
}
#[cfg(test)]
mod tests {
use super::*;
async fn test_storage() -> (tempfile::TempDir, Storage) {
let dir = tempfile::tempdir().unwrap();
let storage = dbx_core::persistence::test_storage::open(&dir.path().join("dbx.db")).await.unwrap();
(dir, storage)
}
fn request(enabled: bool, hosts: &[&str], rotate_token: bool) -> UpdateWebMcpRequest {
UpdateWebMcpRequest {
enabled,
allowed_hosts: hosts.iter().map(|host| host.to_string()).collect(),
allowed_origins: vec!["https://client.example.test".to_string()],
rotate_token,
}
}
#[test]
fn deployment_token_rejects_whitespace() {
assert!(validate_token(" token".to_string()).is_err());
assert!(validate_token("token ".to_string()).is_err());
assert!(validate_token("token\n".to_string()).is_err());
}
#[tokio::test]
async fn managed_token_survives_restart_and_is_encrypted() {
let (_dir, storage) = test_storage().await;
let runtime = WebMcpRuntime::load_with_deployment(&storage, None, true).await.unwrap();
assert!(!runtime.status("/mcp".to_string(), true).enabled);
runtime.update(&storage, request(true, &["dbx.example.test:4224"], false)).await.unwrap();
let status = runtime.status("/mcp".to_string(), true);
let token = status.access_token.clone().unwrap();
assert!(status.enabled);
assert_eq!(token.len(), 64);
assert_eq!(status.token_source, Some("managed"));
assert!(!serde_json::to_string(&storage.load_web_mcp_settings().await.unwrap()).unwrap().contains(&token));
let restarted = WebMcpRuntime::load_with_deployment(&storage, None, true).await.unwrap();
assert_eq!(restarted.status("/mcp".to_string(), true).access_token.as_deref(), Some(token.as_str()));
}
#[tokio::test]
async fn rotate_and_disable_update_live_auth() {
let (_dir, storage) = test_storage().await;
let runtime = WebMcpRuntime::load_with_deployment(&storage, None, true).await.unwrap();
runtime.update(&storage, request(true, &["dbx.example.test:4224"], false)).await.unwrap();
let old = runtime.status("/mcp".to_string(), true).access_token.unwrap();
runtime.rotate(&storage).await.unwrap();
let new = runtime.status("/mcp".to_string(), true).access_token.unwrap();
assert_ne!(old, new);
assert!(runtime.auth.enabled());
runtime.update(&storage, request(false, &[], false)).await.unwrap();
assert!(!runtime.auth.enabled());
assert!(!runtime.status("/mcp".to_string(), true).enabled);
assert!(storage.get_secret(SECRET_NAMESPACE, SECRET_KEY).await.unwrap().is_none());
assert!(
!WebMcpRuntime::load_with_deployment(&storage, None, true)
.await
.unwrap()
.status("/mcp".to_string(), true)
.enabled
);
}
#[tokio::test]
async fn deployment_token_overrides_managed_settings() {
let (_dir, storage) = test_storage().await;
let runtime = WebMcpRuntime::load_with_deployment(&storage, None, true).await.unwrap();
runtime.update(&storage, request(true, &["dbx.example.test:4224"], false)).await.unwrap();
let managed = runtime.status("/mcp".to_string(), true).access_token.unwrap();
let deployed = WebMcpRuntime::load_with_deployment(
&storage,
Some(DeploymentConfig {
token: "deployment-secret".to_string(),
source: TokenSource::Environment,
allowed_hosts: vec!["deployed.example.test:4224".to_string()],
allowed_origins: vec![],
}),
false,
)
.await
.unwrap();
let status = deployed.status("/mcp".to_string(), true);
assert!(status.enabled);
assert!(status.deployment_managed);
assert_eq!(status.token_source, Some("environment"));
assert_eq!(status.allowed_hosts, ["deployed.example.test:4224"]);
assert!(status.access_token.is_none());
assert!(deployed.update(&storage, request(false, &[], false)).await.is_err());
assert_eq!(storage.get_secret(SECRET_NAMESPACE, SECRET_KEY).await.unwrap().as_deref(), Some(managed.as_str()));
assert!(
!WebMcpRuntime::load_with_deployment(&storage, None, false)
.await
.unwrap()
.status("/mcp".to_string(), false)
.enabled
);
assert_eq!(
WebMcpRuntime::load_with_deployment(&storage, None, true)
.await
.unwrap()
.status("/mcp".to_string(), true)
.access_token
.as_deref(),
Some(managed.as_str())
);
}
#[tokio::test]
async fn invalid_host_or_origin_does_not_enable_mcp() {
let (_dir, storage) = test_storage().await;
let runtime = WebMcpRuntime::load_with_deployment(&storage, None, true).await.unwrap();
assert!(runtime.update(&storage, request(true, &["https://dbx.example.test"], false)).await.is_err());
assert!(!runtime.auth.enabled());
assert!(storage.get_secret(SECRET_NAMESPACE, SECRET_KEY).await.unwrap().is_none());
}
}