From e435d733a1ac62f0ce58843737b789a885747dd6 Mon Sep 17 00:00:00 2001 From: ZhuchkaTriplesix Date: Sun, 15 Nov 2026 13:10:25 +0300 Subject: [PATCH 1/2] feat(rust): sqlparser-rs multi-statement guard for query execute (#1884) Reject empty and multi-statement SQL at db_execute_query with a typed SqlGuard error so drivers only ever see one statement per call. --- apps/tauri/src-tauri/Cargo.lock | 72 +++++++ apps/tauri/src-tauri/Cargo.toml | 1 + apps/tauri/src-tauri/src/connection/error.rs | 15 ++ .../tauri/src-tauri/src/connection/manager.rs | 42 +++- apps/tauri/src-tauri/src/connection/mod.rs | 1 + .../src-tauri/src/connection/sql_guard.rs | 180 ++++++++++++++++++ 6 files changed, 306 insertions(+), 5 deletions(-) create mode 100644 apps/tauri/src-tauri/src/connection/sql_guard.rs diff --git a/apps/tauri/src-tauri/Cargo.lock b/apps/tauri/src-tauri/Cargo.lock index 08a0a430..e881438b 100644 --- a/apps/tauri/src-tauri/Cargo.lock +++ b/apps/tauri/src-tauri/Cargo.lock @@ -65,6 +65,15 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object", +] + [[package]] name = "async-broadcast" version = "0.7.2" @@ -2735,6 +2744,15 @@ dependencies = [ "objc2-foundation", ] +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -3140,6 +3158,16 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + [[package]] name = "querya_desktop_tauri" version = "0.1.0" @@ -3151,6 +3179,7 @@ dependencies = [ "rusqlite", "serde", "serde_json", + "sqlparser", "sqlx", "tauri", "tauri-build", @@ -3226,6 +3255,26 @@ version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" +[[package]] +name = "recursive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0786a43debb760f491b1bc0269fe5e84155353c67482b9e60d0cfb596054b43e" +dependencies = [ + "recursive-proc-macro-impl", + "stacker", +] + +[[package]] +name = "recursive-proc-macro-impl" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76009fbe0614077fc1a2ce255e3a1881a2e3a3527097d5dc6d8212c585e7e38b" +dependencies = [ + "quote", + "syn 2.0.119", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -3928,6 +3977,16 @@ dependencies = [ "der", ] +[[package]] +name = "sqlparser" +version = "0.64.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e0d273b4f8ddd14a35ed36862acbc9cc96cec578e36ee1881a9d42e0e0f2c8" +dependencies = [ + "log", + "recursive", +] + [[package]] name = "sqlx" version = "0.8.6" @@ -4126,6 +4185,19 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + [[package]] name = "static_vcruntime" version = "3.0.0" diff --git a/apps/tauri/src-tauri/Cargo.toml b/apps/tauri/src-tauri/Cargo.toml index 5060b3ac..2435e08c 100644 --- a/apps/tauri/src-tauri/Cargo.toml +++ b/apps/tauri/src-tauri/Cargo.toml @@ -31,6 +31,7 @@ sqlx = { version = "0.8", default-features = false, features = [ futures-util = "0.3" chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } keyring = { version = "3", features = ["apple-native", "windows-native", "linux-native-sync-persistent"] } +sqlparser = "0.64" [profile.release] codegen-units = 1 diff --git a/apps/tauri/src-tauri/src/connection/error.rs b/apps/tauri/src-tauri/src/connection/error.rs index 69bb387b..a3bbb538 100644 --- a/apps/tauri/src-tauri/src/connection/error.rs +++ b/apps/tauri/src-tauri/src/connection/error.rs @@ -13,6 +13,8 @@ pub enum ConnectionError { UnsupportedDriver { driver: DriverKind }, Io { message: String }, Driver { driver: DriverKind, message: String }, + /// sqlparser / product SQL guard refusal (`rule` is a stable id). + SqlGuard { rule: String, message: String }, } impl ConnectionError { @@ -34,6 +36,16 @@ impl ConnectionError { message: message.into(), } } + + pub fn sql_guard( + rule: super::sql_guard::SqlGuardRule, + message: impl Into, + ) -> Self { + Self::SqlGuard { + rule: rule.as_str().to_owned(), + message: message.into(), + } + } } impl fmt::Display for ConnectionError { @@ -50,6 +62,9 @@ impl fmt::Display for ConnectionError { Self::Driver { driver, message } => { write!(f, "{driver} error: {message}") } + Self::SqlGuard { rule, message } => { + write!(f, "sql guard ({rule}): {message}") + } } } } diff --git a/apps/tauri/src-tauri/src/connection/manager.rs b/apps/tauri/src-tauri/src/connection/manager.rs index 648ae9b9..5e4d19c6 100644 --- a/apps/tauri/src-tauri/src/connection/manager.rs +++ b/apps/tauri/src-tauri/src/connection/manager.rs @@ -203,13 +203,16 @@ impl ConnectionRegistry { limit: Option, emit: impl FnMut(QueryEvent) -> ConnectionResult<()>, ) -> ConnectionResult<()> { - match self.driver_of(id) { - Some(DriverKind::Sqlite) => self.execute_sqlite_query(id, sql, limit, emit), - Some(DriverKind::Postgres) => { + let driver = self + .driver_of(id) + .ok_or_else(|| ConnectionError::NotFound { id: id.clone() })?; + super::sql_guard::assert_single_statement(sql, driver)?; + match driver { + DriverKind::Sqlite => self.execute_sqlite_query(id, sql, limit, emit), + DriverKind::Postgres => { self.with_postgres(id, |s| s.execute_streaming(sql, limit, emit)) } - Some(other) => Err(ConnectionError::UnsupportedDriver { driver: other }), - None => Err(ConnectionError::NotFound { id: id.clone() }), + other => Err(ConnectionError::UnsupportedDriver { driver: other }), } } @@ -407,6 +410,35 @@ mod tests { assert!(matches!(err, ConnectionError::InvalidConfig { .. })); } + #[test] + fn execute_query_rejects_multi_statement() { + let path = std::env::temp_dir().join(format!( + "querya_reg_guard_{}.db", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let _ = rusqlite::Connection::open(&path).unwrap(); + let reg = ConnectionRegistry::with_builtin_drivers(); + let id = reg + .connect(ConnectionConfig::Sqlite { + path: path.to_string_lossy().into(), + id: None, + }) + .unwrap(); + let err = reg + .execute_query(&id, "SELECT 1; SELECT 2", None, |_| Ok(())) + .unwrap_err(); + match err { + ConnectionError::SqlGuard { rule, .. } => { + assert_eq!(rule, "single_statement"); + } + other => panic!("expected SqlGuard, got {other:?}"), + } + let _ = std::fs::remove_file(&path); + } + #[test] fn execute_sqlite_query_streams_via_session() { let path = std::env::temp_dir().join(format!( diff --git a/apps/tauri/src-tauri/src/connection/mod.rs b/apps/tauri/src-tauri/src/connection/mod.rs index 567b3ee7..21510258 100644 --- a/apps/tauri/src-tauri/src/connection/mod.rs +++ b/apps/tauri/src-tauri/src/connection/mod.rs @@ -11,6 +11,7 @@ pub(crate) mod postgres_query; mod query; mod runtime; mod smoke_slice; +mod sql_guard; mod sqlite; mod sqlite_introspect; mod sqlite_object_tree; diff --git a/apps/tauri/src-tauri/src/connection/sql_guard.rs b/apps/tauri/src-tauri/src/connection/sql_guard.rs new file mode 100644 index 00000000..46a7034a --- /dev/null +++ b/apps/tauri/src-tauri/src/connection/sql_guard.rs @@ -0,0 +1,180 @@ +//! sqlparser-rs multi-statement guard (Flutter MCP / table-browser parity). +//! +//! Product rule for `db_execute_query`: exactly one statement per call. +//! Trailing semicolons and comments are fine; scripts with two+ statements +//! are refused so the UI (or a later splitter) must send them separately. +//! `#1885` will layer dangerous-DML confirmation on top of this gate. + +use super::error::{ConnectionError, ConnectionResult}; +use super::id::DriverKind; +use sqlparser::dialect::{GenericDialect, MySqlDialect, PostgreSqlDialect, SQLiteDialect}; +use sqlparser::parser::Parser; + +/// Stable rule ids for typed IPC / future audit logs. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SqlGuardRule { + Empty, + MultiStatement, + Parse, +} + +impl SqlGuardRule { + pub fn as_str(self) -> &'static str { + match self { + Self::Empty => "empty_query", + Self::MultiStatement => "single_statement", + Self::Parse => "parse_error", + } + } +} + +const EMPTY_QUERY_MSG: &str = "The query is empty."; + +fn empty_err() -> ConnectionError { + ConnectionError::sql_guard(SqlGuardRule::Empty, EMPTY_QUERY_MSG) +} + +fn parse_err(e: impl std::fmt::Display) -> ConnectionError { + ConnectionError::sql_guard(SqlGuardRule::Parse, format!("SQL parse error: {e}")) +} + +/// Parse `sql` and ensure it is exactly one statement for `driver`. +pub fn assert_single_statement(sql: &str, driver: DriverKind) -> ConnectionResult<()> { + let trimmed = sql.trim(); + if trimmed.is_empty() { + return Err(empty_err()); + } + + let count = statement_count(trimmed, driver)?; + match count { + 0 => Err(empty_err()), + 1 => Ok(()), + n => Err(ConnectionError::sql_guard( + SqlGuardRule::MultiStatement, + format!( + "Only one statement per call is allowed; got {n}. Send them separately." + ), + )), + } +} + +fn statement_count(sql: &str, driver: DriverKind) -> ConnectionResult { + let primary = match driver { + DriverKind::Postgres => Parser::parse_sql(&PostgreSqlDialect {}, sql), + DriverKind::Sqlite => Parser::parse_sql(&SQLiteDialect {}, sql), + DriverKind::Mysql => Parser::parse_sql(&MySqlDialect {}, sql), + }; + + let statements = match primary { + Ok(stmts) => stmts, + Err(primary_err) if !matches!(driver, DriverKind::Mysql) => { + Parser::parse_sql(&GenericDialect {}, sql).map_err(|_| parse_err(primary_err))? + } + Err(primary_err) => return Err(parse_err(primary_err)), + }; + + Ok(statements.len()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn allow(sql: &str, driver: DriverKind) { + assert_single_statement(sql, driver).unwrap_or_else(|e| { + panic!("expected allow for {sql:?} ({driver}): {e}"); + }); + } + + fn block_rule(sql: &str, driver: DriverKind, rule: SqlGuardRule) { + let err = assert_single_statement(sql, driver).expect_err("expected block"); + match err { + ConnectionError::SqlGuard { rule: r, .. } => assert_eq!(r, rule.as_str()), + other => panic!("expected SqlGuard, got {other:?}"), + } + } + + #[test] + fn allows_single_select() { + allow("SELECT 1", DriverKind::Sqlite); + allow("SELECT * FROM t", DriverKind::Postgres); + allow("SELECT 1", DriverKind::Mysql); + } + + #[test] + fn allows_trailing_semicolon_and_comment() { + allow("SELECT * FROM t;", DriverKind::Postgres); + allow("SELECT * FROM t; -- done", DriverKind::Postgres); + allow("SELECT 1; /* trailing */", DriverKind::Sqlite); + } + + #[test] + fn allows_with_select_and_values() { + allow( + "WITH x AS (SELECT 1) SELECT * FROM x", + DriverKind::Postgres, + ); + allow("VALUES (1)", DriverKind::Postgres); + allow("(SELECT 1)", DriverKind::Postgres); + } + + #[test] + fn allows_semicolon_inside_string_literal() { + allow( + "SELECT * FROM logs WHERE message = 'error; system halted'", + DriverKind::Postgres, + ); + allow("SELECT 'a;b' AS x", DriverKind::Sqlite); + } + + #[test] + fn allows_single_dml_for_now() { + // Dangerous-DML confirmation is #1885; this gate only counts statements. + allow("DELETE FROM t", DriverKind::Postgres); + allow("UPDATE t SET a = 1", DriverKind::Sqlite); + allow("INSERT INTO t VALUES (1)", DriverKind::Mysql); + } + + #[test] + fn rejects_multi_statement_even_when_first_is_select() { + block_rule( + "SELECT 1; DELETE FROM t", + DriverKind::Postgres, + SqlGuardRule::MultiStatement, + ); + block_rule( + "SELECT 1; SELECT 2", + DriverKind::Sqlite, + SqlGuardRule::MultiStatement, + ); + block_rule( + "SELECT 1; SELECT 2; SELECT 3", + DriverKind::Mysql, + SqlGuardRule::MultiStatement, + ); + } + + #[test] + fn rejects_empty_and_whitespace() { + block_rule("", DriverKind::Sqlite, SqlGuardRule::Empty); + block_rule(" \n\t ", DriverKind::Postgres, SqlGuardRule::Empty); + block_rule("-- only a comment", DriverKind::Postgres, SqlGuardRule::Empty); + block_rule("/* block */", DriverKind::Sqlite, SqlGuardRule::Empty); + } + + #[test] + fn rejects_unparseable_sql() { + block_rule("SELECT FROM WHERE", DriverKind::Postgres, SqlGuardRule::Parse); + } + + #[test] + fn sql_guard_error_serde() { + let err = ConnectionError::sql_guard( + SqlGuardRule::MultiStatement, + "Only one statement per call is allowed; got 2. Send them separately.", + ); + let json = serde_json::to_value(&err).unwrap(); + assert_eq!(json["kind"], "sql_guard"); + assert_eq!(json["rule"], "single_statement"); + } +} \ No newline at end of file From 8945833e4ff88d4876bdd07b965e1e864ad10280 Mon Sep 17 00:00:00 2001 From: ZhuchkaTriplesix Date: Sun, 15 Nov 2026 13:14:34 +0300 Subject: [PATCH 2/2] test(rust): lock MCP hidden-statement vectors in sql_guard --- .../src-tauri/src/connection/sql_guard.rs | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/apps/tauri/src-tauri/src/connection/sql_guard.rs b/apps/tauri/src-tauri/src/connection/sql_guard.rs index 46a7034a..e9c61a6d 100644 --- a/apps/tauri/src-tauri/src/connection/sql_guard.rs +++ b/apps/tauri/src-tauri/src/connection/sql_guard.rs @@ -167,6 +167,34 @@ mod tests { block_rule("SELECT FROM WHERE", DriverKind::Postgres, SqlGuardRule::Parse); } + /// Parity with Flutter MCP security splitter vectors (`mcp_security_test` / + /// `mcp_sql_guard_test`): comment-hidden `;`, dollar quotes, backslash smuggle. + #[test] + fn rejects_hidden_second_statements() { + block_rule( + "SELECT 1 /* ; */; DROP TABLE t", + DriverKind::Postgres, + SqlGuardRule::MultiStatement, + ); + block_rule( + "SELECT $$ ; $$; DROP TABLE t", + DriverKind::Postgres, + SqlGuardRule::MultiStatement, + ); + // Postgres/SQLite: `\'` does not escape inside `'...'`, so this is two + // statements (string ends at the second `'`, then DELETE…). + block_rule( + "SELECT 'a\\'; DELETE FROM users; --'", + DriverKind::Postgres, + SqlGuardRule::MultiStatement, + ); + block_rule( + "SELECT 'a\\'; DELETE FROM users; --'", + DriverKind::Sqlite, + SqlGuardRule::MultiStatement, + ); + } + #[test] fn sql_guard_error_serde() { let err = ConnectionError::sql_guard(