fix(ai): harden write SQL confirmation flow
This commit is contained in:
1 parent
1e72d28ed3
commit
cb9d0f7cbf
20 files changed
+1258
-51
No files matched your search
@@ -58,9 +58,13 @@ fn effective_mcp_policy_with_legacy_allow_writes(
|
||||
state: McpGlobalPolicyState,
|
||||
legacy_allow_writes: Option<bool>,
|
||||
) -> McpGlobalPolicy {
|
||||
let configured = state.configured;
|
||||
let mut policy = state.policy();
|
||||
if !configured && legacy_allow_writes == Some(false) {
|
||||
// When DBX_MCP_ALLOW_WRITES is explicitly set to false by the CLI agent
|
||||
// for an unconfirmed run, force read-only regardless of the configured
|
||||
// persistent MCP policy. Run-scoped CLI restrictions must override the
|
||||
// persistent policy, otherwise a user with a writable configured policy
|
||||
// can execute unconfirmed writes through CLI providers.
|
||||
if legacy_allow_writes == Some(false) {
|
||||
policy.read_only = true;
|
||||
}
|
||||
policy
|
||||
@@ -636,7 +640,7 @@ impl DbxBackend for WebBackend {
|
||||
database: &str,
|
||||
tool_name: &str,
|
||||
arguments: Value,
|
||||
_permissions: AgentSqlPermissions,
|
||||
permissions: AgentSqlPermissions,
|
||||
) -> ToolResult {
|
||||
let result = async {
|
||||
if tool_name != "execute_query" {
|
||||
@@ -649,6 +653,29 @@ impl DbxBackend for WebBackend {
|
||||
}
|
||||
self.ensure_connected(connection).await?;
|
||||
let sql = arguments.get("sql").and_then(Value::as_str).ok_or("Missing SQL query")?;
|
||||
|
||||
// Replicate the confirmed-SQL binding check here because the
|
||||
// /api/query/execute endpoint performs its own risk checks but
|
||||
// does NOT receive the confirmed_write_sql binding from the MCP
|
||||
// layer. Without this, a CLI/MCP agent could execute a different
|
||||
// write/DDL statement after a single user confirmation.
|
||||
let risk = dbx_core::sql_risk::classify_sql_risk_for_database(sql, connection.db_type)
|
||||
.map_err(|error| format!("SQL risk classification failed: {error}"))?;
|
||||
if risk != dbx_core::sql_risk::SqlRisk::ReadOnly {
|
||||
if let Some(ref confirmed) = permissions.confirmed_write_sql {
|
||||
let normalized = agent_tools::normalize_sql_for_confirmation(sql);
|
||||
let normalized_confirmed = agent_tools::normalize_sql_for_confirmation(confirmed);
|
||||
if normalized != normalized_confirmed {
|
||||
return Err(format!(
|
||||
"Blocked: the executed SQL does not match the user-confirmed SQL.\n\
|
||||
Confirmed: {}\n\
|
||||
Attempted: {}",
|
||||
confirmed, sql,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let max_rows = arguments.get("limit").and_then(Value::as_u64).unwrap_or(100) as usize;
|
||||
let response = self
|
||||
.request(
|
||||
@@ -1397,11 +1424,19 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_read_only_only_restricts_an_unconfigured_policy() {
|
||||
fn legacy_read_only_overrides_configured_and_unconfigured_policies() {
|
||||
// DBX_MCP_ALLOW_WRITES=0 always forces read_only, even when the
|
||||
// persistent MCP policy is configured as writable.
|
||||
assert!(effective_mcp_policy_with_legacy_allow_writes(policy_state(false, false), Some(false)).read_only);
|
||||
assert!(!effective_mcp_policy_with_legacy_allow_writes(policy_state(false, false), Some(true)).read_only);
|
||||
assert!(!effective_mcp_policy_with_legacy_allow_writes(policy_state(true, false), Some(false)).read_only);
|
||||
assert!(effective_mcp_policy_with_legacy_allow_writes(policy_state(true, false), Some(false)).read_only);
|
||||
assert!(!effective_mcp_policy_with_legacy_allow_writes(policy_state(true, false), Some(true)).read_only);
|
||||
// Configured read_only is a hard upper bound — env var cannot relax it.
|
||||
assert!(effective_mcp_policy_with_legacy_allow_writes(policy_state(true, true), Some(true)).read_only);
|
||||
assert!(effective_mcp_policy_with_legacy_allow_writes(policy_state(true, true), Some(false)).read_only);
|
||||
// Unset env var leaves the policy as-is.
|
||||
assert!(!effective_mcp_policy_with_legacy_allow_writes(policy_state(true, false), None).read_only);
|
||||
assert!(effective_mcp_policy_with_legacy_allow_writes(policy_state(true, true), None).read_only);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -793,9 +793,23 @@ fn mcp_permissions(
|
||||
dbx_core::agent_tools::AgentSqlPermissions {
|
||||
allow_writes: !policy.read_only && !connection.read_only,
|
||||
allow_dangerous: !policy.read_only && !connection.read_only && policy.allow_dangerous_sql,
|
||||
confirmed_write_sql: mcp_confirmed_write_sql_from_env(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the DBX_MCP_CONFIRMED_WRITE_SQL env var (set by the CLI agent when the
|
||||
/// user confirmed a specific write SQL). Returns None when the var is unset or
|
||||
/// empty, so desktop-embedded MCP contexts (which don't set this var) continue
|
||||
/// to work without a confirmed-SQL binding.
|
||||
fn mcp_confirmed_write_sql_from_env() -> Option<String> {
|
||||
normalize_confirmed_write_sql(std::env::var("DBX_MCP_CONFIRMED_WRITE_SQL").ok())
|
||||
}
|
||||
|
||||
fn normalize_confirmed_write_sql(value: Option<String>) -> Option<String> {
|
||||
let trimmed = value?.trim().to_string();
|
||||
(!trimmed.is_empty()).then_some(trimmed)
|
||||
}
|
||||
|
||||
// CallToolResult is the transport-native error payload; boxing it would complicate every MCP call site.
|
||||
#[allow(clippy::result_large_err)]
|
||||
fn validate_sql_policy(
|
||||
@@ -823,13 +837,24 @@ fn validate_sql_policy(
|
||||
));
|
||||
}
|
||||
let high_risk = risk == SqlRisk::Ddl || is_dangerous_sql_for_database(sql, connection.db_type);
|
||||
if high_risk && !policy.allow_dangerous_sql {
|
||||
let confirmed_sql = mcp_confirmed_write_sql_from_env();
|
||||
if high_risk && !policy.allow_dangerous_sql && confirmed_sql.is_none() {
|
||||
return Err(tool_error("SQL_BLOCKED", "High-risk SQL is disabled in DBX MCP settings."));
|
||||
}
|
||||
if is_write && targets_production_database(connection, database, sql) {
|
||||
return Err(tool_error("PRODUCTION_WRITE_BLOCKED", "MCP cannot execute writes against a production database."));
|
||||
}
|
||||
Ok(mcp_permissions(connection, policy))
|
||||
let mut permissions = mcp_permissions(connection, policy);
|
||||
// When the user confirmed a specific write/DDL SQL via the CLI agent, the
|
||||
// confirmed-SQL binding authorises dangerous (DDL) execution in the SQL
|
||||
// path only. The precise SQL match check (sql_matches_confirmed_write) in
|
||||
// agent_tools still guards execution — only the exact confirmed statement
|
||||
// can run. Redis and Mongo paths are unaffected; they continue to use the
|
||||
// persistent policy (mcp_permissions) without any confirmed-SQL elevation.
|
||||
if confirmed_sql.is_some() {
|
||||
permissions.allow_dangerous = true;
|
||||
}
|
||||
Ok(permissions)
|
||||
}
|
||||
|
||||
// CallToolResult is the transport-native error payload; boxing it would complicate every MCP call site.
|
||||
@@ -1225,4 +1250,92 @@ mod tests {
|
||||
});
|
||||
assert!(result_text(&result).contains("Error [MCP_READ_ONLY]: policy changed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_confirmation_and_policy_guards_fail_closed() {
|
||||
assert_eq!(
|
||||
normalize_confirmed_write_sql(Some(" DELETE FROM sessions WHERE id = 7 ".to_string())),
|
||||
Some("DELETE FROM sessions WHERE id = 7".to_string())
|
||||
);
|
||||
assert_eq!(normalize_confirmed_write_sql(Some(" \n ".to_string())), None);
|
||||
|
||||
let read_only = ConnectionConfig { read_only: true, ..connection("readonly", "readonly", "postgres", "app") };
|
||||
let writable_policy =
|
||||
McpGlobalPolicy { read_only: false, allow_dangerous_sql: true, allowed_connection_ids: None };
|
||||
let read_only_error =
|
||||
validate_sql_policy(&read_only, &writable_policy, "app", "DELETE FROM sessions").unwrap_err();
|
||||
assert!(result_text(&read_only_error).contains("CONNECTION_READ_ONLY"));
|
||||
|
||||
let mut production = connection("production", "production", "postgres", "app");
|
||||
production.production_databases = vec!["app".to_string()];
|
||||
let production_error =
|
||||
validate_sql_policy(&production, &writable_policy, "app", "DROP TABLE sessions").unwrap_err();
|
||||
assert!(result_text(&production_error).contains("PRODUCTION_WRITE_BLOCKED"));
|
||||
}
|
||||
|
||||
/// RAII guard that sets an env var and restores the original value (or
|
||||
/// removes the var) on drop. Panic-safe — cleanup runs even when an
|
||||
/// assertion fails.
|
||||
struct EnvGuard {
|
||||
key: &'static str,
|
||||
original: Option<String>,
|
||||
}
|
||||
|
||||
impl EnvGuard {
|
||||
fn set(key: &'static str, value: &str) -> Self {
|
||||
let original = std::env::var(key).ok();
|
||||
std::env::set_var(key, value);
|
||||
Self { key, original }
|
||||
}
|
||||
|
||||
fn remove(key: &'static str) -> Self {
|
||||
let original = std::env::var(key).ok();
|
||||
std::env::remove_var(key);
|
||||
Self { key, original }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for EnvGuard {
|
||||
fn drop(&mut self) {
|
||||
match &self.original {
|
||||
Some(original) => std::env::set_var(self.key, original),
|
||||
None => std::env::remove_var(self.key),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confirmed_sql_binding_tests() {
|
||||
let connection = connection("dev", "dev", "postgres", "app");
|
||||
|
||||
// 1. mcp_permissions (Redis/Mongo path) must NOT elevate allow_dangerous.
|
||||
let _guard = EnvGuard::set("DBX_MCP_CONFIRMED_WRITE_SQL", "CREATE TABLE metrics (id INT)");
|
||||
let policy = McpGlobalPolicy { read_only: false, allow_dangerous_sql: false, allowed_connection_ids: None };
|
||||
let permissions = mcp_permissions(&connection, &policy);
|
||||
assert!(!permissions.allow_dangerous, "confirmed SQL must NOT elevate allow_dangerous for Redis/Mongo paths");
|
||||
assert!(permissions.allow_writes);
|
||||
assert_eq!(permissions.confirmed_write_sql.as_deref(), Some("CREATE TABLE metrics (id INT)"));
|
||||
|
||||
// 2. SQL path (validate_sql_policy) elevates allow_dangerous with a confirmed binding.
|
||||
let permissions = validate_sql_policy(&connection, &policy, "app", "CREATE TABLE metrics (id INT)").unwrap();
|
||||
assert!(permissions.allow_dangerous, "SQL path should elevate allow_dangerous with confirmed binding");
|
||||
assert!(permissions.allow_writes);
|
||||
assert_eq!(permissions.confirmed_write_sql.as_deref(), Some("CREATE TABLE metrics (id INT)"));
|
||||
drop(_guard);
|
||||
|
||||
// 3. Without a confirmed binding, high-risk SQL is blocked.
|
||||
let _guard = EnvGuard::remove("DBX_MCP_CONFIRMED_WRITE_SQL");
|
||||
let error = validate_sql_policy(&connection, &policy, "app", "DROP TABLE sessions").unwrap_err();
|
||||
assert!(result_text(&error).contains("SQL_BLOCKED"));
|
||||
assert!(result_text(&error).contains("High-risk SQL is disabled"));
|
||||
drop(_guard);
|
||||
|
||||
// 4. Confirmed SQL must not bypass global read_only.
|
||||
let _guard = EnvGuard::set("DBX_MCP_CONFIRMED_WRITE_SQL", "CREATE TABLE metrics (id INT)");
|
||||
let read_only_policy =
|
||||
McpGlobalPolicy { read_only: true, allow_dangerous_sql: false, allowed_connection_ids: None };
|
||||
let error =
|
||||
validate_sql_policy(&connection, &read_only_policy, "app", "CREATE TABLE metrics (id INT)").unwrap_err();
|
||||
assert!(result_text(&error).contains("MCP_READ_ONLY"), "confirmed SQL must not bypass global read_only");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user