feat(mcp): centralize connection access policies

This commit is contained in:
二丫讲梵 authored and GitHub committed 2026-07-20 22:47:40 +08:00
1 parent 29f493f7da
commit d642d01eac
56 files changed
+6393 -617

No files matched your search

+15
View File
@@ -5,6 +5,7 @@ use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
use axum::extract::State;
use axum::Json;
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use dbx_core::storage::{McpGlobalPolicy, McpGlobalPolicyState};
use pbkdf2::pbkdf2_hmac;
use serde::Deserialize;
use sha2::Sha256;
@@ -50,6 +51,20 @@ pub async fn save_pinned_tree_node_ids(
Ok(Json(()))
}
pub async fn load_mcp_global_policy(
State(state): State<Arc<WebState>>,
) -> Result<Json<McpGlobalPolicyState>, AppError> {
state.app.storage.load_mcp_global_policy().await.map(Json).map_err(AppError)
}
pub async fn save_mcp_global_policy(
State(state): State<Arc<WebState>>,
Json(policy): Json<McpGlobalPolicy>,
) -> Result<Json<()>, AppError> {
state.app.storage.save_mcp_global_policy(&policy).await.map_err(AppError)?;
Ok(Json(()))
}
pub async fn decrypt_config(Json(body): Json<DecryptConfigRequest>) -> Result<Json<String>, AppError> {
decrypt_config_payload(&body.payload, &body.passphrase).map(Json).map_err(AppError)
}
+133 -4
View File
@@ -51,6 +51,18 @@ pub struct SaveConnectionsRequest {
pub configs: Vec<ConnectionConfig>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct McpAddConnectionRequest {
pub config: ConnectionConfig,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct McpRemoveConnectionRequest {
pub connection_id: String,
}
fn is_connection_info_capability_unsupported(error: &str) -> bool {
let error = error.to_ascii_lowercase();
error.contains("connectioninfo")
@@ -259,6 +271,31 @@ pub async fn save_connections(
Ok(Json(()))
}
pub async fn mcp_add_connection(
State(state): State<Arc<WebState>>,
Json(body): Json<McpAddConnectionRequest>,
) -> Result<Json<ConnectionConfig>, AppError> {
let saved = state.app.storage.add_connection_for_mcp(body.config).await.map_err(AppError)?;
state.app.configs.write().await.insert(saved.id.clone(), saved.clone());
Ok(Json(saved))
}
pub async fn mcp_remove_connection(
State(state): State<Arc<WebState>>,
Json(body): Json<McpRemoveConnectionRequest>,
) -> Result<Json<bool>, AppError> {
let connection_id = body.connection_id;
let removed = state.app.storage.remove_connection_for_mcp(&connection_id).await.map_err(AppError)?;
if removed {
state.app.configs.write().await.remove(&connection_id);
state.app.remove_connection_pools_detached(&connection_id).await;
state.app.nacos_registry.drop_connection(&connection_id).await;
#[cfg(feature = "mq-admin")]
state.app.mq_registry.drop_connection(&connection_id).await;
}
Ok(Json(removed))
}
pub async fn load_connections(State(state): State<Arc<WebState>>) -> Result<Json<Vec<ConnectionConfig>>, AppError> {
let configs = state.app.storage.load_connections().await.map_err(AppError)?;
let sync = sync_connection_configs(&state, &configs).await;
@@ -349,9 +386,10 @@ async fn remove_connection_pools_for_connection_ids(state: &WebState, connection
#[cfg(test)]
mod tests {
use super::{
connect_db, connection_final_proxy_port, disconnect_db, load_connections, save_connection_database_info,
save_connections, test_connection, test_connection_with_info, ConnectRequest, DisconnectRequest,
SaveConnectionDatabaseInfoRequest, SaveConnectionsRequest,
connect_db, connection_final_proxy_port, disconnect_db, load_connections, mcp_add_connection,
mcp_remove_connection, save_connection_database_info, save_connections, test_connection,
test_connection_with_info, ConnectRequest, DisconnectRequest, McpAddConnectionRequest,
McpRemoveConnectionRequest, SaveConnectionDatabaseInfoRequest, SaveConnectionsRequest,
};
use crate::state::{LoginRateLimit, WebState};
use axum::extract::State;
@@ -361,7 +399,7 @@ mod tests {
AttachedDatabaseConfig, ConnectionConfig, DatabaseConnectionInfo, DatabaseType, ProxyTunnelConfig, ProxyType,
TransportLayerConfig,
};
use dbx_core::storage::Storage;
use dbx_core::storage::{McpGlobalPolicy, Storage};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
#[cfg(feature = "mq-admin")]
@@ -584,6 +622,97 @@ mod tests {
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn mcp_connection_routes_preserve_unrelated_concurrent_changes() {
let (state, dir) = test_web_state().await;
let mut existing = sqlite_config("existing", &dir.join("before.db").to_string_lossy());
state.app.storage.save_connections(std::slice::from_ref(&existing)).await.unwrap();
state
.app
.storage
.save_mcp_global_policy(&McpGlobalPolicy {
read_only: false,
allow_dangerous_sql: false,
allowed_connection_ids: Some(vec![existing.id.clone()]),
})
.await
.unwrap();
// Simulate a Web UI edit after the MCP client last observed the list.
existing.host = dir.join("after.db").to_string_lossy().into_owned();
state.app.storage.save_connections(std::slice::from_ref(&existing)).await.unwrap();
let added = sqlite_config("added", &dir.join("added.db").to_string_lossy());
let result =
mcp_add_connection(State(state.clone()), Json(McpAddConnectionRequest { config: added.clone() })).await;
assert!(result.is_ok());
let persisted = state.app.storage.load_connections().await.unwrap();
assert_eq!(persisted.len(), 2);
assert_eq!(
persisted.iter().find(|config| config.id == existing.id).map(|config| config.host.as_str()),
Some(existing.host.as_str())
);
assert!(persisted.iter().any(|config| config.id == added.id));
assert!(state.app.configs.read().await.contains_key(&added.id));
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn mcp_connection_routes_recheck_read_only_and_allowlist_in_the_mutation_transaction() {
let (state, dir) = test_web_state().await;
let kept = sqlite_config("kept", &dir.join("kept.db").to_string_lossy());
let removed = sqlite_config("removed", &dir.join("removed.db").to_string_lossy());
state.app.storage.save_connections(&[kept.clone(), removed.clone()]).await.unwrap();
state
.app
.storage
.save_mcp_global_policy(&McpGlobalPolicy {
read_only: false,
allow_dangerous_sql: false,
allowed_connection_ids: Some(vec![removed.id.clone()]),
})
.await
.unwrap();
let removed_result = mcp_remove_connection(
State(state.clone()),
Json(McpRemoveConnectionRequest { connection_id: removed.id.clone() }),
)
.await
.unwrap_or_else(|error| panic!("{}", error.0));
assert!(removed_result.0);
assert_eq!(state.app.storage.load_connections().await.unwrap()[0].id, kept.id);
let scope_error = mcp_remove_connection(
State(state.clone()),
Json(McpRemoveConnectionRequest { connection_id: kept.id.clone() }),
)
.await
.unwrap_err();
assert!(scope_error.0.starts_with("CONNECTION_OUT_OF_SCOPE:"));
state
.app
.storage
.save_mcp_global_policy(&McpGlobalPolicy {
read_only: true,
allow_dangerous_sql: false,
allowed_connection_ids: None,
})
.await
.unwrap();
let read_only_error = mcp_add_connection(
State(state.clone()),
Json(McpAddConnectionRequest { config: sqlite_config("new", &dir.join("new.db").to_string_lossy()) }),
)
.await
.unwrap_err();
assert!(read_only_error.0.starts_with("MCP_READ_ONLY:"));
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn save_connection_database_info_preserves_connected_pool() {
let (state, dir) = test_web_state().await;
+438
View File
@@ -0,0 +1,438 @@
use std::sync::Arc;
use axum::http::HeaderMap;
use dbx_core::models::connection::ConnectionConfig;
use dbx_core::storage::McpGlobalPolicy;
use crate::error::AppError;
use crate::state::WebState;
const MCP_REQUEST_HEADER: &str = "x-dbx-mcp-request";
pub fn is_mcp_request(headers: &HeaderMap) -> bool {
headers.get(MCP_REQUEST_HEADER).and_then(|value| value.to_str().ok()) == Some("1")
}
pub fn mongo_pipeline_has_write_stage(pipeline_json: &str) -> bool {
serde_json::from_str::<serde_json::Value>(pipeline_json)
.ok()
.and_then(|value| value.as_array().cloned())
.is_some_and(|stages| {
stages.iter().any(|stage| {
stage
.as_object()
.is_some_and(|document| document.contains_key("$out") || document.contains_key("$merge"))
})
})
}
pub fn mongo_filter_is_effectively_unbounded(filter_json: &str) -> bool {
serde_json::from_str::<serde_json::Value>(filter_json)
.ok()
.as_ref()
.is_none_or(|value| mongo_filter_contains_opaque_logic(value) || mongo_filter_value_is_unbounded(value))
}
fn mongo_filter_contains_opaque_logic(value: &serde_json::Value) -> bool {
let Some(filter) = value.as_object() else {
return true;
};
filter.iter().any(|(key, value)| match key.as_str() {
"$comment" => false,
"$where" | "$expr" | "$nor" => true,
"$and" | "$or" => {
let Some(clauses) = value.as_array() else {
return true;
};
clauses.is_empty()
|| clauses.iter().any(|clause| !clause.is_object() || mongo_filter_contains_opaque_logic(clause))
|| (key == "$or"
&& clauses
.iter()
.any(|clause| clause.as_object().is_some_and(|document| document.contains_key("$and"))))
|| (key == "$or" && mongo_or_has_complementary_field_clauses(clauses))
}
_ => key.starts_with('$') || mongo_field_predicate_contains_opaque_logic(value),
})
}
fn mongo_field_predicate_contains_opaque_logic(value: &serde_json::Value) -> bool {
let Some(predicate) = value.as_object() else {
return false;
};
if mongo_extended_json_scalar_literal_is_valid(value) {
return false;
}
let has_operator = predicate.keys().any(|key| key.starts_with('$'));
has_operator
&& predicate.keys().any(|key| {
!matches!(key.as_str(), "$eq" | "$ne" | "$gt" | "$gte" | "$lt" | "$lte" | "$in" | "$nin" | "$exists")
})
}
fn mongo_extended_json_scalar_literal_is_valid(value: &serde_json::Value) -> bool {
let Some(wrapper) = value.as_object().filter(|wrapper| wrapper.len() == 1) else {
return false;
};
if let Some(value) = wrapper.get("$oid").and_then(serde_json::Value::as_str) {
return value.len() == 24 && value.bytes().all(|byte| byte.is_ascii_hexdigit());
}
if let Some(value) = wrapper.get("$numberLong").and_then(serde_json::Value::as_str) {
return value.parse::<i64>().is_ok();
}
wrapper
.get("$date")
.and_then(serde_json::Value::as_str)
.is_some_and(|value| chrono::DateTime::parse_from_rfc3339(value).is_ok())
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum MongoFieldOperator {
Eq,
Ne,
Gt,
Gte,
Lt,
Lte,
In,
Nin,
Exists,
}
struct MongoPureFieldPredicate<'a> {
field: &'a str,
operator: MongoFieldOperator,
operand: &'a serde_json::Value,
}
fn mongo_or_has_complementary_field_clauses(clauses: &[serde_json::Value]) -> bool {
clauses.iter().enumerate().any(|(index, clause)| {
let Some(predicate) = mongo_pure_field_predicate(clause) else {
return false;
};
clauses[index + 1..]
.iter()
.filter_map(mongo_pure_field_predicate)
.any(|other| mongo_field_predicates_are_complementary(&predicate, &other))
})
}
fn mongo_pure_field_predicate(value: &serde_json::Value) -> Option<MongoPureFieldPredicate<'_>> {
let filter = value.as_object()?;
let mut entries = filter.iter().filter(|(key, _)| key.as_str() != "$comment");
let (field, predicate) = entries.next()?;
if entries.next().is_some() {
return None;
}
if field == "$and" {
let clauses = predicate.as_array()?;
let mut bounded = clauses.iter().filter(|clause| !mongo_filter_value_is_unbounded(clause));
let clause = bounded.next()?;
if bounded.next().is_some() {
return None;
}
return mongo_pure_field_predicate(clause);
}
if field == "$or" {
let clauses = predicate.as_array()?;
return (clauses.len() == 1).then(|| mongo_pure_field_predicate(&clauses[0])).flatten();
}
if field.starts_with('$') {
return None;
}
let Some(operator_document) = predicate.as_object() else {
return Some(MongoPureFieldPredicate { field, operator: MongoFieldOperator::Eq, operand: predicate });
};
if mongo_extended_json_scalar_literal_is_valid(predicate)
|| !operator_document.keys().any(|key| key.starts_with('$'))
{
return Some(MongoPureFieldPredicate { field, operator: MongoFieldOperator::Eq, operand: predicate });
}
let mut operators = operator_document.iter();
let (operator, operand) = operators.next()?;
if operators.next().is_some() {
return None;
}
let operator = match operator.as_str() {
"$eq" => MongoFieldOperator::Eq,
"$ne" => MongoFieldOperator::Ne,
"$gt" => MongoFieldOperator::Gt,
"$gte" => MongoFieldOperator::Gte,
"$lt" => MongoFieldOperator::Lt,
"$lte" => MongoFieldOperator::Lte,
"$in" => MongoFieldOperator::In,
"$nin" => MongoFieldOperator::Nin,
"$exists" => MongoFieldOperator::Exists,
_ => return None,
};
Some(MongoPureFieldPredicate { field, operator, operand })
}
fn mongo_field_predicates_are_complementary(
left: &MongoPureFieldPredicate<'_>,
right: &MongoPureFieldPredicate<'_>,
) -> bool {
if left.field != right.field {
return false;
}
use MongoFieldOperator::{Eq, Exists, Gt, Gte, In, Lt, Lte, Ne, Nin};
match (left.operator, right.operator) {
(Exists, Exists) => {
left.operand.as_bool().zip(right.operand.as_bool()).is_some_and(|(left, right)| left != right)
}
(In, Nin) | (Nin, In) => mongo_json_sets_equal(left.operand, right.operand),
(Eq, Ne) | (Ne, Eq) | (Gt, Lte) | (Lte, Gt) | (Gte, Lt) | (Lt, Gte) => left.operand == right.operand,
_ => false,
}
}
fn mongo_json_sets_equal(left: &serde_json::Value, right: &serde_json::Value) -> bool {
let (Some(left), Some(right)) = (left.as_array(), right.as_array()) else {
return false;
};
left.iter().all(|value| right.contains(value)) && right.iter().all(|value| left.contains(value))
}
fn mongo_filter_value_is_unbounded(value: &serde_json::Value) -> bool {
let Some(filter) = value.as_object() else {
return true;
};
if filter.is_empty() || filter.contains_key("$where") || filter.contains_key("$expr") {
return true;
}
filter.iter().all(|(key, value)| match key.as_str() {
"$comment" => true,
"$and" => value
.as_array()
.is_none_or(|clauses| clauses.is_empty() || clauses.iter().all(mongo_filter_value_is_unbounded)),
"$or" => value
.as_array()
.is_none_or(|clauses| clauses.is_empty() || clauses.iter().any(mongo_filter_value_is_unbounded)),
"$nor" => true,
_ if mongo_field_predicate_is_empty_nin(value) => true,
"_id" if mongo_field_predicate_is_exists_true(value) => true,
_ => key.starts_with('$'),
})
}
fn mongo_field_predicate_is_empty_nin(value: &serde_json::Value) -> bool {
value.as_object().is_some_and(|predicate| {
predicate.len() == 1 && predicate.get("$nin").and_then(serde_json::Value::as_array).is_some_and(Vec::is_empty)
})
}
fn mongo_field_predicate_is_exists_true(value: &serde_json::Value) -> bool {
value.as_object().is_some_and(|predicate| {
predicate.len() == 1 && predicate.get("$exists").and_then(serde_json::Value::as_bool) == Some(true)
})
}
async fn load_policy(state: &Arc<WebState>) -> Result<McpGlobalPolicy, AppError> {
state.app.storage.load_mcp_global_policy().await.map(|state| state.policy()).map_err(AppError)
}
fn ensure_allowed(policy: &McpGlobalPolicy, connection_id: &str) -> Result<(), AppError> {
if policy.allowed_connection_ids.as_ref().is_some_and(|allowed| !allowed.iter().any(|id| id == connection_id)) {
return Err(AppError(format!(
"CONNECTION_OUT_OF_SCOPE: connection '{connection_id}' is not allowed by DBX MCP settings"
)));
}
Ok(())
}
fn connection_read_only_error(message: impl Into<String>) -> AppError {
AppError(format!("CONNECTION_READ_ONLY: {}", message.into()))
}
async fn load_connection(state: &Arc<WebState>, connection_id: &str) -> Result<ConnectionConfig, AppError> {
state
.app
.storage
.load_connections()
.await
.map_err(AppError)?
.into_iter()
.find(|config| config.id == connection_id)
.ok_or_else(|| AppError(format!("Connection with id '{connection_id}' not found")))
}
pub async fn ensure_scope(state: &Arc<WebState>, headers: &HeaderMap, connection_id: &str) -> Result<(), AppError> {
if !is_mcp_request(headers) {
return Ok(());
}
ensure_allowed(&load_policy(state).await?, connection_id)
}
pub async fn ensure_write(
state: &Arc<WebState>,
headers: &HeaderMap,
connection_id: &str,
database: &str,
action: &str,
) -> Result<(), AppError> {
ensure_write_with_risk(state, headers, connection_id, database, action, false).await
}
pub async fn ensure_dangerous_write(
state: &Arc<WebState>,
headers: &HeaderMap,
connection_id: &str,
database: &str,
action: &str,
) -> Result<(), AppError> {
ensure_write_with_risk(state, headers, connection_id, database, action, true).await
}
pub async fn ensure_mongo_pipeline_target(
state: &Arc<WebState>,
headers: &HeaderMap,
connection_id: &str,
database: &str,
pipeline_json: &str,
) -> Result<(), AppError> {
if !is_mcp_request(headers) {
return Ok(());
}
let config = load_connection(state, connection_id).await?;
if dbx_core::production_safety::mongo_pipeline_targets_production_database(&config, database, pipeline_json) {
return Err(AppError(
"PRODUCTION_DATABASE_READ_ONLY: MongoDB aggregate write targeting production scope is blocked.".to_string(),
));
}
Ok(())
}
async fn ensure_write_with_risk(
state: &Arc<WebState>,
headers: &HeaderMap,
connection_id: &str,
database: &str,
action: &str,
dangerous: bool,
) -> Result<(), AppError> {
if !is_mcp_request(headers) {
return Ok(());
}
let policy = load_policy(state).await?;
ensure_allowed(&policy, connection_id)?;
if policy.read_only {
return Err(AppError(format!("MCP_READ_ONLY: DBX MCP read-only mode is enabled. {action} blocked.")));
}
if dangerous && !policy.allow_dangerous_sql {
return Err(AppError(format!("SQL_BLOCKED: High-risk operation '{action}' is disabled in DBX MCP settings.")));
}
let config = load_connection(state, connection_id).await?;
if config.read_only {
return Err(connection_read_only_error(format!(
"Connection '{}' has read-only protection enabled. {action} blocked.",
config.name
)));
}
if dbx_core::production_safety::is_production_database(&config, database) {
return Err(AppError(format!(
"PRODUCTION_DATABASE_READ_ONLY: {action} blocked for production database '{database}'."
)));
}
Ok(())
}
pub async fn ensure_sql(
state: &Arc<WebState>,
headers: &HeaderMap,
connection_id: &str,
database: &str,
sql: &str,
) -> Result<(), AppError> {
if !is_mcp_request(headers) {
return Ok(());
}
let policy = load_policy(state).await?;
ensure_allowed(&policy, connection_id)?;
let config = load_connection(state, connection_id).await?;
if dbx_core::sql_risk::mcp_sql_has_forbidden_database_switch(sql, config.db_type) {
return Err(AppError("SQL_BLOCKED: MCP does not allow USE or persistent database switching.".to_string()));
}
let is_write = dbx_core::query_execution_sql::is_write_sql_for_database(sql, config.db_type);
if policy.read_only && is_write {
return Err(AppError("MCP_READ_ONLY: DBX MCP read-only mode is enabled. SQL write blocked.".to_string()));
}
if !policy.allow_dangerous_sql && dbx_core::sql_risk::is_dangerous_sql_for_database(sql, config.db_type) {
return Err(AppError("SQL_BLOCKED: High-risk SQL is disabled in DBX MCP settings.".to_string()));
}
if config.read_only {
dbx_core::query_execution_sql::check_read_only(sql, &config.name, config.db_type)
.map_err(connection_read_only_error)?;
}
if is_write && dbx_core::production_safety::targets_production_database(&config, database, sql) {
return Err(AppError(
"PRODUCTION_DATABASE_READ_ONLY: SQL write targeting production scope is blocked.".to_string(),
));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::{connection_read_only_error, mongo_filter_is_effectively_unbounded, mongo_pipeline_has_write_stage};
#[test]
fn connection_read_only_errors_use_the_stable_mcp_code() {
assert_eq!(connection_read_only_error("write blocked").0, "CONNECTION_READ_ONLY: write blocked");
}
#[test]
fn detects_only_top_level_aggregate_write_stages() {
assert!(mongo_pipeline_has_write_stage(r#"[{"$out":"archive"}]"#));
assert!(mongo_pipeline_has_write_stage(r#"[{"$merge":{"into":"archive"}}]"#));
assert!(!mongo_pipeline_has_write_stage(r#"[{"$project":{"value":"$out"}}]"#));
assert!(!mongo_pipeline_has_write_stage("not-json"));
}
#[test]
fn detects_effectively_unbounded_mongo_filters() {
for filter in [
"{}",
r#"{"$comment":"all rows"}"#,
r#"{"$expr":true}"#,
r#"{"$or":[{}, {"id":1}]}"#,
r#"{"$nor":[{"$expr":false}]}"#,
r#"{"$or":[{"id":{"$exists":true}},{"id":{"$exists":false}}]}"#,
r#"{"$or":[{"id":{"$exists":true}},{"id":{"$not":{"$exists":true}}}]}"#,
r#"{"$or":[{"id":{"$eq":1}},{"id":{"$ne":1}}]}"#,
r#"{"$or":[{"$and":[{"id":{"$eq":1}}]},{"id":{"$ne":1}}]}"#,
r#"{"$or":[{"$and":[{"id":{"$eq":1}},{}]},{"id":{"$ne":1}}]}"#,
r#"{"$or":[{"$and":[{"id":{"$eq":1}},{"x":{"$exists":true}}]},{"id":{"$ne":1}},{"x":{"$exists":false}}]}"#,
r#"{"$or":[{"id":1},{"id":{"$ne":1}}]}"#,
r#"{"$or":[{"id":{"$gt":1}},{"id":{"$lte":1}}]}"#,
r#"{"$or":[{"id":{"$gte":1}},{"id":{"$lt":1}}]}"#,
r#"{"$or":[{"id":{"$in":[1,2]}},{"id":{"$nin":[2,1]}}]}"#,
r#"{"_id":{"$exists":true}}"#,
r#"{"id":{"$nin":[]}}"#,
r#"{"_id":{"$oid":"not-an-object-id"}}"#,
r#"{"sequence":{"$numberLong":"9223372036854775808"}}"#,
r#"{"created_at":{"$date":"2026-02-30T00:00:00Z"}}"#,
r#"{"name":{"$regex":".*"}}"#,
r#"{"$or":[{"_id":{"$oid":"507f1f77bcf86cd799439011"}},{"_id":{"$ne":{"$oid":"507f1f77bcf86cd799439011"}}}]}"#,
r#"{"$and":[{"tenant_id":1},{"$nor":[{"archived":true}]}]}"#,
r#"{"$or":[]}"#,
r#"{"$opaque":[{"id":1}]}"#,
] {
assert!(mongo_filter_is_effectively_unbounded(filter), "{filter}");
}
for filter in [
r#"{"id":1}"#,
r#"{"created_at":{"$gte":"2026-01-01"}}"#,
r#"{"$and":[{}, {"tenant_id":1}]}"#,
r#"{"$or":[{"tenant_id":1},{"tenant_id":2}]}"#,
r#"{"id":{"$ne":1}}"#,
r#"{"id":{"$in":[1,2]}}"#,
r#"{"id":{"$exists":true}}"#,
r#"{"_id":{"$oid":"507f1f77bcf86cd799439011"}}"#,
r#"{"sequence":{"$numberLong":"9223372036854775807"}}"#,
r#"{"created_at":{"$date":"2026-01-01T00:00:00.000Z"}}"#,
r#"{"tenant_id":1,"id":{"$nin":[]}}"#,
] {
assert!(!mongo_filter_is_effectively_unbounded(filter), "{filter}");
}
}
}
+1
View File
@@ -10,6 +10,7 @@ pub mod etcd;
pub mod history;
pub mod jdbc;
pub mod layout;
pub mod mcp_policy;
pub mod mongo;
#[cfg(feature = "mq-admin")]
pub mod mq;
+206
View File
@@ -2,6 +2,7 @@ use std::future::Future;
use std::sync::Arc;
use axum::extract::State;
use axum::http::HeaderMap;
use axum::Json;
use serde::Deserialize;
@@ -269,8 +270,10 @@ pub struct MongoDeleteRequest {
pub async fn list_databases(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<MongoConnectionRequest>,
) -> Result<Json<Vec<String>>, AppError> {
super::mcp_policy::ensure_scope(&state, &headers, &req.connection_id).await?;
let result =
dbx_core::mongo_ops::mongo_list_databases_core(&state.app, &req.connection_id).await.map_err(AppError)?;
Ok(Json(result))
@@ -278,8 +281,10 @@ pub async fn list_databases(
pub async fn list_collections(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<MongoCollectionRequest>,
) -> Result<Json<Vec<dbx_core::document_ops::CollectionInfo>>, AppError> {
super::mcp_policy::ensure_scope(&state, &headers, &req.connection_id).await?;
let result = dbx_core::mongo_ops::mongo_list_collections_core(&state.app, &req.connection_id, &req.database)
.await
.map_err(AppError)?;
@@ -333,8 +338,11 @@ pub async fn drop_database(
pub async fn drop_collection(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<MongoCollectionNameRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &req.database, "Drop collection")
.await?;
ensure_writable(&state.app, &req.connection_id, "Drop collection").await?;
dbx_core::mongo_ops::mongo_drop_collection_core(&state.app, &req.connection_id, &req.database, &req.collection)
.await
@@ -344,8 +352,10 @@ pub async fn drop_collection(
pub async fn find_documents(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<MongoFindRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
super::mcp_policy::ensure_scope(&state, &headers, &req.connection_id).await?;
let result = run_cancellable(
&state,
req.execution_id.clone(),
@@ -388,8 +398,10 @@ pub async fn find_one(
pub async fn count_documents(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<MongoCountRequest>,
) -> Result<Json<u64>, AppError> {
super::mcp_policy::ensure_scope(&state, &headers, &req.connection_id).await?;
let result = run_cancellable(
&state,
req.execution_id,
@@ -408,8 +420,10 @@ pub async fn count_documents(
pub async fn server_version(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<MongoServerVersionRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
super::mcp_policy::ensure_scope(&state, &headers, &req.connection_id).await?;
let result = run_cancellable(
&state,
req.execution_id.clone(),
@@ -421,8 +435,10 @@ pub async fn server_version(
pub async fn collection_stats(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<MongoCollectionStatsRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
super::mcp_policy::ensure_scope(&state, &headers, &req.connection_id).await?;
let result = run_cancellable(
&state,
req.execution_id.clone(),
@@ -440,8 +456,28 @@ pub async fn collection_stats(
pub async fn aggregate_documents(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<MongoAggregateRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
super::mcp_policy::ensure_scope(&state, &headers, &req.connection_id).await?;
if super::mcp_policy::mongo_pipeline_has_write_stage(&req.pipeline_json) {
super::mcp_policy::ensure_dangerous_write(
&state,
&headers,
&req.connection_id,
&req.database,
"MongoDB aggregate write",
)
.await?;
super::mcp_policy::ensure_mongo_pipeline_target(
&state,
&headers,
&req.connection_id,
&req.database,
&req.pipeline_json,
)
.await?;
}
let result = run_cancellable(
&state,
req.execution_id.clone(),
@@ -461,8 +497,10 @@ pub async fn aggregate_documents(
pub async fn distinct(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<MongoDistinctRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
super::mcp_policy::ensure_scope(&state, &headers, &req.connection_id).await?;
let result = run_cancellable(
&state,
req.execution_id.clone(),
@@ -481,8 +519,11 @@ pub async fn distinct(
pub async fn create_index(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<MongoCreateIndexRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &req.database, "Create index")
.await?;
ensure_writable(&state.app, &req.connection_id, "Create index").await?;
let name = dbx_core::mongo_ops::mongo_create_index_core(
&state.app,
@@ -499,8 +540,11 @@ pub async fn create_index(
pub async fn drop_indexes(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<MongoDropIndexesRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &req.database, "Drop indexes")
.await?;
ensure_writable(&state.app, &req.connection_id, "Drop indexes").await?;
let result = dbx_core::mongo_ops::mongo_drop_indexes_core(
&state.app,
@@ -535,8 +579,10 @@ pub async fn insert_document(
pub async fn insert_documents(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<MongoInsertDocumentsRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
super::mcp_policy::ensure_write(&state, &headers, &req.connection_id, &req.database, "Insert").await?;
ensure_writable(&state.app, &req.connection_id, "Insert").await?;
let result = dbx_core::mongo_ops::mongo_insert_documents_core(
&state.app,
@@ -571,8 +617,15 @@ pub async fn update_document(
pub async fn update_documents(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<MongoUpdateDocumentsRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
if super::mcp_policy::mongo_filter_is_effectively_unbounded(&req.filter_json) {
super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &req.database, "Update")
.await?;
} else {
super::mcp_policy::ensure_write(&state, &headers, &req.connection_id, &req.database, "Update").await?;
}
ensure_writable(&state.app, &req.connection_id, "Update").await?;
let result = dbx_core::mongo_ops::mongo_update_documents_core(
&state.app,
@@ -591,8 +644,11 @@ pub async fn update_documents(
pub async fn find_one_and_update(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<MongoFindOneAndUpdateRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
ensure_find_one_write_policy(&state, &headers, &req.connection_id, &req.database, &req.filter_json, "Update")
.await?;
ensure_writable(&state.app, &req.connection_id, "Update").await?;
let result = dbx_core::mongo_ops::mongo_find_one_and_update_core(
&state.app,
@@ -610,8 +666,11 @@ pub async fn find_one_and_update(
pub async fn find_one_and_replace(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<MongoFindOneAndReplaceRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
ensure_find_one_write_policy(&state, &headers, &req.connection_id, &req.database, &req.filter_json, "Replace")
.await?;
ensure_writable(&state.app, &req.connection_id, "Update").await?;
let result = dbx_core::mongo_ops::mongo_find_one_and_replace_core(
&state.app,
@@ -629,8 +688,11 @@ pub async fn find_one_and_replace(
pub async fn find_one_and_delete(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<MongoFindOneAndDeleteRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
ensure_find_one_write_policy(&state, &headers, &req.connection_id, &req.database, &req.filter_json, "Delete")
.await?;
ensure_writable(&state.app, &req.connection_id, "Delete").await?;
let result = dbx_core::mongo_ops::mongo_find_one_and_delete_core(
&state.app,
@@ -665,8 +727,15 @@ pub async fn delete_document(
pub async fn delete_documents(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<MongoDeleteDocumentsRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
if super::mcp_policy::mongo_filter_is_effectively_unbounded(&req.filter_json) {
super::mcp_policy::ensure_dangerous_write(&state, &headers, &req.connection_id, &req.database, "Delete")
.await?;
} else {
super::mcp_policy::ensure_write(&state, &headers, &req.connection_id, &req.database, "Delete").await?;
}
ensure_writable(&state.app, &req.connection_id, "Delete").await?;
let result = dbx_core::mongo_ops::mongo_delete_documents_core(
&state.app,
@@ -680,3 +749,140 @@ pub async fn delete_documents(
.map_err(AppError)?;
Ok(Json(serde_json::json!({ "affected_rows": result })))
}
async fn ensure_find_one_write_policy(
state: &Arc<WebState>,
headers: &HeaderMap,
connection_id: &str,
database: &str,
filter_json: &str,
action: &str,
) -> Result<(), AppError> {
if super::mcp_policy::mongo_filter_is_effectively_unbounded(filter_json) {
super::mcp_policy::ensure_dangerous_write(state, headers, connection_id, database, action).await
} else {
super::mcp_policy::ensure_write(state, headers, connection_id, database, action).await
}
}
#[cfg(test)]
mod tests {
use super::ensure_find_one_write_policy;
use crate::state::{LoginRateLimit, WebState};
use axum::http::{HeaderMap, HeaderValue};
use dbx_core::connection::AppState;
use dbx_core::models::connection::ConnectionConfig;
use dbx_core::storage::{McpGlobalPolicy, Storage};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use tokio::sync::{Mutex, RwLock};
fn mongo_config(is_production: bool) -> ConnectionConfig {
serde_json::from_value(serde_json::json!({
"id": "mongo-policy-test",
"name": "Mongo policy test",
"db_type": "mongodb",
"host": "localhost",
"port": 27017,
"username": "tester",
"password": "",
"database": "app",
"is_production": is_production
}))
.unwrap()
}
async fn test_web_state() -> (Arc<WebState>, std::path::PathBuf) {
let dir = std::env::temp_dir().join(format!("dbx-web-mongo-policy-test-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
let storage = Storage::open(&dir.join("storage.db")).await.unwrap();
let app = Arc::new(AppState::new_with_plugin_dir(storage, dir.join("plugins")));
let state = Arc::new(WebState {
app,
data_dir: dir.clone(),
public_base_path: "/".to_string(),
password_disabled: false,
password_hash: RwLock::new(None),
sessions: RwLock::new(HashSet::new()),
sse_channels: RwLock::new(HashMap::new()),
sql_file_executions: RwLock::new(HashMap::new()),
login_rate_limit: Mutex::new(LoginRateLimit { fail_count: 0, locked_until: None }),
export_files: RwLock::new(HashMap::new()),
});
(state, dir)
}
fn mcp_headers() -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert("x-dbx-mcp-request", HeaderValue::from_static("1"));
headers
}
#[tokio::test]
async fn find_one_writes_recheck_policy_filter_production_and_allowlist() {
let (state, dir) = test_web_state().await;
let connection = mongo_config(false);
state.app.storage.save_connections(std::slice::from_ref(&connection)).await.unwrap();
let headers = mcp_headers();
let writable_policy = McpGlobalPolicy {
read_only: false,
allow_dangerous_sql: false,
allowed_connection_ids: Some(vec![connection.id.clone()]),
};
state.app.storage.save_mcp_global_policy(&writable_policy).await.unwrap();
assert!(ensure_find_one_write_policy(&state, &headers, &connection.id, "app", r#"{"_id":1}"#, "Update")
.await
.is_ok());
state
.app
.storage
.save_mcp_global_policy(&McpGlobalPolicy { read_only: true, ..writable_policy.clone() })
.await
.unwrap();
let revoked = ensure_find_one_write_policy(&state, &headers, &connection.id, "app", r#"{"_id":1}"#, "Update")
.await
.unwrap_err();
assert!(revoked.0.starts_with("MCP_READ_ONLY:"), "{}", revoked.0);
state.app.storage.save_mcp_global_policy(&writable_policy).await.unwrap();
let empty_filter =
ensure_find_one_write_policy(&state, &headers, &connection.id, "app", "{}", "Delete").await.unwrap_err();
assert!(empty_filter.0.starts_with("SQL_BLOCKED:"), "{}", empty_filter.0);
state
.app
.storage
.save_mcp_global_policy(&McpGlobalPolicy { allow_dangerous_sql: true, ..writable_policy.clone() })
.await
.unwrap();
assert!(ensure_find_one_write_policy(&state, &headers, &connection.id, "app", "{}", "Replace").await.is_ok());
state.app.storage.save_connections(&[mongo_config(true)]).await.unwrap();
let production =
ensure_find_one_write_policy(&state, &headers, &connection.id, "app", r#"{"_id":1}"#, "Update")
.await
.unwrap_err();
assert!(production.0.starts_with("PRODUCTION_DATABASE_READ_ONLY:"), "{}", production.0);
state.app.storage.save_connections(std::slice::from_ref(&connection)).await.unwrap();
state
.app
.storage
.save_mcp_global_policy(&McpGlobalPolicy {
read_only: false,
allow_dangerous_sql: true,
allowed_connection_ids: Some(vec!["different-connection".to_string()]),
})
.await
.unwrap();
let allowlist = ensure_find_one_write_policy(&state, &headers, &connection.id, "app", r#"{"_id":1}"#, "Delete")
.await
.unwrap_err();
assert!(allowlist.0.starts_with("CONNECTION_OUT_OF_SCOPE:"), "{}", allowlist.0);
drop(state);
let _ = std::fs::remove_dir_all(dir);
}
}
+9
View File
@@ -1,6 +1,7 @@
use std::sync::Arc;
use axum::extract::State;
use axum::http::HeaderMap;
use axum::Json;
use serde::Deserialize;
@@ -317,8 +318,10 @@ pub struct BuildDatabaseSqlExportRequest {
pub async fn execute_query(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<ExecuteQueryRequest>,
) -> Result<Json<dbx_core::db::QueryResult>, AppError> {
super::mcp_policy::ensure_sql(&state, &headers, &req.connection_id, &req.database, &req.sql).await?;
let execution_id = req.execution_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
let registered = state.app.running_queries.register_task(
@@ -358,8 +361,10 @@ pub async fn execute_query(
pub async fn execute_multi(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<ExecuteQueryRequest>,
) -> Result<Json<Vec<dbx_core::query::ExecuteMultiResult>>, AppError> {
super::mcp_policy::ensure_sql(&state, &headers, &req.connection_id, &req.database, &req.sql).await?;
let execution_id = req.execution_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
let registered = state.app.running_queries.register_task(
@@ -399,8 +404,12 @@ pub async fn execute_multi(
pub async fn execute_batch(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<ExecuteBatchRequest>,
) -> Result<Json<dbx_core::db::QueryResult>, AppError> {
for statement in &req.statements {
super::mcp_policy::ensure_sql(&state, &headers, &req.connection_id, &req.database, statement).await?;
}
tracing::debug!(connection_id = %req.connection_id, "execute_batch");
let result = dbx_core::query::execute_statements(
&state.app,
+33 -5
View File
@@ -1,6 +1,7 @@
use std::sync::Arc;
use axum::extract::State;
use axum::http::HeaderMap;
use axum::Json;
use serde::Deserialize;
@@ -518,14 +519,41 @@ pub async fn flush_db(
pub async fn execute_command(
State(state): State<Arc<WebState>>,
headers: HeaderMap,
Json(req): Json<RedisCommandRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
super::mcp_policy::ensure_scope(&state, &headers, &req.connection_id).await?;
let argv = dbx_core::db::redis_driver::parse_command_argv(&req.command)
.map_err(|error| AppError(format!("Invalid Redis command: {error}")))?;
let cmd_name = argv[0].to_ascii_uppercase();
let safety = dbx_core::db::redis_driver::classify_command(&cmd_name);
let is_mcp_request = super::mcp_policy::is_mcp_request(&headers);
let centrally_approved_high_risk =
is_mcp_request && safety == dbx_core::db::redis_driver::RedisCommandSafety::Blocked;
if safety != dbx_core::db::redis_driver::RedisCommandSafety::Allowed {
if centrally_approved_high_risk {
super::mcp_policy::ensure_dangerous_write(
&state,
&headers,
&req.connection_id,
&req.db.to_string(),
&format!("Redis command '{cmd_name}'"),
)
.await?;
} else {
super::mcp_policy::ensure_write(
&state,
&headers,
&req.connection_id,
&req.db.to_string(),
&format!("Redis command '{cmd_name}'"),
)
.await?;
}
}
// In read-only mode, only allow safe read commands
if let Some(name) = dbx_core::query::connection_readonly_name(&state.app, &req.connection_id).await {
let cmd_name = req.command.split_whitespace().next().unwrap_or("");
if dbx_core::db::redis_driver::classify_command(cmd_name)
!= dbx_core::db::redis_driver::RedisCommandSafety::Allowed
{
if safety != dbx_core::db::redis_driver::RedisCommandSafety::Allowed {
return Err(AppError(format!(
"Read-only mode: connection '{}' has read-only protection enabled. Command '{}' blocked.",
name, cmd_name
@@ -537,7 +565,7 @@ pub async fn execute_command(
&req.connection_id,
req.db,
&req.command,
req.skip_safety_check.unwrap_or(false),
if is_mcp_request { centrally_approved_high_risk } else { req.skip_safety_check.unwrap_or(false) },
)
.await
.map_err(AppError)?;