From 8f3351f720f3581cbbe9627f3458134e32b7f8d5 Mon Sep 17 00:00:00 2001 From: Melody Ruch <396921921@qq.com> Date: Sat, 15 Aug 2026 18:57:22 +0800 Subject: [PATCH] fix(mcp): enforce read-only SQL classification consistently --- crates/dbx-core/src/sql_risk.rs | 109 +++++++++++++++++++++++-------- crates/dbx-mcp/src/server.rs | 6 +- crates/dbx-mcp/tests/protocol.rs | 108 ++++++++++++++++++++++++++++++ 3 files changed, 194 insertions(+), 29 deletions(-) diff --git a/crates/dbx-core/src/sql_risk.rs b/crates/dbx-core/src/sql_risk.rs index 827dd154cb..5bd7fa5be6 100644 --- a/crates/dbx-core/src/sql_risk.rs +++ b/crates/dbx-core/src/sql_risk.rs @@ -88,20 +88,19 @@ fn classify_statement(stmt: &Statement, detect_select_into: bool) -> SqlRisk { // Show/Describe variants Statement::ShowTables { .. } | Statement::ShowColumns { .. } + | Statement::ShowCatalogs { .. } | Statement::ShowDatabases { .. } | Statement::ShowSchemas { .. } + | Statement::ShowViews { .. } + | Statement::ShowFunctions { .. } | Statement::ShowCreate { .. } + | Statement::ShowVariable { .. } | Statement::ShowVariables { .. } | Statement::ShowStatus { .. } - | Statement::ShowProcessList { .. } => SqlRisk::ReadOnly, - - // sqlparser has no dedicated MySQL `SHOW TRIGGERS` node and uses its - // loose `ShowVariable` fallback, with TRIGGERS as the first identifier. - Statement::ShowVariable { variable } - if variable.first().is_some_and(|identifier| identifier.value.eq_ignore_ascii_case("triggers")) => - { - SqlRisk::ReadOnly - } + | Statement::ShowProcessList { .. } + | Statement::ShowCharset(_) + | Statement::ShowObjects(_) + | Statement::ShowCollation { .. } => SqlRisk::ReadOnly, // Write operations Statement::Insert { .. } | Statement::Update { .. } | Statement::Delete { .. } | Statement::Merge { .. } => { @@ -709,7 +708,7 @@ pub fn is_dangerous_sql_for_database(sql: &str, database_type: DatabaseType) -> let normalized = normalize_dialect(&database_type_name); let parser_dialect = resolve_dialect(normalized); let detect_select_into = supports_select_into_table_creation(database_type); - let has_locking_clause = sql_contains_top_level_locking_clause(sql, parser_dialect.as_ref()); + let has_locking_clause = sql_contains_locking_clause(sql, parser_dialect.as_ref()); // PostgreSQL-family and SQL Server SELECT INTO forms are represented in // the AST. Their text fallback also matches ordinary INSERT INTO, so only // use it for dialect-specific writes that the selected AST cannot express @@ -805,7 +804,7 @@ fn classify_sql_risk_with_database( ) -> Result { let parser_dialect = resolve_dialect(normalized_dialect); let detect_select_into = database_type.is_none(); - let has_locking_clause = sql_contains_top_level_locking_clause(sql, parser_dialect.as_ref()); + let has_locking_clause = sql_contains_locking_clause(sql, parser_dialect.as_ref()); let has_dialect_specific_write = match database_type { Some(database_type) => crate::query_execution_sql::has_dialect_specific_write(sql, database_type), // Preserve MySQL executable-comment and file-output detection even @@ -846,32 +845,35 @@ fn classify_sql_risk_with_database( } } -fn sql_contains_top_level_locking_clause(sql: &str, dialect: &dyn sqlparser::dialect::Dialect) -> bool { +fn sql_contains_locking_clause(sql: &str, dialect: &dyn sqlparser::dialect::Dialect) -> bool { let Ok(tokens) = Tokenizer::new(dialect, sql).tokenize() else { return false; }; - let mut depth: usize = 0; - let mut words = Vec::new(); + let mut words: Vec = Vec::with_capacity(4); for token in tokens { match token { - Token::LParen => depth += 1, - Token::RParen => depth = depth.saturating_sub(1), - token if depth == 0 => { - let word = token.to_string(); - if word.chars().all(|character| character.is_ascii_alphabetic() || character == '_') { - words.push(word.to_ascii_uppercase()); + Token::Word(word) if word.quote_style.is_none() => { + words.push(word.value.to_ascii_uppercase()); + if words.len() > 4 { + words.remove(0); + } + if words.windows(2).any(|window| { + matches!(window, [r#for, lock] if r#for == "FOR" && matches!(lock.as_str(), "UPDATE" | "SHARE")) + }) || words.windows(3).any(|window| { + matches!(window, [r#for, key, share] if r#for == "FOR" && key == "KEY" && share == "SHARE") + }) || words.windows(4).any(|window| { + matches!(window, [r#for, no, key, update] if r#for == "FOR" && no == "NO" && key == "KEY" && update == "UPDATE") + }) || words.windows(4).any(|window| { + matches!(window, [lock, r#in, share, mode] if lock == "LOCK" && r#in == "IN" && share == "SHARE" && mode == "MODE") + }) { + return true; } } - _ => {} + Token::Whitespace(_) => {} + _ => words.clear(), } } - words.windows(2).any(|window| matches!(window, [r#for, lock] if r#for == "FOR" && matches!(lock.as_str(), "UPDATE" | "SHARE"))) - || words.windows(3).any(|window| { - matches!(window, [r#for, key, share] if r#for == "FOR" && key == "KEY" && share == "SHARE") - }) - || words.windows(4).any(|window| { - matches!(window, [r#for, no, key, update] if r#for == "FOR" && no == "NO" && key == "KEY" && update == "UPDATE") - }) + false } #[cfg(test)] @@ -907,6 +909,21 @@ mod tests { } } + #[test] + fn classify_supported_show_statements_as_read_only() { + for (sql, database_type) in [ + ("SHOW COLLATION", DatabaseType::Mysql), + ("SHOW CHARACTER SET", DatabaseType::Mysql), + ("SHOW search_path", DatabaseType::Postgres), + ] { + assert_eq!( + classify_sql_risk_for_database(sql, database_type).unwrap(), + SqlRisk::ReadOnly, + "expected read-only: {sql}" + ); + } + } + #[test] fn mysql_show_triggers_preserves_write_detection() { for (sql, expected_risk) in [ @@ -924,6 +941,42 @@ mod tests { } } + #[test] + fn classify_mysql_legacy_shared_lock_reads_like_for_share() { + // MySQL's pre-8.0.1 spelling of `FOR SHARE` is still valid in 8.0.x and + // takes the same shared row locks, so it must not classify as a plain read. + for sql in [ + "SELECT * FROM users LOCK IN SHARE MODE", + "SELECT * FROM users lock in share mode", + "SELECT id FROM users WHERE id = 1 LOCK IN SHARE MODE", + "WITH c AS (SELECT 1) SELECT * FROM users LOCK IN SHARE MODE", + "SELECT * FROM (SELECT * FROM users LOCK IN SHARE MODE) AS locked_users", + "WITH locked AS (SELECT * FROM users LOCK IN SHARE MODE) SELECT * FROM locked", + "SELECT (SELECT id FROM users LOCK IN SHARE MODE)", + ] { + assert_eq!( + classify_sql_risk_for_database(sql, DatabaseType::Mysql).unwrap(), + SqlRisk::Write, + "expected locking read to be write-capable: {sql}" + ); + assert!(is_dangerous_sql_for_database(sql, DatabaseType::Mysql), "expected high-risk SQL: {sql}"); + } + + // A column or alias literally named "mode" must stay a plain read. + for sql in [ + "SELECT lock_in_share_mode FROM settings", + "SELECT mode FROM share WHERE id = 1", + "SELECT 'LOCK IN SHARE MODE'", + "SELECT lock, `in`, share, mode FROM settings", + ] { + assert_eq!( + classify_sql_risk_for_database(sql, DatabaseType::Mysql).unwrap(), + SqlRisk::ReadOnly, + "expected plain read: {sql}" + ); + } + } + #[test] fn classify_cte_read() { assert_eq!( diff --git a/crates/dbx-mcp/src/server.rs b/crates/dbx-mcp/src/server.rs index 56bccffa23..be7d754fe9 100644 --- a/crates/dbx-mcp/src/server.rs +++ b/crates/dbx-mcp/src/server.rs @@ -1096,7 +1096,11 @@ fn validate_sql_policy( if risk == SqlRisk::Transaction { return Err(tool_error("SQL_BLOCKED", "Transaction statements are not supported by MCP.")); } - let is_write = is_write_sql_for_database(sql, connection.db_type); + // The keyword scan alone misses write-capable SQL that the risk classifier + // does recognize (locking reads, side-effect functions, writable CTEs), and + // those statements would otherwise reach the database whenever high-risk SQL + // is permitted. Fail closed on either signal so read-only stays read-only. + let is_write = risk != SqlRisk::ReadOnly || is_write_sql_for_database(sql, connection.db_type); if policy.read_only && is_write { return Err(tool_error("MCP_READ_ONLY", "DBX global MCP read-only mode is enabled. SQL write blocked.")); } diff --git a/crates/dbx-mcp/tests/protocol.rs b/crates/dbx-mcp/tests/protocol.rs index c04b67dedc..547474de61 100644 --- a/crates/dbx-mcp/tests/protocol.rs +++ b/crates/dbx-mcp/tests/protocol.rs @@ -126,6 +126,36 @@ fn test_connection(id: &str, name: &str) -> ConnectionConfig { .expect("test connection") } +fn mysql_connection(id: &str, name: &str) -> ConnectionConfig { + serde_json::from_value(json!({ + "id": id, + "name": name, + "db_type": "mysql", + "host": "localhost", + "port": 3306, + "username": "tester", + "password": "", + "database": "reporting", + "ssl": false + })) + .expect("test MySQL connection") +} + +fn postgres_connection(id: &str, name: &str) -> ConnectionConfig { + serde_json::from_value(json!({ + "id": id, + "name": name, + "db_type": "postgres", + "host": "localhost", + "port": 5432, + "username": "tester", + "password": "", + "database": "reporting", + "ssl": false + })) + .expect("test PostgreSQL connection") +} + #[tokio::test] async fn initializes_lists_tools_and_calls_a_tool() { let (server_transport, client_transport) = tokio::io::duplex(16 * 1024); @@ -213,6 +243,84 @@ async fn enforces_global_connection_scope_and_read_only_policy() { server_task.abort(); } +/// Regression for issue #6053: MCP read-only mode let some write-capable SQL +/// through because the read-only gate consulted only the keyword heuristic and +/// ignored the SQL risk classifier it had already computed. +#[tokio::test] +async fn read_only_policy_blocks_write_capable_sql_the_keyword_scan_misses() { + for (allow_dangerous_sql, sql) in [ + // MySQL's legacy spelling of FOR SHARE — takes the same shared row + // locks and is reachable with the plain read-only execution mode. + (false, "SELECT * FROM users LOCK IN SHARE MODE"), + (true, "SELECT * FROM users LOCK IN SHARE MODE"), + (true, "SELECT * FROM users FOR SHARE"), + ] { + let backend = PolicyBackend { + policy: McpGlobalPolicy { read_only: true, allow_dangerous_sql, allowed_connection_ids: None }, + connections: vec![mysql_connection("mysql", "reporting")], + group_paths: Ok(HashMap::new()), + }; + let (server_transport, client_transport) = tokio::io::duplex(16 * 1024); + let server = DbxMcpServer::with_runtime_options(Arc::new(backend), McpScope::default(), false); + let server_task = tokio::spawn(async move { server.serve(server_transport).await }); + let client = ().serve(client_transport).await.expect("initialize MCP client"); + + let result = client + .peer() + .call_tool(CallToolRequestParams::new("dbx_execute_query").with_arguments( + json!({ "connection_id": "mysql", "sql": sql }).as_object().cloned().unwrap_or_else(Map::new), + )) + .await + .expect("call read-only policy"); + let text = result.content[0].as_text().expect("tool result text").text.clone(); + assert_eq!( + result.is_error, + Some(true), + "{sql} (allow_dangerous_sql={allow_dangerous_sql}) reached the backend" + ); + assert!( + text.contains("MCP_READ_ONLY"), + "expected MCP_READ_ONLY for {sql} (allow_dangerous_sql={allow_dangerous_sql}), got: {text}" + ); + + client.cancel().await.expect("close MCP client"); + server_task.abort(); + } +} + +#[tokio::test] +async fn read_only_policy_allows_read_only_show_statements() { + for (connection, sql) in [ + (mysql_connection("mysql", "reporting"), "SHOW COLLATION"), + (postgres_connection("postgres", "reporting"), "SHOW search_path"), + ] { + let connection_id = connection.id.clone(); + let backend = PolicyBackend { + policy: McpGlobalPolicy { read_only: true, allow_dangerous_sql: false, allowed_connection_ids: None }, + connections: vec![connection], + group_paths: Ok(HashMap::new()), + }; + let (server_transport, client_transport) = tokio::io::duplex(16 * 1024); + let server = DbxMcpServer::with_runtime_options(Arc::new(backend), McpScope::default(), false); + let server_task = tokio::spawn(async move { server.serve(server_transport).await }); + let client = ().serve(client_transport).await.expect("initialize MCP client"); + + let result = client + .peer() + .call_tool(CallToolRequestParams::new("dbx_execute_query").with_arguments( + json!({ "connection_id": connection_id, "sql": sql }).as_object().cloned().unwrap_or_else(Map::new), + )) + .await + .expect("call read-only policy"); + let text = result.content[0].as_text().expect("tool result text").text.clone(); + assert!(!text.contains("MCP_READ_ONLY"), "read-only SHOW was blocked: {sql}: {text}"); + assert!(text.contains("query should have been blocked"), "expected {sql} to reach the backend, got: {text}"); + + client.cancel().await.expect("close MCP client"); + server_task.abort(); + } +} + #[tokio::test] async fn duplicate_connection_rejects_ambiguous_source_names() { let backend = PolicyBackend {