2121//! transaction statement count, and transaction deadline, plus SQL-safety
2222//! rejection and read-only enforcement.
2323
24+ use std:: ffi:: { CStr , CString } ;
2425use std:: fs;
2526use std:: path:: { Component , Path , PathBuf } ;
2627use std:: sync:: atomic:: { AtomicBool , AtomicUsize , Ordering } ;
@@ -547,6 +548,9 @@ fn current_policy(vm: &Vm) -> &SqlitePolicy {
547548}
548549
549550fn sqlite_error ( error : rusqlite:: Error ) -> VmError {
551+ if matches ! ( error, rusqlite:: Error :: MultipleStatement ) {
552+ return VmError :: HostError ( "multiple SQLite statements are not allowed" . to_string ( ) ) ;
553+ }
550554 let code = error
551555 . sqlite_error ( )
552556 . map ( |value| value. extended_code . to_string ( ) )
@@ -860,6 +864,15 @@ fn install_authorizer(connection: &Connection, allow_unsafe_sql: bool) {
860864 return Authorization :: Allow ;
861865 }
862866 match context. action {
867+ // Regular triggers and their ordinary DML/RAISE guards use the
868+ // same permissions as top-level writes. All accesses in a trigger
869+ // body still pass through this authorizer when SQLite compiles it.
870+ AuthAction :: CreateTrigger { .. }
871+ | AuthAction :: Insert { .. }
872+ | AuthAction :: Update { .. }
873+ | AuthAction :: Delete { .. }
874+ | AuthAction :: Read { .. }
875+ | AuthAction :: Select => Authorization :: Allow ,
863876 AuthAction :: Attach { .. }
864877 | AuthAction :: Detach { .. }
865878 | AuthAction :: Pragma { .. }
@@ -871,7 +884,32 @@ fn install_authorizer(connection: &Connection, allow_unsafe_sql: bool) {
871884 {
872885 Authorization :: Deny
873886 }
874- _ => Authorization :: Allow ,
887+ // Preserve the other known actions already allowed by this
888+ // adapter, including existing schema/drop/temp permissions. Future
889+ // rusqlite action variants must not acquire permission implicitly.
890+ AuthAction :: CreateIndex { .. }
891+ | AuthAction :: CreateTable { .. }
892+ | AuthAction :: CreateTempIndex { .. }
893+ | AuthAction :: CreateTempTable { .. }
894+ | AuthAction :: CreateTempTrigger { .. }
895+ | AuthAction :: CreateTempView { .. }
896+ | AuthAction :: CreateView { .. }
897+ | AuthAction :: DropIndex { .. }
898+ | AuthAction :: DropTable { .. }
899+ | AuthAction :: DropTempIndex { .. }
900+ | AuthAction :: DropTempTable { .. }
901+ | AuthAction :: DropTempTrigger { .. }
902+ | AuthAction :: DropTempView { .. }
903+ | AuthAction :: DropTrigger { .. }
904+ | AuthAction :: DropView { .. }
905+ | AuthAction :: Transaction { .. }
906+ | AuthAction :: AlterTable { .. }
907+ | AuthAction :: Reindex { .. }
908+ | AuthAction :: Analyze { .. }
909+ | AuthAction :: Function { .. }
910+ | AuthAction :: Savepoint { .. }
911+ | AuthAction :: Recursive => Authorization :: Allow ,
912+ _ => Authorization :: Deny ,
875913 }
876914 } ) ) ;
877915}
@@ -899,12 +937,14 @@ fn open_connection(options: &OpenOptions) -> VmResult<Connection> {
899937 Ok ( connection)
900938}
901939
940+ // Lexical policy checks only: statement boundaries are decided by SQLite in
941+ // check_single_statement, never by counting semicolons or BEGIN/END tokens.
902942fn normalized_sql ( sql : & str ) -> VmResult < String > {
903943 let bytes = sql. as_bytes ( ) ;
904944 let mut out = String :: with_capacity ( sql. len ( ) ) ;
905945 let mut index = 0 ;
906946 let mut quote = None ;
907- let mut statement_ended = false ;
947+
908948 while index < bytes. len ( ) {
909949 let byte = bytes[ index] ;
910950 if let Some ( active_quote) = quote {
@@ -918,8 +958,8 @@ fn normalized_sql(sql: &str) -> VmResult<String> {
918958 index += 1 ;
919959 continue ;
920960 }
921- if matches ! ( byte, b'\'' | b'"' | b'`' ) {
922- quote = Some ( byte) ;
961+ if matches ! ( byte, b'\'' | b'"' | b'`' | b'[' ) {
962+ quote = Some ( if byte == b'[' { b']' } else { byte } ) ;
923963 out. push ( ' ' ) ;
924964 index += 1 ;
925965 continue ;
@@ -947,15 +987,10 @@ fn normalized_sql(sql: &str) -> VmResult<String> {
947987 continue ;
948988 }
949989 if byte == b';' {
950- statement_ended = true ;
990+ out . push ( ' ' ) ;
951991 index += 1 ;
952992 continue ;
953993 }
954- if statement_ended && !byte. is_ascii_whitespace ( ) {
955- return Err ( VmError :: HostError (
956- "multiple SQLite statements are not allowed" . to_string ( ) ,
957- ) ) ;
958- }
959994 out. push ( ( byte as char ) . to_ascii_lowercase ( ) ) ;
960995 index += 1 ;
961996 }
@@ -1261,12 +1296,89 @@ fn value_from_row(
12611296 }
12621297}
12631298
1299+ /// Probe exactly one statement on the executing connection, under its current
1300+ /// authorizer, limits and progress handler. Never step the probe. In particular,
1301+ /// a trigger's body semicolons belong to SQLite's grammar, not a host SQL lexer.
1302+ fn check_single_statement ( connection : & Connection , sql : & str ) -> Result < ( ) , rusqlite:: Error > {
1303+ let text = CString :: new ( sql) . map_err ( |_| rusqlite:: Error :: InvalidQuery ) ?;
1304+ let length = i32:: try_from ( sql. len ( ) ) . map_err ( |_| rusqlite:: Error :: InvalidQuery ) ?;
1305+ let mut statement = std:: ptr:: null_mut ( ) ;
1306+ let mut tail = std:: ptr:: null ( ) ;
1307+ // SAFETY: the worker exclusively owns this live connection while holding
1308+ // its connection lock. `text` is NUL-terminated, contains `length` SQL bytes,
1309+ // and outlives prepare. SQLite writes only our two output pointers. No
1310+ // statement escapes this block: finalize (also valid for NULL) runs on both
1311+ // success and error, before any Rust error return or tail validation. No
1312+ // callback can access the connection; the installed hooks only inspect
1313+ // authorization context / atomic cancellation state.
1314+ let ( has_statement, consumed) = unsafe {
1315+ let handle = connection. handle ( ) ;
1316+ let rc = rusqlite:: ffi:: sqlite3_prepare_v2 (
1317+ handle,
1318+ text. as_ptr ( ) ,
1319+ length,
1320+ & mut statement,
1321+ & mut tail,
1322+ ) ;
1323+ let has_statement = !statement. is_null ( ) ;
1324+ rusqlite:: ffi:: sqlite3_finalize ( statement) ;
1325+ if rc != rusqlite:: ffi:: SQLITE_OK {
1326+ // SQLite owns a non-null, NUL-terminated error string for the
1327+ // lifetime of this live handle; copy it before the next API call.
1328+ let message = CStr :: from_ptr ( rusqlite:: ffi:: sqlite3_errmsg ( handle) )
1329+ . to_string_lossy ( )
1330+ . into_owned ( ) ;
1331+ return Err ( rusqlite:: Error :: SqliteFailure (
1332+ rusqlite:: ffi:: Error :: new ( rc) ,
1333+ Some ( message) ,
1334+ ) ) ;
1335+ }
1336+ (
1337+ has_statement,
1338+ ( tail as usize ) . checked_sub ( text. as_ptr ( ) as usize ) ,
1339+ )
1340+ } ;
1341+ let consumed = consumed
1342+ . filter ( |offset| * offset <= sql. len ( ) )
1343+ . ok_or ( rusqlite:: Error :: InvalidQuery ) ?;
1344+ if !has_statement {
1345+ return Err ( rusqlite:: Error :: InvalidQuery ) ;
1346+ }
1347+ // Only whitespace and complete comments may follow the parsed statement.
1348+ // This linear tail scan is deliberately not a second SQL grammar/parser.
1349+ let bytes = sql. as_bytes ( ) ;
1350+ let mut index = consumed;
1351+ while index < bytes. len ( ) {
1352+ if bytes[ index] . is_ascii_whitespace ( ) {
1353+ index += 1 ;
1354+ } else if bytes[ index..] . starts_with ( b"--" ) {
1355+ index += 2 ;
1356+ while index < bytes. len ( ) && bytes[ index] != b'\n' {
1357+ index += 1 ;
1358+ }
1359+ } else if bytes[ index..] . starts_with ( b"/*" ) {
1360+ index += 2 ;
1361+ while index + 1 < bytes. len ( ) && !bytes[ index..] . starts_with ( b"*/" ) {
1362+ index += 1 ;
1363+ }
1364+ if index + 1 >= bytes. len ( ) {
1365+ return Err ( rusqlite:: Error :: InvalidQuery ) ;
1366+ }
1367+ index += 2 ;
1368+ } else {
1369+ return Err ( rusqlite:: Error :: MultipleStatement ) ;
1370+ }
1371+ }
1372+ Ok ( ( ) )
1373+ }
1374+
12641375fn query_with_connection (
12651376 connection : & Connection ,
12661377 sql : & str ,
12671378 params : & [ SqlValue ] ,
12681379 limits : SqliteLimits ,
12691380) -> Result < VmMap , rusqlite:: Error > {
1381+ check_single_statement ( connection, sql) ?;
12701382 let mut statement = connection. prepare ( sql) ?;
12711383 let columns = statement
12721384 . column_names ( )
@@ -1331,6 +1443,7 @@ fn execute_with_connection(
13311443 sql : & str ,
13321444 params : & [ SqlValue ] ,
13331445) -> Result < VmMap , rusqlite:: Error > {
1446+ check_single_statement ( connection, sql) ?;
13341447 let mut statement = connection. prepare ( sql) ?;
13351448 let rows_affected = statement. execute ( params_from_iter ( params. iter ( ) ) ) ?;
13361449 drop ( statement) ;
0 commit comments