From 47a8b6a77d06b74dd5cefce0c5cf3464ce6c9822 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 06:13:42 +0000 Subject: [PATCH 1/6] ADFA-7298 SQLite debugger: the execute tool, one write in autocommit Phase 2, P2-3 (ADFA-7131 comments 41476, 41477). Independent of P2-1. - execute runs one statement that writes on a second, writable server connection per database, cached apart from the read-only one. No readOnlyHint; destructiveHint true. Binds args as query does and returns changes. - changes is sqlite3_changes64, or 0 when sqlite3_total_changes64 did not move: sqlite3_changes64 keeps the previous write's count across a CREATE TABLE or a PRAGMA (41489). - A writable connection now has an authorizer too. Both refuse BEGIN, COMMIT, ROLLBACK, SAVEPOINT, RELEASE, ATTACH, and PRAGMA locking_mode, busy_timeout, the heap limits, temp_store_directory, query_only, writable_schema, and setting journal_mode or schema_version. Before, a writable connection had no authorizer. - A statement that does not write is refused (use query). RETURNING rows are read and dropped. - Every write is stopped and rolled back after 1.5 s (SQLITEDBG_SERVER_NON_WAL_MS), in WAL mode too: it holds the write lock, which the app's writes wait for only 2.5 s. - The transaction backstop runs after execute as after query. - README, tool descriptions, the debugger.endpoints permission text and PLUGIN_AUTHORING.md no longer say read-only (D11). Tests: test.sh passes (ASan+UBSan, TSan, JNI 289 checks). DatabaseToolsTest, McpProtocolTest and EventDecoderTest pass (113), compiled with the Kotlin compiler outside Gradle. Revert proofs: no authorizer on a writable connection fails test_server_holds_no_locks (18 PRAGMAs and transaction statements not refused); plain sqlite3_changes64 fails the CREATE TABLE, PRAGMA and DROP counts; the write cap only outside WAL fails the WAL case (the app's insert got SQLITE_BUSY); one connection cache for both fails executeRunsOnAWritableConnectionApartFromTheReadOnlyOne. Not run here: Gradle, spotlessCheck, apiCheck, a device. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ8yszEP4MqbR9PLba (cherry picked from commit a560ca624b098892b079aeb9d587f6b7b4948a1f) --- docs/PLUGIN_AUTHORING.md | 2 +- .../com/itsaky/androidide/plugins/IPlugin.kt | 4 +- subprojects/sqlite-debugger/README.md | 7 +- .../sqlite-debugger/src/main/cpp/sqlitedbg.c | 42 +++--- .../sqlite-debugger/src/main/cpp/sqlitedbg.h | 33 +++-- .../src/main/cpp/sqlitedbg_jni.c | 140 +++++++++++++----- .../sqlitedebugger/engine/DebugEngine.kt | 30 +++- .../sqlitedebugger/engine/NativeBridge.kt | 9 ++ .../engine/NativeDebugEngine.kt | 10 ++ .../sqlitedebugger/mcp/DatabaseTools.kt | 92 +++++++++--- .../sqlitedebugger/mcp/McpProtocol.kt | 4 +- .../src/test/c/sqlitedbg_test.c | 32 +++- .../sqlitedebugger/engine/FakeDebugEngine.kt | 12 ++ .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 81 +++++++++- .../src/test/jni/JniQueryTest.java | 140 +++++++++++++++++- .../sqlitedebugger/engine/NativeBridge.java | 2 + 16 files changed, 535 insertions(+), 105 deletions(-) diff --git a/docs/PLUGIN_AUTHORING.md b/docs/PLUGIN_AUTHORING.md index 2160356e70..7d46535c31 100644 --- a/docs/PLUGIN_AUTHORING.md +++ b/docs/PLUGIN_AUTHORING.md @@ -343,7 +343,7 @@ Defined by `PluginPermission` in `plugin-api/src/main/kotlin/com/itsaky/androidi | `project.structure` | Modify project structure | | `native.code` | Execute native machine code | | `ide.environment.write` | Write to IDE-managed directories (Android SDK, NDK, cache) | -| `debugger.endpoints` | Read the port and token of the open project's SQLite debugger servers, and so query the apps' databases (read-only for now) | +| `debugger.endpoints` | Read the port and token of the open project's SQLite debugger servers, and so query and write the apps' databases | Plugins run in Code on the Go's process. A permission declares what a plugin means to do, and the services check it on every call, but it cannot stop a plugin that reaches into the host by diff --git a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt index 246836d1c8..968196de75 100644 --- a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt +++ b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt @@ -56,8 +56,8 @@ enum class PluginPermission( IDE_ENVIRONMENT_WRITE("ide.environment.write", "Write to IDE-managed directories such as the Android SDK, NDK, and cache"), DEBUGGER_ENDPOINTS( "debugger.endpoints", - "Read the port and token of the open project's SQLite debugger servers. The token lets the plugin query the " + - "databases of the project's apps: read-only for now, and later versions may allow writes. Plugins run in " + + "Read the port and token of the open project's SQLite debugger servers. The token lets the plugin query and " + + "change the databases of the project's apps. Plugins run in " + "Code on the Go's process, so this declares intent and cannot stop reflection", ), } diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 236123db27..f61ea443ba 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -1,6 +1,6 @@ # SQLite debugger for apps -A debug-only SQLite debugger and MCP server that runs inside apps built with Code on the Go (ADFA-7131). It lets an AI agent list an app's databases, read their schema and rows, see the SQL the app runs, and check integrity, all read-only. Phase 1 is the native extension (ADFA-7135) and the server (ADFA-7136). Nothing in CoGo itself depends on it: apps do, in debug builds. +A debug-only SQLite debugger and MCP server that runs inside apps built with Code on the Go (ADFA-7131). It lets an AI agent list an app's databases, read their schema and rows, see the SQL the app runs, check integrity, and run one statement that writes (`execute`, ADFA-7298). Phase 1 is the native extension (ADFA-7135) and the server (ADFA-7136). Nothing in CoGo itself depends on it: apps do, in debug builds. The module builds an AAR with `libsqlitedbg.so` for arm64-v8a and armeabi-v7a in one artifact, so it has no v7/v8 flavors (`AndroidModuleConf`). Its minSdk is 21, requery's, because the debugger runs on requery's SQLite. The unit test task is `:subprojects:sqlite-debugger:testDebugUnitTest`. @@ -34,7 +34,8 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Debug builds only.** `DebuggerStartup.onCreate` throws if the process is not debuggable, so a release build that includes the library by mistake crashes at once instead of opening a local server. - **Loopback HTTP, a random port and token per start.** `McpHttp` binds 127.0.0.1 only (port 0, so the system picks one) and requires `Authorization: Bearer `, a new 32-byte random token each process start. It also checks that the Host and any Origin name 127.0.0.1 or localhost, against DNS rebinding. At most 8 connections at once. The head of a request (request line and headers) must arrive within 5 s, from connecting for a connection's first request and from its first byte for later ones, and Host, Origin, path and token are checked before the body is read, so a client that trickles bytes or never authenticates frees its slot; a refused request closes the connection. It opens no event stream: GET gets 405. -- **Read-only is a guard against accidents, not a security boundary.** Every tool opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock across statements, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too; the JNI query path also rolls back any transaction left open (`sqlitedbg_end_transaction`, whose ROLLBACK is the one transaction statement the authorizer lets past), and a rollback that fails is the query's error. A server connection waits up to 3 s (`SQLITEDBG_SERVER_BUSY_MS`, fixed in C) for a lock the app holds, as in rollback-journal mode, and then reports `SQLITE_BUSY`. A statement that is running holds a lock, though: on a database that is not in WAL mode (rollback journal) a read holds a SHARED lock, and the app's own COMMIT waits for it only as long as requery's busy timeout, 2500 ms (`BUSY_TIMEOUT_MS` in requery/sqlite-android 3.49.0, `android_database_SQLiteConnection.cpp`). So the JNI query path, which every tool uses, reads `PRAGMA journal_mode` (without a value, so it only reads) on each call and stops a statement on a database that is not in WAL mode after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), with an error that says the database is not in WAL mode and to narrow the query or add a LIMIT. That also stops a `quick_check`, an `integrity_check` or a `get_stats` row count that runs longer than 1.5 s on such a database. A database in WAL mode keeps the 50 s limit, as readers do not block its writer. Anyone holding the token can still run SQL, so the token is the boundary. +- **Read-only is a guard against accidents, not a security boundary.** Every tool but `execute` opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock across statements, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too; the JNI query path also rolls back any transaction left open (`sqlitedbg_end_transaction`, whose ROLLBACK is the one transaction statement the authorizer lets past), and a rollback that fails is the query's error. A server connection waits up to 3 s (`SQLITEDBG_SERVER_BUSY_MS`, fixed in C) for a lock the app holds, as in rollback-journal mode, and then reports `SQLITE_BUSY`. A statement that is running holds a lock, though: on a database that is not in WAL mode (rollback journal) a read holds a SHARED lock, and the app's own COMMIT waits for it only as long as requery's busy timeout, 2500 ms (`BUSY_TIMEOUT_MS` in requery/sqlite-android 3.49.0, `android_database_SQLiteConnection.cpp`). So the JNI query path, which every tool uses, reads `PRAGMA journal_mode` (without a value, so it only reads) on each call and stops a statement on a database that is not in WAL mode after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), with an error that says the database is not in WAL mode and to narrow the query or add a LIMIT. That also stops a `quick_check`, an `integrity_check` or a `get_stats` row count that runs longer than 1.5 s on such a database. A database in WAL mode keeps the 50 s limit, as readers do not block its writer. Anyone holding the token can run `execute`, so the token is the boundary, and the client decides which tools to allow (AI-Agent-MCP asks before each `execute`, ADFA-7300). +- **`execute` writes one statement, in autocommit (ADFA-7298).** Read-write is always available; there is no mode switch. `execute` runs on a second server connection per database, opened with `writable = true` (`SQLITE_OPEN_READWRITE`, never `SQLITE_OPEN_CREATE`) and cached apart from the read-only one, so a read never runs where writes are allowed. Its authorizer allows writes and schema changes and refuses what reaches the app rather than the data: transactions, savepoints, `ATTACH` (it would open a file the app may not have open), and `PRAGMA locking_mode`, `busy_timeout`, the heap limits, `temp_store_directory`, `query_only`, `writable_schema`, and setting `journal_mode` or `schema_version`; the read-only connection refuses them too. So a write cannot be part of a transaction: one statement per call, committed at once. A statement that does not write (`sqlite3_stmt_readonly`) is refused, to be run with `query`; rows from `RETURNING` are read and dropped. It binds `args` as `query` does and returns `changes`: `sqlite3_changes64`, or 0 when `sqlite3_total_changes64` did not move, since `sqlite3_changes64` keeps the previous write's count across a statement that changes no row, such as `CREATE TABLE` (ADFA-7131 comment 41489). A write holds the database's write lock until it ends, in WAL mode too, and the app's own writes wait for it only as long as requery's 2500 ms busy timeout, so every `execute` is stopped after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), whatever the journal mode, and rolled back. Without that cap, a long write in WAL mode made the app's own insert fail with `SQLITE_BUSY` in the JNI test. The transaction backstop runs after `execute` as after `query`. The app is not told about the change: Room's observers and other caches keep what they read until they read again (the Room warning is ADFA-7299). - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. Both checks fail with "unknown function" when a CHECK constraint or a NOT NULL virtual generated column calls such a function; a full `integrity_check` (`full: true`) also fails on an index on such an expression and on a partial index whose WHERE calls one, while `quick_check` (the default) does not fail on those two, and the description of `integrity_check` says to use it then. Views, triggers and other generated columns make neither fail (checked with SQLite 3.46). @@ -49,7 +50,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Host C tests of the extension:** `subprojects/sqlite-debugger/test.sh [--update-fixture] [AMALGAMATION_TARBALL]`. It builds SQLite 3.49.1 from the amalgamation as requery builds it (`SQLITE_THREADSAFE=2`), checks its headers against `sqlite-js/upstream/libs`, and runs `src/test/c/sqlitedbg_test.c` under AddressSanitizer with UBSan, then under ThreadSanitizer. It needs gcc, curl, tar and sha256sum, and downloads the tarball unless you pass one. It runs on Linux only: the script uses GNU `sed -i` without a suffix, `sha256sum` and `readlink -f`, and the JNI build includes `include/linux` and builds `.so` files. CI runs it on `ubuntu-latest`. - **The fixture:** `src/test/resources/.../engine/events.bin` and `events.tsv` are written by the C test and read by `EventDecoderTest`. Without `--update-fixture`, `test.sh` checks the committed pair against the current record layout, so a layout change fails until you regenerate it and update `EventDecoder.kt`. -- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. +- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open; and `execute`: change counts, the refusals, and the 1.5 s cap on a write in DELETE and WAL mode while the app writes. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. - **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol`, `McpHttp`, `DatabaseTools` (with `FakeDebugEngine`) and `EndpointBroadcast`, its announce receiver included. `.github/workflows/test-sqlite-debugger.yml` runs `test.sh` (the C and JNI tests) on pull requests that touch the module or the SQLite headers. The JVM tests run in `.github/workflows/debug.yml`, in the step "Run sqlite-debugger unit tests" beside the `:plugin-api` one. diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index d55c47afac..83ad7fc5c6 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -391,10 +391,11 @@ void sqlitedbg_set_client_connected(int connected) { __atomic_store_n(&g_client_connected, connected ? 1 : 0, __ATOMIC_RELAXED); } -static int server_authorizer(void *unused, int action, const char *a1, const char *a2, const char *db, +// The user data of a writable server connection's authorizer; a read-only one gets NULL. +static const int k_writable = 1; + +static int server_authorizer(void *writable, int action, const char *a1, const char *a2, const char *db, const char *trigger) { - (void)unused; - (void)a2; (void)db; (void)trigger; switch (action) { @@ -422,6 +423,8 @@ static int server_authorizer(void *unused, int action, const char *a1, const cha case SQLITE_ALTER_TABLE: case SQLITE_REINDEX: case SQLITE_ANALYZE: + return writable ? SQLITE_OK : SQLITE_DENY; + // ATTACH would open a file the app may not have open (ADFA-7131, Design 3), writable or not. case SQLITE_ATTACH: case SQLITE_DETACH: // A client could open a transaction or savepoint and hold a lock on the app's database. @@ -431,20 +434,27 @@ static int server_authorizer(void *unused, int action, const char *a1, const cha // Only the ROLLBACK of sqlitedbg_end_transaction, which ends one, gets past. return tls_ending_transaction && a1 && strcmp(a1, "ROLLBACK") == 0 ? SQLITE_OK : SQLITE_DENY; case SQLITE_PRAGMA: - // PRAGMA query_only=0 would lift the guard, and a PRAGMA that stores a value writes. - // PRAGMA table_info(t) also has a second argument, so only these names are checked. - // locking_mode=EXCLUSIVE keeps the lock after a read, and busy_timeout (any form) lets a - // statement wait on the app's lock for as long as the client likes. The heap limits and - // temp_store_directory are process-wide: they would change the app's own connections. + // Refused on every server connection, as they would reach the app's own connections or its + // file format, not just data. PRAGMA table_info(t) also has a second argument, so only + // these names are checked. locking_mode=EXCLUSIVE keeps the lock after a statement, and + // busy_timeout (any form) lets a statement wait on the app's lock for as long as the client + // likes. The heap limits and temp_store_directory are process-wide. query_only is the + // server's own guard. writable_schema and a schema_version write can leave a schema the + // app's SQLite reads as corrupt, and a journal_mode change switches the mode under the + // app's connections. if (a1 && (sqlite3_stricmp(a1, "query_only") == 0 || sqlite3_stricmp(a1, "writable_schema") == 0 || sqlite3_stricmp(a1, "locking_mode") == 0 || sqlite3_stricmp(a1, "busy_timeout") == 0 || sqlite3_stricmp(a1, "hard_heap_limit") == 0 || sqlite3_stricmp(a1, "soft_heap_limit") == 0 || - sqlite3_stricmp(a1, "temp_store_directory") == 0 || sqlite3_stricmp(a1, "wal_checkpoint") == 0 || - sqlite3_stricmp(a1, "incremental_vacuum") == 0 || sqlite3_stricmp(a1, "optimize") == 0)) + sqlite3_stricmp(a1, "temp_store_directory") == 0)) + return SQLITE_DENY; + if (a1 && a2 && (sqlite3_stricmp(a1, "journal_mode") == 0 || sqlite3_stricmp(a1, "schema_version") == 0)) return SQLITE_DENY; - if (a1 && a2 && - (sqlite3_stricmp(a1, "journal_mode") == 0 || sqlite3_stricmp(a1, "user_version") == 0 || - sqlite3_stricmp(a1, "application_id") == 0 || sqlite3_stricmp(a1, "schema_version") == 0)) + if (writable) return SQLITE_OK; + // Read-only: a PRAGMA that writes the file is a write. + if (a1 && (sqlite3_stricmp(a1, "wal_checkpoint") == 0 || sqlite3_stricmp(a1, "incremental_vacuum") == 0 || + sqlite3_stricmp(a1, "optimize") == 0)) + return SQLITE_DENY; + if (a1 && a2 && (sqlite3_stricmp(a1, "user_version") == 0 || sqlite3_stricmp(a1, "application_id") == 0)) return SQLITE_DENY; return SQLITE_OK; default: @@ -477,10 +487,8 @@ int sqlitedbg_open_server(const char *path, int writable, sqlite3 **db) { tls_opening_server = 1; int rc = sqlite3_open_v2(path, db, writable ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY, NULL); tls_opening_server = 0; - if (rc == SQLITE_OK && !writable) { - rc = sqlite3_exec(*db, "PRAGMA query_only=1", NULL, NULL, NULL); - if (rc == SQLITE_OK) rc = sqlite3_set_authorizer(*db, server_authorizer, NULL); - } + if (rc == SQLITE_OK && !writable) rc = sqlite3_exec(*db, "PRAGMA query_only=1", NULL, NULL, NULL); + if (rc == SQLITE_OK) rc = sqlite3_set_authorizer(*db, server_authorizer, writable ? (void *)&k_writable : NULL); // In rollback-journal mode a reader fails at once while the app holds a write lock. Wait a little, // well under the tools' 50 s deadline; the client cannot change it (PRAGMA busy_timeout is refused). if (rc == SQLITE_OK) rc = sqlite3_busy_timeout(*db, SQLITEDBG_SERVER_BUSY_MS); diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index 4b342ce878..3076a3396b 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -150,29 +150,34 @@ void sqlitedbg_set_client_connected(int connected); // (BUSY_TIMEOUT_MS in android_database_SQLiteConnection.cpp, requery/sqlite-android 3.49.0, copied from // AOSP). The cap sits below that, with margin for the busy handler's back-off and the app's own work, so // a long read never makes the app's commit fail with "database is locked" (ADFA-7136 acceptance -// criterion 5). A WAL database needs no cap: readers and the writer do not block each other. +// criterion 5). A WAL database needs no cap for a read: readers and the writer do not block each other. +// A write is capped in every mode: it holds the write lock, which the app's own writes wait for in the +// same busy handler (ADFA-7298). #define SQLITEDBG_SERVER_NON_WAL_MS 1500 -// Opens path for the server with the same SQLite the app uses: SQLITE_OPEN_READONLY unless -// writable, PRAGMA query_only when read-only, and an authorizer that refuses ordinary writes when -// read-only, and also BEGIN, SAVEPOINT, PRAGMA locking_mode and PRAGMA busy_timeout: a client cannot -// hold a lock across statements. Within one statement a lock is held while it runs, so the JNI query -// path stops a statement on a database that is not in WAL mode after SQLITEDBG_SERVER_NON_WAL_MS. The process-wide PRAGMAs hard_heap_limit, soft_heap_limit and -// temp_store_directory are refused too: they would change the app's own connections. Read-only mode guards against accidents; it is not a security boundary (ADFA-7131, -// D11). Never traced and never listed. The caller owns *db and closes it with sqlite3_close_v2. +// Opens path for the server with the same SQLite the app uses, SQLITE_OPEN_READONLY unless writable +// (never SQLITE_OPEN_CREATE), with an authorizer. On every server connection it refuses BEGIN, COMMIT, +// ROLLBACK, SAVEPOINT and RELEASE, ATTACH and DETACH, and the PRAGMAs that would reach the app rather +// than the data: locking_mode and busy_timeout (a client could hold a lock across statements, or wait +// on the app's for as long as it likes), the process-wide hard_heap_limit, soft_heap_limit and +// temp_store_directory, query_only, writable_schema, and setting journal_mode or schema_version. +// Read-only also sets PRAGMA query_only and refuses every write. Within one statement a lock is held +// while it runs, so the JNI layer stops a read on a database that is not in WAL mode, and every +// write, after SQLITEDBG_SERVER_NON_WAL_MS. Read-only mode guards against accidents; it is not a +// security boundary (ADFA-7131, D11), and a writable connection can change any data the app's can. +// Never traced and never listed. The caller owns *db and closes it with sqlite3_close_v2. // A server connection, unlike an app connection, may use a progress handler (for time limits). -// The connection waits up to SQLITEDBG_SERVER_BUSY_MS for a lock the app holds (rollback-journal mode) -// and then reports SQLITE_BUSY. +// The connection waits up to SQLITEDBG_SERVER_BUSY_MS for a lock the app holds and then reports +// SQLITE_BUSY. // Returns SQLITE_MISUSE before any app connection has opened (the extension then has no SQLite // API to call), or what sqlite3_open_v2 returns. A failure after the open (PRAGMA query_only, the // authorizer or the busy timeout) closes the connection, sets *db to NULL and returns that code, as // does a failed open: *db is non-NULL only with SQLITE_OK. int sqlitedbg_open_server(const char *path, int writable, sqlite3 **db); -// Ends a transaction left open on a server connection with ROLLBACK, which the read-only authorizer -// lets past for this call only: a client's BEGIN, COMMIT and ROLLBACK stay refused. The JNI layer -// calls it after every query as a backstop; nothing a client can send opens one on a read-only -// connection. Returns SQLITE_OK when none was open or it was rolled back, else what ROLLBACK +// Ends a transaction left open on a server connection with ROLLBACK, which the authorizer lets past +// for this call only: a client's BEGIN, COMMIT and ROLLBACK stay refused. The JNI layer calls it after +// every query and execute as a backstop; nothing a client can send opens one. Returns SQLITE_OK when none was open or it was rolled back, else what ROLLBACK // returned, and the transaction is still open. int sqlitedbg_end_transaction(sqlite3 *db); diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index 8d19317ff2..59f44fdd9f 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -304,6 +304,51 @@ static int prepare_one(sqlite3 *db, const jchar *sql, jsize len, sqlite3_stmt ** return SQLITE_OK; } +// Prepares sql (one statement, see prepare_one) and binds args to it. Returns 1 with *st set, or 0 +// with an exception pending and *st NULL. +static int prepare_bound(JNIEnv *env, sqlite3 *db, jstring sql, jobjectArray args, sqlite3_stmt **st) { + *st = NULL; + const char *message = NULL; + jsize sql_len = (*env)->GetStringLength(env, sql); + const jchar *sql_chars = (*env)->GetStringChars(env, sql, NULL); + if (!sql_chars) return 0; + int rc = prepare_one(db, sql_chars, sql_len, st, &message); + (*env)->ReleaseStringChars(env, sql, sql_chars); + if (rc != SQLITE_OK) { + throw_engine(env, rc, message ? message : sqlite3_errmsg(db)); + return 0; + } + // A missing argument would be bound as NULL and the statement would run, with a plausible result. + int wanted = sqlite3_bind_parameter_count(*st); + jsize given = (*env)->GetArrayLength(env, args); + if (given != wanted) { + char msg[96]; + snprintf(msg, sizeof msg, "the statement has %d parameter(s) but %d argument(s) were given", wanted, (int)given); + throw_engine(env, SQLITE_RANGE, msg); + } else { + rc = bind_args(env, db, *st, args, &message); + if (rc != SQLITE_OK && !(*env)->ExceptionCheck(env)) throw_engine(env, rc, message ? message : "cannot bind"); + } + if ((*env)->ExceptionCheck(env)) { + sqlite3_finalize(*st); + *st = NULL; + return 0; + } + return 1; +} + +// After the statement: rolls back a transaction left open (a way past the authorizer), which would +// hold a lock on the app's database until the next call. A failure is the call's error unless the +// call already failed: that error is kept. Returns 0 when it threw. +static int end_transaction_backstop(JNIEnv *env, sqlite3 *db) { + int rc = sqlitedbg_end_transaction(db); + if (rc == SQLITE_OK) return 1; + char msg[256]; + snprintf(msg, sizeof msg, "a transaction was left open and rolling it back failed: %s", sqlite3_errmsg(db)); + throw_engine(env, rc, msg); + return 0; +} + // One cell as a Java object, or NULL for SQL NULL (or on failure, with an exception pending). // *cut is set when a TEXT or BLOB was cut at its limit, and *bytes grows by what the cell costs the // result: the TEXT or BLOB bytes kept, 8 for a number. @@ -358,22 +403,13 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring size_t cut_n = 0, cut_cap = 0; deadline dl = {(int64_t)deadline_ms, 0, 0}; int handler_set = 0; - const char *message = NULL; int rc; if (now_ms() >= dl.at_ms) { throw_engine(env, SQLITE_INTERRUPT, "the time limit passed before the query started"); goto done; } - jsize sql_len = (*env)->GetStringLength(env, sql); - const jchar *sql_chars = (*env)->GetStringChars(env, sql, NULL); - if (!sql_chars) goto done; - rc = prepare_one(db, sql_chars, sql_len, &st, &message); - (*env)->ReleaseStringChars(env, sql, sql_chars); - if (rc != SQLITE_OK) { - throw_engine(env, rc, message ? message : sqlite3_errmsg(db)); - goto done; - } + if (!prepare_bound(env, db, sql, args, &st)) goto done; // Every server tool runs its statements here, so this is the one place that bounds a read on a database // that is not in WAL mode: it holds a SHARED lock until the statement ends, and the app's commit gives @@ -392,21 +428,6 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring sqlite3_progress_handler(db, 1000, progress_cb, &dl); handler_set = 1; - // A missing argument would be bound as NULL and the query would run, returning a plausible empty result. - int wanted = sqlite3_bind_parameter_count(st); - jsize given = (*env)->GetArrayLength(env, args); - if (given != wanted) { - char msg[96]; - snprintf(msg, sizeof msg, "the statement has %d parameter(s) but %d argument(s) were given", wanted, (int)given); - throw_engine(env, SQLITE_RANGE, msg); - goto done; - } - rc = bind_args(env, db, st, args, &message); - if (rc != SQLITE_OK) { - if (!(*env)->ExceptionCheck(env)) throw_engine(env, rc, message ? message : "cannot bind"); - goto done; - } - int ncols = sqlite3_column_count(st); jobjectArray names = (*env)->NewObjectArray(env, ncols, g_string, NULL); jobject rows = names ? (*env)->NewObject(env, g_array_list, g_list_init) : NULL; @@ -499,16 +520,66 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring if (handler_set) sqlite3_progress_handler(db, 0, NULL, NULL); sqlite3_finalize(st); free(cut_cells); - // Backstop: a transaction left open (a writable connection, or a way past the authorizer) - // would hold a lock on the app's database until the next query. A failure is the call's error, - // unless the query already failed: that error is kept. - rc = sqlitedbg_end_transaction(db); - if (rc != SQLITE_OK) { - char msg[256]; - snprintf(msg, sizeof msg, "a transaction was left open and rolling it back failed: %s", sqlite3_errmsg(db)); - throw_engine(env, rc, msg); - result = NULL; + if (!end_transaction_backstop(env, db)) result = NULL; + return result; +} + +// Runs one statement that writes, to its end, on a writable server connection (ADFA-7298). Rows it +// returns (RETURNING) are read and dropped. Returns {changes}: the rows the statement itself inserted, +// updated or deleted (sqlite3_changes64), or 0 when it changed none, such as CREATE TABLE, which leaves +// sqlite3_changes64 at the previous write's count (ADFA-7131 comment 41489). +static jlongArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstring sql, jobjectArray args, jlong deadline_ms) { + (void)cls; + sqlite3 *db = (sqlite3 *)(intptr_t)handle; + sqlite3_stmt *st = NULL; + jlongArray result = NULL; + deadline dl = {(int64_t)deadline_ms, 0, 0}; + int handler_set = 0; + int rc; + + if (now_ms() >= dl.at_ms) { + throw_engine(env, SQLITE_INTERRUPT, "the time limit passed before the statement started"); + goto done; } + if (!prepare_bound(env, db, sql, args, &st)) goto done; + // query is the tool for a read; a statement that changes nothing here would only cost an approval. + if (sqlite3_stmt_readonly(st)) { + throw_engine(env, SQLITE_ERROR, "the statement does not write; run it with query"); + goto done; + } + + // A write holds the database's write lock until it ends, in every journal mode, and the app's own + // writes wait for it only as long as requery's busy timeout: cap it as a non-WAL read is capped. + int64_t cap_at = now_ms() + SQLITEDBG_SERVER_NON_WAL_MS; + if (cap_at < dl.at_ms) { + dl.at_ms = cap_at; + dl.capped = 1; + } + sqlite3_progress_handler(db, 1000, progress_cb, &dl); + handler_set = 1; + + sqlite3_int64 total_before = sqlite3_total_changes64(db); + while ((rc = sqlite3_step(st)) == SQLITE_ROW) {} + if (rc != SQLITE_DONE) { + if (dl.hit && rc == SQLITE_INTERRUPT && dl.capped) { + char msg[256]; + snprintf(msg, sizeof msg, + "the statement was stopped after %.1f s and rolled back: a write holds the database's write lock, so a " + "longer one would make the app's own writes fail. Change fewer rows per call", + SQLITEDBG_SERVER_NON_WAL_MS / 1000.0); + throw_engine(env, SQLITE_INTERRUPT, msg); + } else if (dl.hit && rc == SQLITE_INTERRUPT) throw_engine(env, SQLITE_INTERRUPT, "the statement ran past its time limit"); + else throw_engine(env, rc, sqlite3_errmsg(db)); + goto done; + } + jlong changes = sqlite3_total_changes64(db) == total_before ? 0 : (jlong)sqlite3_changes64(db); + result = (*env)->NewLongArray(env, 1); + if (result) (*env)->SetLongArrayRegion(env, result, 0, 1, &changes); + +done: + if (handler_set) sqlite3_progress_handler(db, 0, NULL, NULL); + sqlite3_finalize(st); + if (!end_transaction_backstop(env, db)) result = NULL; return result; } @@ -551,6 +622,7 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { {"setClientConnected", "(Z)V", (void *)bridge_set_client_connected}, {"openServer", "([BZ)J", (void *)bridge_open_server}, {"query", "(JLjava/lang/String;[Ljava/lang/Object;JIIIIJ)[Ljava/lang/Object;", (void *)bridge_query}, + {"execute", "(JLjava/lang/String;[Ljava/lang/Object;J)[J", (void *)bridge_execute}, {"close", "(J)V", (void *)bridge_close}, }; jclass bridge = (*env)->FindClass(env, BRIDGE_CLASS); diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index 0225492399..1c70446902 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt @@ -33,9 +33,10 @@ interface DebugEngine { fun setClientConnected(connected: Boolean) /** - * Opens [path] for the server: read-only (with an authorizer refusing writes) unless - * [writable]. Only a path one of [connections] has open may be passed: opening a database that - * Android's own SQLite has open, with requery's, can corrupt it (ADFA-7131, Design 3). + * Opens [path] for the server: read-only (an authorizer refuses writes) unless [writable]. Either + * way the authorizer refuses transactions and the PRAGMAs that would reach the app's own + * connections (sqlitedbg.h). Only a path one of [connections] has open may be passed: opening a + * database that Android's own SQLite has open, with requery's, can corrupt it (ADFA-7131, Design 3). * * @throws DebugEngineException if SQLite cannot open it, or no app connection has opened yet. */ @@ -65,8 +66,31 @@ interface ServerConnection : Closeable { limits: QueryLimits, deadlineMillis: Long, ): QueryResult + + /** + * Runs [sql], one statement that writes, to its end in autocommit, with [args] bound as in [query]; rows it + * returns (RETURNING) are dropped. Needs a connection opened with `writable = true`. The statement is + * stopped and rolled back once [deadlineMillis] has passed, or after SQLITEDBG_SERVER_NON_WAL_MS + * (1.5 s) whichever is first: it holds the write lock, which the app's own writes wait for. + * + * @throws DebugEngineException as [query] does, and for a statement that does not write + * (`sqlite3_stmt_readonly`), a transaction statement, or a refused PRAGMA. + */ + fun execute( + sql: String, + args: List, + deadlineMillis: Long, + ): ExecuteResult } +data class ExecuteResult( + /** + * The rows the statement itself inserted, updated or deleted, as `sqlite3_changes64` (not those of + * triggers or foreign key actions); 0 for a statement that changed no row, such as CREATE TABLE. + */ + val changes: Long, +) + data class AppConnection( /** Unique within the process, never reused. */ val id: Long, diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt index 2aee5d390a..93f5dc5233 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt @@ -49,6 +49,15 @@ internal object NativeBridge { deadlineMillis: Long, ): Array + /** `{changes}` of one statement that writes (see [ServerConnection.execute]). Throws [DebugEngineException]. */ + @JvmStatic + external fun execute( + handle: Long, + sql: String, + args: Array, + deadlineMillis: Long, + ): LongArray + @JvmStatic external fun close(handle: Long) } diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt index de4217fb02..1e2d596069 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt @@ -114,6 +114,16 @@ class NativeDebugEngine : DebugEngine { return QueryResult(columns, rows, truncatedCells = counts[0].toInt(), hasMore = counts[1] != 0L, truncatedCellIndexes = cut) } + override fun execute( + sql: String, + args: List, + deadlineMillis: Long, + ): ExecuteResult { + check(handle != 0L) { "the connection is closed" } + val result = NativeBridge.execute(handle, sql, Array(args.size) { bindable(args[it]) }, deadlineMillis) + return ExecuteResult(changes = result[0]) + } + override fun close() { val h = handle handle = 0 diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index ac343b44af..af974c2669 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -13,8 +13,12 @@ import java.util.Timer import java.util.TimerTask /** - * The debugger's MCP tools, all read-only: they open server connections through [engine] with - * `writable = false`, so SQLite's authorizer refuses a write whatever SQL a client sends. A tool + * The debugger's MCP tools. All but execute are read-only: they open server connections through + * [engine] with `writable = false`, so SQLite's authorizer refuses a write whatever SQL a client + * sends. execute (ADFA-7298) runs one statement that writes on a separate writable connection, in + * autocommit; on both, the authorizer refuses transactions and the PRAGMAs that would reach the + * app's own connections. Read-only was a guard against accidents, not a security boundary + * (ADFA-7131, D11); the client decides which tools to allow. A tool * names a database by the path one of the app's own connections has open; any other path is * refused before the engine is called (opening a file Android's SQLite has open, with the * extension's SQLite, can corrupt it). @@ -90,6 +94,14 @@ class DatabaseTools internal constructor( "longer), so a long read does not block the app's own writes; use a narrower query or a LIMIT. A database in " + "WAL mode has no such limit (the $DEADLINE_SECONDS s limit applies, also best effort)." + /** + * Said by execute. The limit is the same C constant as [NON_WAL_NOTE]'s (sqlitedbg.h), applied to every write + * whatever the journal mode: a write holds the database's write lock, which the app's own writes wait for. + */ + const val WRITE_NOTE = + "A statement is stopped and rolled back after 1.5 s (best effort: it can run up to about 3 s longer), in every " + + "journal mode, so a long write does not make the app's own writes fail; change fewer rows per call." + /** Server connections never load what the app registers on its own connections (see the README). */ private const val APP_FUNCTIONS_NOTE = "Functions the app adds to its own connections, such as sqlite-js's stored JavaScript functions, do not exist " + @@ -145,6 +157,9 @@ class DatabaseTools internal constructor( private val lock = Any() private val serverConnections = HashMap() + + /** execute's connections, apart from the read-only ones, so a read never runs where writes are allowed. */ + private val writableConnections = HashMap() private var clientConnected = false private var lastEventsCallMs = 0L private var cancelIdleCheck: (() -> Unit)? = null @@ -175,8 +190,10 @@ class DatabaseTools internal constructor( /** Closes the server connections and tells the engine no client is watching. Call when the server stops. */ fun onServerStopped() { synchronized(lock) { - serverConnections.values.forEach { runCatching { it.connection.close() } } - serverConnections.clear() + for (cache in listOf(serverConnections, writableConnections)) { + cache.values.forEach { runCatching { it.connection.close() } } + cache.clear() + } cancelPendingIdleCheck() if (clientConnected) { clientConnected = false @@ -254,7 +271,7 @@ class DatabaseTools internal constructor( "A result also stops at about " + "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cell bytes (has_more is then true), though the first row always " + "comes back whole. Use offset to page. " + - "$PAGING_NOTE Writes are refused. $APP_FUNCTIONS_NOTE: read the rows or compute in plain SQL instead. $NON_WAL_NOTE", + "$PAGING_NOTE Writes are refused: use execute. $APP_FUNCTIONS_NOTE: read the rows or compute in plain SQL instead. $NON_WAL_NOTE", databaseSchema( "sql" to prop("string", "The SQL statement."), "args" to JSONObject().put("type", "array").put("description", "Values for ? parameters: null, numbers or strings."), @@ -263,6 +280,26 @@ class DatabaseTools internal constructor( required = listOf("sql"), ), ) { call, args -> query(call, args) }, + tool( + "execute", + "Run a statement that writes", + "Runs one SQL statement that writes, such as INSERT, UPDATE, DELETE, CREATE, DROP, ALTER or a PRAGMA that " + + "stores a value, on the app's database, in autocommit: it is committed at once and cannot be undone. " + + "Returns changes, the rows the statement itself inserted, updated or deleted (not those of triggers or " + + "foreign key actions), and 0 for one that changes no row, such as CREATE TABLE. One statement per call; " + + "BEGIN, COMMIT, ROLLBACK and SAVEPOINT are refused, so several statements cannot be made atomic. " + + "A statement that does not write is refused: use query. Rows from RETURNING are not returned. " + + "Also refused: ATTACH, and PRAGMA locking_mode, busy_timeout, query_only, writable_schema, the heap limits, " + + "temp_store_directory, and setting journal_mode or schema_version, as they would reach the app's own " + + "connections. $WRITE_NOTE The app is not told about the change: a screen showing this data may stay " + + "stale until it reads it again. $APP_FUNCTIONS_NOTE.", + databaseSchema( + "sql" to prop("string", "The SQL statement."), + "args" to JSONObject().put("type", "array").put("description", "Values for ? parameters: null, numbers or strings."), + required = listOf("sql"), + ), + readOnly = false, + ) { call, args -> execute(call, args) }, tool( "explain_query_plan", "Explain a query plan", @@ -323,8 +360,9 @@ class DatabaseTools internal constructor( title: String, description: String, inputSchema: JSONObject = JSONObject().put("type", "object").put("properties", JSONObject()).put("additionalProperties", false), + readOnly: Boolean = true, run: (Call, JSONObject) -> JSONObject, - ) = McpTool(name, title, description, inputSchema, readOnly = true, run = { args, deadline -> + ) = McpTool(name, title, description, inputSchema, readOnly = readOnly, destructive = !readOnly, run = { args, deadline -> val call = Call(deadline) call.locked { expireIdleClientLocked() } run(call, args) @@ -430,6 +468,16 @@ class DatabaseTools internal constructor( return out } + private fun execute( + call: Call, + args: JSONObject, + ): JSONObject { + val sql = stringArg(args, "sql") + val bind = bindArgs(args) + val result = withConnection(call, checkedPath(call, args), writable = true) { it.execute(sql, bind, call.deadline) } + return JSONObject().put("changes", encodeLong(result.changes)) + } + private fun explain( call: Call, args: JSONObject, @@ -651,22 +699,30 @@ class DatabaseTools internal constructor( bind: List, offset: Long, limits: QueryLimits, - ): QueryResult = + ): QueryResult = withConnection(call, path, writable = false) { it.query(sql, bind, offset, limits, call.deadline) } + + /** Runs [block] on the cached server connection to [path], opened if need be, under [lock]. */ + private fun withConnection( + call: Call, + path: String, + writable: Boolean, + block: (ServerConnection) -> T, + ): T = call.locked { try { val live = engine.connections() dropStaleServerConnections(live) val conn = - serverConnections + (if (writable) writableConnections else serverConnections) .getOrPut(path) { // checkedPath looked at an earlier snapshot: the app may have closed, or begun closing, its // last connection to this path since, and the server never opens a database the app doesn't // have open. knownPaths skips closing connections too; this re-check covers the gap since its snapshot. val ids = live.filter { it.path == path && !it.closing }.map { it.id }.toSet() if (ids.isEmpty()) throw unknownDatabase(path, knownPaths(live)) - CachedConnection(engine.openServerConnection(path, writable = false), ids) + CachedConnection(engine.openServerConnection(path, writable), ids) }.connection - conn.query(sql, bind, offset, limits, call.deadline) + block(conn) } catch (e: DebugEngineException) { val error = engineError(e) // The time limit counts the call's waits for the lock, so a quick query can run out of time @@ -690,13 +746,15 @@ class DatabaseTools internal constructor( * has any more, or only new ones, is stale. Call with [lock] held. */ private fun dropStaleServerConnections(live: List) { - val it = serverConnections.entries.iterator() - while (it.hasNext()) { - val (path, cached) = it.next() - val ids = live.filter { c -> c.path == path && !c.closing }.map { c -> c.id } - if (ids.none { id -> id in cached.appConnectionIds }) { - runCatching { cached.connection.close() } - it.remove() + for (cache in listOf(serverConnections, writableConnections)) { + val it = cache.entries.iterator() + while (it.hasNext()) { + val (path, cached) = it.next() + val ids = live.filter { c -> c.path == path && !c.closing }.map { c -> c.id } + if (ids.none { id -> id in cached.appConnectionIds }) { + runCatching { cached.connection.close() } + it.remove() + } } } } diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt index b0d017b73f..b5b0449c98 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/McpProtocol.kt @@ -17,6 +17,8 @@ class McpTool( val inputSchema: JSONObject = JSONObject().put("type", "object").put("properties", JSONObject()).put("additionalProperties", false), /** Only reports; changes nothing. Shown to clients as a hint, not relied on. */ val readOnly: Boolean = true, + /** May delete or overwrite data. Meaningful only when not [readOnly]; a hint like it. */ + val destructive: Boolean = false, val run: (args: JSONObject, deadlineMs: Long?) -> JSONObject, ) { fun describe(): JSONObject = @@ -30,7 +32,7 @@ class McpTool( JSONObject() .put("title", title) .put("readOnlyHint", readOnly) - .put("destructiveHint", false) + .put("destructiveHint", destructive) .put("openWorldHint", false), ) } diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index 5f3d6c637d..e3e36db88a 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -634,6 +634,18 @@ static void test_server(void) { CHECK_EQ(sqlite3_db_readonly(srv, "main"), 0); CHECK_EQ(step_all(srv, "INSERT INTO t VALUES(1234)"), SQLITE_DONE); CHECK_EQ(list_conns(&l), before); + // ADFA-7298: ordinary writes, schema changes and the PRAGMAs that only store data are allowed + CHECK_EQ(step_all(srv, "UPDATE t SET a=a WHERE a=1234"), SQLITE_DONE); + CHECK_EQ(step_all(srv, "CREATE TABLE w(a)"), SQLITE_DONE); + CHECK_EQ(step_all(srv, "CREATE INDEX wi ON w(a)"), SQLITE_DONE); + CHECK_EQ(step_all(srv, "DROP TABLE w"), SQLITE_DONE); + CHECK_EQ(step_all(srv, "PRAGMA user_version"), SQLITE_DONE); + CHECK_EQ(step_all(srv, "PRAGMA table_info(t)"), SQLITE_DONE); + CHECK_EQ(sqlite3_get_autocommit(srv), 1); + // not traced, as a read-only one + read_all(cur, &b); + CHECK_EQ(b.count, 0); + batch_free(&b); CHECK_EQ(sqlite3_close_v2(srv), SQLITE_OK); CHECK_EQ(sqlite3_prepare_v2(g_main, "SELECT count(*) FROM t WHERE a=1234", -1, &st, NULL), SQLITE_OK); CHECK_EQ(sqlite3_step(st), SQLITE_ROW); @@ -674,18 +686,28 @@ static void test_server_holds_no_locks(void) { "PRAGMA soft_heap_limit=1000000000", "PRAGMA soft_heap_limit", "PRAGMA temp_store_directory='/tmp'", + // ADFA-7298: also refused on a writable connection, as they reach the app or its file format + "RELEASE s", + "ATTACH ':memory:' AS m", + "PRAGMA query_only=1", + "PRAGMA writable_schema=1", + "PRAGMA journal_mode=DELETE", + "PRAGMA schema_version=1", }; - for (size_t i = 0; i < sizeof denied / sizeof denied[0]; i++) { + // the same on a read-only and on a writable connection (ADFA-7298) + for (size_t i = 0; i < 2 * (sizeof denied / sizeof denied[0]); i++) { + int writable = i % 2; + const char *sql = denied[i / 2]; sqlite3 *srv = NULL; - CHECK_EQ(sqlitedbg_open_server(g_db_path, 0, &srv), SQLITE_OK); - int rc = step_all(srv, denied[i]); - if (rc != SQLITE_AUTH) fprintf(stderr, "not refused: %s (%d)\n", denied[i], rc); + CHECK_EQ(sqlitedbg_open_server(g_db_path, writable, &srv), SQLITE_OK); + int rc = step_all(srv, sql); + if (rc != SQLITE_AUTH) fprintf(stderr, "not refused (writable %d): %s (%d)\n", writable, sql, rc); CHECK_EQ(rc, SQLITE_AUTH); // a read on the same connection, then the app must still be able to write CHECK_EQ(step_all(srv, "SELECT count(*) FROM t"), SQLITE_DONE); char *err = NULL; rc = sqlite3_exec(g_main, "INSERT INTO t VALUES(4242)", NULL, NULL, &err); - if (rc != SQLITE_OK) fprintf(stderr, "app write after \"%s\": %s\n", denied[i], err ? err : "?"); + if (rc != SQLITE_OK) fprintf(stderr, "app write after \"%s\": %s\n", sql, err ? err : "?"); sqlite3_free(err); CHECK_EQ(rc, SQLITE_OK); exec_ok(g_main, "DELETE FROM t WHERE a=4242"); diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt index f889ba3684..926451fb34 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt @@ -9,6 +9,8 @@ class FakeDebugEngine( var answer: (path: String, writable: Boolean, sql: String, args: List) -> QueryResult = { _, _, _, _ -> QueryResult(emptyList(), emptyList(), 0, false) }, + /** Answers [ServerConnection.execute] on a writable connection; a read-only one refuses, as the authorizer does. */ + var executeAnswer: (path: String, sql: String, args: List) -> ExecuteResult = { _, _, _ -> ExecuteResult(0) }, ) : DebugEngine { val appConnections = mutableListOf() @@ -137,6 +139,16 @@ class FakeDebugEngine( ) } + override fun execute( + sql: String, + args: List, + deadlineMillis: Long, + ): ExecuteResult { + check(!closed) { "closed" } + if (!writable) throw DebugEngineException(DebugEngineException.SQLITE_AUTH, "not authorized") + return executeAnswer(path, sql, args) + } + override fun close() { if (!closed) closedServerConnections++ closed = true diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index c804bb99c1..0a3f6192f3 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -4,6 +4,7 @@ import org.appdevforall.sqlitedebugger.engine.AppConnection import org.appdevforall.sqlitedebugger.engine.DebugEngine import org.appdevforall.sqlitedebugger.engine.DebugEngineException import org.appdevforall.sqlitedebugger.engine.EventKind +import org.appdevforall.sqlitedebugger.engine.ExecuteResult import org.appdevforall.sqlitedebugger.engine.FakeDebugEngine import org.appdevforall.sqlitedebugger.engine.QueryLimits import org.appdevforall.sqlitedebugger.engine.QueryResult @@ -75,7 +76,7 @@ class DatabaseToolsTest { } } - @Test fun everyToolIsReadOnly() { + @Test fun everyToolButExecuteIsReadOnly() { val list = tools.tools() assertEquals( listOf( @@ -83,6 +84,7 @@ class DatabaseToolsTest { "list_connections", "get_schema", "query", + "execute", "explain_query_plan", "get_stats", "integrity_check", @@ -90,7 +92,11 @@ class DatabaseToolsTest { ), list.map { it.name }, ) - list.forEach { assertTrue(it.name, it.describe().getJSONObject("annotations").getBoolean("readOnlyHint")) } + for (tool in list) { + val annotations = tool.describe().getJSONObject("annotations") + assertEquals(tool.name, tool.name != "execute", annotations.getBoolean("readOnlyHint")) + assertEquals(tool.name, tool.name == "execute", annotations.getBoolean("destructiveHint")) + } } @Test fun everyToolThatRunsAStatementSaysAStatementOnANonWalDatabaseStopsAfterOneAndAHalfSeconds() { @@ -222,6 +228,7 @@ class DatabaseToolsTest { "explain_query_plan" to JSONObject().put("sql", "select 1"), "get_stats" to JSONObject(), "integrity_check" to JSONObject(), + "execute" to JSONObject().put("sql", "delete from t"), ) for ((name, extra) in cases) { for (bad in listOf("/data/other.db", "", "/data/a.db-wal")) { @@ -1151,6 +1158,76 @@ class DatabaseToolsTest { assertEquals(0, scheduler.pending.size) } + @Test fun executeRunsOnAWritableConnectionApartFromTheReadOnlyOne() { + engine.appConnections += conn(1, "/data/a.db") + val ran = mutableListOf>>() + engine.executeAnswer = { _, sql, args -> + ran += sql to args + ExecuteResult(changes = 3) + } + val t = tools + ok("query", db().put("sql", "select 1"), t) + val r = ok("execute", db().put("sql", "update t set a = ? where b = ?").put("args", JSONArray().put("x").put(2)), t) + assertEquals(3, r.getInt("changes")) + assertEquals(listOf("update t set a = ? where b = ?" to listOf("x", 2L)), ran) + ok("execute", db().put("sql", "delete from t"), t) + ok("query", db().put("sql", "select 1"), t) + // one of each, each kept: a read never runs on the writable connection + assertEquals(listOf("/data/a.db" to false, "/data/a.db" to true), engine.openedServerConnections) + } + + @Test fun executeReportsChangesPastTwoToTheFiftyThirdAsAString() { + engine.appConnections += conn(1, "/data/a.db") + engine.executeAnswer = { _, _, _ -> ExecuteResult(changes = 1L shl 60) } + assertEquals((1L shl 60).toString(), ok("execute", db().put("sql", "delete from t")).getString("changes")) + } + + @Test fun executeErrorsCarryTheSqliteCode() { + engine.appConnections += conn(1, "/data/a.db") + engine.executeAnswer = { _, _, _ -> throw DebugEngineException(DebugEngineException.SQLITE_AUTH, "not authorized") } + val r = runTool(tools, "execute", db().put("sql", "begin")) + assertTrue(r.getBoolean("isError")) + assertEquals(23, r.getJSONObject("structuredContent").getInt("sqlite_code")) + } + + @Test fun executeChecksItsArgumentsBeforeTheEngine() { + engine.appConnections += conn(1, "/data/a.db") + assertTrue(runTool(tools, "execute", db()).getBoolean("isError")) + assertTrue(runTool(tools, "execute", db().put("sql", "x").put("args", "nope")).getBoolean("isError")) + assertTrue(runTool(tools, "execute", db().put("sql", "x").put("args", JSONArray().put(JSONObject()))).getBoolean("isError")) + assertEquals(0, engine.openAttempts) + } + + @Test fun theWritableConnectionIsDroppedWhenTheAppRecreatesTheDatabaseAndClosedWhenTheServerStops() { + engine.appConnections += conn(1, "/data/a.db") + val t = tools + ok("execute", db().put("sql", "delete from t"), t) + engine.appConnections.clear() + engine.appConnections += conn(2, "/data/a.db") + ok("execute", db().put("sql", "delete from t"), t) + assertEquals(2, engine.openedServerConnections.size) + assertEquals(1, engine.closedServerConnections) + t.onServerStopped() + assertEquals(2, engine.closedServerConnections) + } + + @Test fun executeDescribesWhatItRefusesItsTimeLimitAndThatTheAppIsNotTold() { + val d = tools.tools().first { it.name == "execute" }.description + for (text in listOf( + "committed at once and cannot be undone", + "BEGIN, COMMIT, ROLLBACK and SAVEPOINT are refused", + "does not write is refused: use query", + "RETURNING are not returned", + "stopped and rolled back after 1.5 s", + "in every journal mode", + "may stay stale", + "Functions the app adds to its own connections", + )) { + assertTrue("$text: $d", d.contains(text)) + } + assertTrue(tools.tools().first { it.name == "query" }.description.contains("Writes are refused: use execute.")) + } + @Test fun stoppingTheServerClosesServerConnections() { engine.appConnections += conn(1, "/data/a.db") val t = tools diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 5e47180211..2577a586f0 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -88,6 +88,117 @@ static Set set(Long... v) { return new HashSet<>(Arrays.asList(v)); } + static long exec(long h, String sql, Object... args) throws DebugEngineException { + long[] r = NativeBridge.execute(h, sql, args, FAR); + eq(r.length, 1, "execute returns {changes}"); + return r[0]; + } + + static int execCode(long h, String sql, Object[] args, long deadline) { + try { + NativeBridge.execute(h, sql, args, deadline); + return 0; + } catch (DebugEngineException e) { + return e.sqliteCode; + } + } + + /** "code message" of the refusal, or null when the statement ran. */ + static String execRefusal(long h, String sql) { + try { + NativeBridge.execute(h, sql, new Object[0], FAR); + return null; + } catch (DebugEngineException e) { + return e.sqliteCode + " " + e.getMessage(); + } + } + + /** ADFA-7298: execute on a writable server connection. */ + static void execute(Path dir, String path, long app) throws Exception { + long w = NativeBridge.openServer(path.getBytes(StandardCharsets.UTF_8), true); + long r = NativeBridge.openServer(path.getBytes(StandardCharsets.UTF_8), false); + + // a write reports its own change count, and the app sees it + eq(exec(w, "INSERT INTO t(id, s) VALUES(?, ?), (?, ?)", 6001L, "a", 6002L, "b"), 2L, "insert 2: changes 2"); + eq(exec(w, "UPDATE t SET s = ? WHERE id >= ?", "z", 6001L), 2L, "update 2: changes 2"); + eq(exec(w, "DELETE FROM t WHERE id = :id", 6001L), 1L, "delete 1, named parameter: changes 1"); + eq(exec(w, "DELETE FROM t WHERE id = -1"), 0L, "delete none: changes 0"); + // a statement that changes no row reports 0, not the previous write's count (sqlite3_changes64 keeps it) + eq(exec(w, "UPDATE t SET s = 'y' WHERE id = 6002"), 1L, "update 1"); + eq(exec(w, "CREATE TABLE ex(a)"), 0L, "CREATE TABLE: changes 0, not the update's 1"); + eq(exec(w, "PRAGMA user_version = 7"), 0L, "a PRAGMA that stores a value runs: changes 0"); + eq(q(r, "PRAGMA user_version").rows.get(0)[0], 7L, "and is stored"); + eq(exec(w, "PRAGMA user_version = 0"), 0L, "user_version back"); + eq(exec(w, "DROP TABLE ex"), 0L, "DROP TABLE: changes 0"); + eq(exec(w, "INSERT INTO t(id) VALUES(6003) RETURNING id"), 1L, "RETURNING rows are read and dropped: changes 1"); + eq(q(r, "SELECT count(*) FROM t WHERE id IN (6002, 6003)").rows.get(0)[0], 2L, "the writes are visible to a reader"); + eq(Helper.exec(app, "DELETE FROM t WHERE id IN (6002, 6003)"), 0, "the app's own connection writes after them"); + eq(Helper.autocommit(app), 1, "and the app's connection is in autocommit"); + + // a statement that does not write belongs to query + eq(execRefusal(w, "SELECT 1"), "1 the statement does not write; run it with query", "a SELECT is refused"); + eq(execRefusal(w, "PRAGMA user_version"), "1 the statement does not write; run it with query", "a PRAGMA read is refused"); + // one statement, the same argument rules as query + eq(execRefusal(w, "DELETE FROM t WHERE id = -1; DELETE FROM t"), + "1 the SQL holds more than one statement; run one statement per call", "a second statement"); + eq(q(r, "SELECT count(*) FROM t WHERE id = 1").rows.get(0)[0], 1L, "nothing deleted by the refused second statement"); + eq(execCode(w, "DELETE FROM t WHERE id = ?", new Object[0], FAR), 25, "a missing argument: SQLITE_RANGE"); + eq(execCode(w, "DELETE FROM t WHERE id = ?", new Object[] {1L, 2L}, FAR), 25, "an extra argument: SQLITE_RANGE"); + eq(execCode(w, "INSERT INTO nope VALUES(1)", new Object[0], FAR), 1, "an SQLite error: SQLITE_ERROR"); + eq(execCode(w, "COMMIT", new Object[0], FAR), 23, "COMMIT refused"); + eq(execCode(w, "ROLLBACK", new Object[0], FAR), 23, "ROLLBACK refused"); + eq(execCode(w, "PRAGMA journal_mode = DELETE", new Object[0], FAR), 23, "journal_mode change refused"); + eq(execCode(w, "PRAGMA busy_timeout = 60000", new Object[0], FAR), 23, "busy_timeout refused"); + eq(execCode(w, "DELETE FROM t WHERE id = -1", new Object[0], System.currentTimeMillis() - 1), 9, "a deadline already past"); + // a read-only connection still refuses a write through execute + eq(execCode(r, "INSERT INTO t(id) VALUES(6004)", new Object[0], FAR), 23, "read-only connection: SQLITE_AUTH"); + eq(q(r, "SELECT count(*) FROM t WHERE id = 6004").rows.get(0)[0], 0L, "nothing written through a read-only connection"); + NativeBridge.close(r); + NativeBridge.close(w); + + // a long write is stopped after the 1.5 s cap, in WAL mode too, and rolled back, so the app's write never fails + for (String mode : new String[] {"DELETE", "WAL"}) { + String p = dir.resolve("cap-" + mode + ".db").toString(); + long a = Helper.open(p); + eq(Helper.busyTimeout(a, 2500), 0, mode + ": the app's busy timeout"); + eq(Helper.exec(a, "PRAGMA journal_mode=" + mode), 0, mode + ": mode"); + eq(Helper.exec(a, "CREATE TABLE t(id INTEGER)"), 0, mode + ": create"); + eq(Helper.exec(a, "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM c WHERE x<300) INSERT INTO t SELECT x FROM c"), 0, + mode + ": insert"); + long sw = NativeBridge.openServer(p.getBytes(StandardCharsets.UTF_8), true); + Ran ran = new Ran(); + Thread th = new Thread(() -> { + long t = System.currentTimeMillis(); + try { + // far more work than 1.5 s: a cross join of t four times over, inserted + NativeBridge.execute(sw, "INSERT INTO t SELECT a.id FROM t a, t b, t c, t d WHERE a.id + b.id + c.id + d.id < 0 " + + "UNION ALL SELECT -1", new Object[0], System.currentTimeMillis() + 8000); + } catch (DebugEngineException e) { + ran.code = e.sqliteCode; + ran.message = e.getMessage(); + } + ran.ms = System.currentTimeMillis() - t; + }); + th.start(); + Thread.sleep(300); + long t0 = System.currentTimeMillis(); + eq(Helper.exec(a, "INSERT INTO t(id) VALUES(7001)"), 0, mode + ": the app commits during a long server write"); + long commitMs = System.currentTimeMillis() - t0; + th.join(); + check(commitMs < 2500, mode + ": the commit waited " + commitMs + " ms, under the busy timeout"); + eq(ran.code, 9, mode + ": the long write was interrupted: SQLITE_INTERRUPT"); + check(ran.message != null && ran.message.contains("rolled back") && ran.message.contains("fewer rows"), + mode + ": the message says why and what to do: " + ran.message); + check(ran.ms >= 1400 && ran.ms < 2500, mode + ": the write stopped after " + ran.ms + " ms, near the 1500 ms cap"); + long rr = NativeBridge.openServer(p.getBytes(StandardCharsets.UTF_8), false); + eq(q(rr, "SELECT count(*) FROM t WHERE id = -1").rows.get(0)[0], 0L, mode + ": the stopped write left nothing"); + eq(q(rr, "SELECT count(*) FROM t WHERE id = 7001").rows.get(0)[0], 1L, mode + ": the app's write is there"); + NativeBridge.close(rr); + NativeBridge.close(sw); + Helper.close(a); + } + } + /** Reads t four times over: far longer than the cap, and it holds the lock from its first step. */ static final String LONG_READ = "SELECT count(*) FROM t a, t b, t c, t d WHERE a.id + b.id + c.id + d.id < 0"; @@ -344,15 +455,19 @@ public static void main(String[] a) throws Exception { eq(((String[]) NativeBridge.connections()[1]).length, 1, "server not listed"); NativeBridge.close(srv); - // the backstop: a writable connection that opens a transaction does not keep it + // a writable connection refuses transactions too (ADFA-7298), so the app is never locked out long w = NativeBridge.openServer(bytes, true); - q(w, "BEGIN IMMEDIATE"); - eq(Helper.exec(app, "INSERT INTO t(id) VALUES(4244)"), 0, "the app can write after a writable BEGIN IMMEDIATE"); - Helper.exec(app, "DELETE FROM t WHERE id = 4244"); - q(w, "BEGIN"); + for (String sql : new String[] {"BEGIN", "BEGIN IMMEDIATE", "SAVEPOINT s"}) { + eq(codeOf(w, sql, new Object[0], FAR), 23, "writable: " + sql + " refused: SQLITE_AUTH"); + eq(execCode(w, sql, new Object[0], FAR), 23, "writable execute: " + sql + " refused: SQLITE_AUTH"); + eq(Helper.exec(app, "INSERT INTO t(id) VALUES(4244)"), 0, "the app can write after a writable " + sql); + Helper.exec(app, "DELETE FROM t WHERE id = 4244"); + } q(w, "INSERT INTO t(id) VALUES(4245)"); eq(q(w, "SELECT count(*) FROM t WHERE id = 4245").rows.get(0)[0], 1L, "an autocommit insert on the writable connection stays"); - // a rollback the backstop cannot make is the query's error, not a lock held in silence + // a rollback the backstop cannot make is the query's error, not a lock held in silence. The + // transactions below are opened past the authorizer, removed here, as a hole in it would leave one. + eq(Helper.denyTransactions(w, false), 0, "the server's authorizer removed"); eq(Helper.exec(w, "BEGIN IMMEDIATE"), 0, "a transaction opened outside the query path"); eq(Helper.denyTransactions(w, true), 0, "an authorizer that refuses ROLLBACK"); eq(refusal(w, "SELECT 1"), "23 a transaction was left open and rolling it back failed: not authorized", @@ -383,9 +498,22 @@ public static void main(String[] a) throws Exception { eq(Helper.denyTransactions(w, false), 0, "the authorizer cleared, again"); eq(refusal(w, "SELECT 1"), null, "the next query rolls it back, again"); eq(Helper.autocommit(w), 1, "closed"); + // the backstop runs after execute too, and keeps execute's own error + eq(Helper.exec(w, "BEGIN IMMEDIATE"), 0, "a transaction opened outside the execute path"); + eq(execCode(w, "UPDATE t SET id = id WHERE id = -1; SELECT 1", new Object[0], FAR), 1, "execute's own error is kept"); + eq(Helper.autocommit(w), 1, "rolled back after a failed execute"); + eq(Helper.exec(w, "BEGIN IMMEDIATE"), 0, "a transaction opened outside the execute path, rollback to be refused"); + eq(Helper.denyTransactions(w, true), 0, "an authorizer that refuses ROLLBACK, for execute"); + eq(execRefusal(w, "DELETE FROM t WHERE id = -1"), "23 a transaction was left open and rolling it back failed: not authorized", + "execute reports the failed rollback"); + eq(Helper.denyTransactions(w, false), 0, "the authorizer cleared, for execute"); + eq(execRefusal(w, "DELETE FROM t WHERE id = -1"), null, "the next execute rolls it back"); + eq(Helper.autocommit(w), 1, "closed, after execute"); NativeBridge.close(w); Helper.exec(app, "DELETE FROM t WHERE id = 4245"); + execute(dir, path, app); + nonWalCap(dir, path); try { diff --git a/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java b/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java index bc4ee25852..b78c60d0dc 100644 --- a/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java +++ b/subprojects/sqlite-debugger/src/test/jni/org/appdevforall/sqlitedebugger/engine/NativeBridge.java @@ -22,5 +22,7 @@ public static native Object[] query(long handle, String sql, Object[] args, long int maxBlobBytes, int maxTotalBytes, long deadlineMillis) throws DebugEngineException; + public static native long[] execute(long handle, String sql, Object[] args, long deadlineMillis) throws DebugEngineException; + public static native void close(long handle); } From 953516932f2335c764f6c5398d819e06a934748d Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 23:22:56 -0800 Subject: [PATCH 2/6] ADFA-7298 Apply spotless formatting Formatting only, no functional change: spotlessKotlinCheck failed on one assertTrue chain in DatabaseToolsTest.kt that came in with 47a8b6a77. spotlessKotlinApply changed nothing else. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index 0a3f6192f3..ad95affea3 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -1225,7 +1225,13 @@ class DatabaseToolsTest { )) { assertTrue("$text: $d", d.contains(text)) } - assertTrue(tools.tools().first { it.name == "query" }.description.contains("Writes are refused: use execute.")) + assertTrue( + tools + .tools() + .first { it.name == "query" } + .description + .contains("Writes are refused: use execute."), + ) } @Test fun stoppingTheServerClosesServerConnections() { From b73b9f71cf3a81489b0d37921989716f5c8bb9a6 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 23:25:52 -0800 Subject: [PATCH 3/6] ADFA-7298 SQLite debugger: execute returns last_insert_rowid Phase 2, P2-3 (David, 2026-11-25). execute's result now carries last_insert_rowid next to changes: the rowid of the last row the statement inserted into a rowid table, or null when it inserted none. - The writable connection is cached and sqlite3_last_insert_rowid keeps its value across statements, so bridge_execute sets it to 0 with sqlite3_set_last_insert_rowid before the statement and reports it only when non-zero afterwards. Otherwise an UPDATE would report an earlier INSERT's rowid. - Wire encoding: bridge_execute returns {changes, last_insert_rowid}, 0 for none; NativeDebugEngine maps 0 to null (ExecuteResult.lastInsertRowid: Long?). DatabaseTools adds a number (a string past 2^53, as changes) or JSON null. Tool description and README updated. - Accepted edge, in the README: a row inserted with rowid 0 reads as null. - Triggers: sqlite3.h says that after a trigger ends the value reverts to what it was before, so a statement whose only inserts are in triggers reports null. The JNI test checks it (UPDATE with an inserting trigger). Checked: sqlite3_set_last_insert_rowid is in sqlite3_api_routines (sqlite3ext.h, macro to sqlite3_api->set_last_insert_rowid), which the JNI layer already uses, and the JNI build (no SQLITE_CORE, libsqlite3x.so) compiles and runs it. The host C tests do not call bridge_execute. The test copy NativeBridge.java needed no change: the signature stays long[]. Tests: JniQueryTest (27 new checks, 316 in all): INSERT, next INSERT, UPDATE after them, INSERT OR IGNORE that inserts nothing, WITHOUT ROWID, multi-row INSERT, DELETE, trigger-only insert. DatabaseToolsTest: executeReportsLastInsertRowidAsANumberOrNull. Revert proof: with only the sqlite3_set_last_insert_rowid call removed (git diff non-empty), test.sh JNI fails 5 checks, e.g. "FAIL an UPDATE after INSERTs reports null, not their rowid: 2 vs null"; restored, green. Runs: test.sh outside flox: ASan+UBSan 15914 + 3 checks, TSan 15914, JNI 316, 0 failures. Gradle: sqlite-debugger testDebugUnitTest 119 tests, plugin-api testDebugUnitTest 251, assembleDebug, apiCheck, spotlessCheck all pass. Not run: a device. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 4 +-- .../src/main/cpp/sqlitedbg_jni.c | 20 +++++++++---- .../sqlitedebugger/engine/DebugEngine.kt | 6 ++++ .../sqlitedebugger/engine/NativeBridge.kt | 5 +++- .../engine/NativeDebugEngine.kt | 2 +- .../sqlitedebugger/mcp/DatabaseTools.kt | 8 +++-- .../sqlitedebugger/engine/FakeDebugEngine.kt | 2 +- .../sqlitedebugger/mcp/DatabaseToolsTest.kt | 17 +++++++++-- .../src/test/jni/JniQueryTest.java | 30 ++++++++++++++++++- 9 files changed, 78 insertions(+), 16 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index f61ea443ba..0b9af78712 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -35,7 +35,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Debug builds only.** `DebuggerStartup.onCreate` throws if the process is not debuggable, so a release build that includes the library by mistake crashes at once instead of opening a local server. - **Loopback HTTP, a random port and token per start.** `McpHttp` binds 127.0.0.1 only (port 0, so the system picks one) and requires `Authorization: Bearer `, a new 32-byte random token each process start. It also checks that the Host and any Origin name 127.0.0.1 or localhost, against DNS rebinding. At most 8 connections at once. The head of a request (request line and headers) must arrive within 5 s, from connecting for a connection's first request and from its first byte for later ones, and Host, Origin, path and token are checked before the body is read, so a client that trickles bytes or never authenticates frees its slot; a refused request closes the connection. It opens no event stream: GET gets 405. - **Read-only is a guard against accidents, not a security boundary.** Every tool but `execute` opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock across statements, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too; the JNI query path also rolls back any transaction left open (`sqlitedbg_end_transaction`, whose ROLLBACK is the one transaction statement the authorizer lets past), and a rollback that fails is the query's error. A server connection waits up to 3 s (`SQLITEDBG_SERVER_BUSY_MS`, fixed in C) for a lock the app holds, as in rollback-journal mode, and then reports `SQLITE_BUSY`. A statement that is running holds a lock, though: on a database that is not in WAL mode (rollback journal) a read holds a SHARED lock, and the app's own COMMIT waits for it only as long as requery's busy timeout, 2500 ms (`BUSY_TIMEOUT_MS` in requery/sqlite-android 3.49.0, `android_database_SQLiteConnection.cpp`). So the JNI query path, which every tool uses, reads `PRAGMA journal_mode` (without a value, so it only reads) on each call and stops a statement on a database that is not in WAL mode after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), with an error that says the database is not in WAL mode and to narrow the query or add a LIMIT. That also stops a `quick_check`, an `integrity_check` or a `get_stats` row count that runs longer than 1.5 s on such a database. A database in WAL mode keeps the 50 s limit, as readers do not block its writer. Anyone holding the token can run `execute`, so the token is the boundary, and the client decides which tools to allow (AI-Agent-MCP asks before each `execute`, ADFA-7300). -- **`execute` writes one statement, in autocommit (ADFA-7298).** Read-write is always available; there is no mode switch. `execute` runs on a second server connection per database, opened with `writable = true` (`SQLITE_OPEN_READWRITE`, never `SQLITE_OPEN_CREATE`) and cached apart from the read-only one, so a read never runs where writes are allowed. Its authorizer allows writes and schema changes and refuses what reaches the app rather than the data: transactions, savepoints, `ATTACH` (it would open a file the app may not have open), and `PRAGMA locking_mode`, `busy_timeout`, the heap limits, `temp_store_directory`, `query_only`, `writable_schema`, and setting `journal_mode` or `schema_version`; the read-only connection refuses them too. So a write cannot be part of a transaction: one statement per call, committed at once. A statement that does not write (`sqlite3_stmt_readonly`) is refused, to be run with `query`; rows from `RETURNING` are read and dropped. It binds `args` as `query` does and returns `changes`: `sqlite3_changes64`, or 0 when `sqlite3_total_changes64` did not move, since `sqlite3_changes64` keeps the previous write's count across a statement that changes no row, such as `CREATE TABLE` (ADFA-7131 comment 41489). A write holds the database's write lock until it ends, in WAL mode too, and the app's own writes wait for it only as long as requery's 2500 ms busy timeout, so every `execute` is stopped after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), whatever the journal mode, and rolled back. Without that cap, a long write in WAL mode made the app's own insert fail with `SQLITE_BUSY` in the JNI test. The transaction backstop runs after `execute` as after `query`. The app is not told about the change: Room's observers and other caches keep what they read until they read again (the Room warning is ADFA-7299). +- **`execute` writes one statement, in autocommit (ADFA-7298).** Read-write is always available; there is no mode switch. `execute` runs on a second server connection per database, opened with `writable = true` (`SQLITE_OPEN_READWRITE`, never `SQLITE_OPEN_CREATE`) and cached apart from the read-only one, so a read never runs where writes are allowed. Its authorizer allows writes and schema changes and refuses what reaches the app rather than the data: transactions, savepoints, `ATTACH` (it would open a file the app may not have open), and `PRAGMA locking_mode`, `busy_timeout`, the heap limits, `temp_store_directory`, `query_only`, `writable_schema`, and setting `journal_mode` or `schema_version`; the read-only connection refuses them too. So a write cannot be part of a transaction: one statement per call, committed at once. A statement that does not write (`sqlite3_stmt_readonly`) is refused, to be run with `query`; rows from `RETURNING` are read and dropped. It binds `args` as `query` does and returns `changes`: `sqlite3_changes64`, or 0 when `sqlite3_total_changes64` did not move, since `sqlite3_changes64` keeps the previous write's count across a statement that changes no row, such as `CREATE TABLE` (ADFA-7131 comment 41489). `last_insert_rowid` is the rowid of the last row the statement inserted into a rowid table, or null when it inserted none (an `UPDATE`, a `WITHOUT ROWID` table, an ignored row). The writable connection is cached and SQLite keeps `sqlite3_last_insert_rowid` across statements, so the JNI layer sets it to 0 with `sqlite3_set_last_insert_rowid` before each statement and reports non-zero only; a row inserted with rowid 0 reads as null (accepted). Rows a trigger inserts do not count, as SQLite restores the value when the trigger ends. A write holds the database's write lock until it ends, in WAL mode too, and the app's own writes wait for it only as long as requery's 2500 ms busy timeout, so every `execute` is stopped after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), whatever the journal mode, and rolled back. Without that cap, a long write in WAL mode made the app's own insert fail with `SQLITE_BUSY` in the JNI test. The transaction backstop runs after `execute` as after `query`. The app is not told about the change: Room's observers and other caches keep what they read until they read again (the Room warning is ADFA-7299). - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. Both checks fail with "unknown function" when a CHECK constraint or a NOT NULL virtual generated column calls such a function; a full `integrity_check` (`full: true`) also fails on an index on such an expression and on a partial index whose WHERE calls one, while `quick_check` (the default) does not fail on those two, and the description of `integrity_check` says to use it then. Views, triggers and other generated columns make neither fail (checked with SQLite 3.46). @@ -50,7 +50,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Host C tests of the extension:** `subprojects/sqlite-debugger/test.sh [--update-fixture] [AMALGAMATION_TARBALL]`. It builds SQLite 3.49.1 from the amalgamation as requery builds it (`SQLITE_THREADSAFE=2`), checks its headers against `sqlite-js/upstream/libs`, and runs `src/test/c/sqlitedbg_test.c` under AddressSanitizer with UBSan, then under ThreadSanitizer. It needs gcc, curl, tar and sha256sum, and downloads the tarball unless you pass one. It runs on Linux only: the script uses GNU `sed -i` without a suffix, `sha256sum` and `readlink -f`, and the JNI build includes `include/linux` and builds `.so` files. CI runs it on `ubuntu-latest`. - **The fixture:** `src/test/resources/.../engine/events.bin` and `events.tsv` are written by the C test and read by `EventDecoderTest`. Without `--update-fixture`, `test.sh` checks the committed pair against the current record layout, so a layout change fails until you regenerate it and update `EventDecoder.kt`. -- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open; and `execute`: change counts, the refusals, and the 1.5 s cap on a write in DELETE and WAL mode while the app writes. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. +- **JNI test:** when a JDK is on PATH, `test.sh` also builds `libsqlitedbg.so` as it ships (no `SQLITE_CORE`) against a requery-like `libsqlite3x.so` and runs `src/test/jni/JniQueryTest.java` through `NativeBridge`: paging, the total-bytes budget, per-cell truncation, bound types, one statement per call, the deadline, refused writes and transactions, and the rollback of a transaction left open; and `execute`: change counts, `last_insert_rowid`, the refusals, and the 1.5 s cap on a write in DELETE and WAL mode while the app writes. It uses Java stubs of `NativeBridge` and `DebugEngineException` instead of the Kotlin, so a JDK is all it needs; `test.sh` checks the native names match `NativeBridge.kt`. Otherwise it is skipped with a message. CI runs `test.sh` in `.github/workflows/test-sqlite-debugger.yml` for changes under this module. - **JVM tests:** `flox activate -d flox/local -- ./gradlew :subprojects:sqlite-debugger:testDebugUnitTest`. They cover `EventDecoder`, `McpProtocol`, `McpHttp`, `DatabaseTools` (with `FakeDebugEngine`) and `EndpointBroadcast`, its announce receiver included. `.github/workflows/test-sqlite-debugger.yml` runs `test.sh` (the C and JNI tests) on pull requests that touch the module or the SQLite headers. The JVM tests run in `.github/workflows/debug.yml`, in the step "Run sqlite-debugger unit tests" beside the `:plugin-api` one. diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index 59f44fdd9f..e035a5a580 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -525,9 +525,12 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring } // Runs one statement that writes, to its end, on a writable server connection (ADFA-7298). Rows it -// returns (RETURNING) are read and dropped. Returns {changes}: the rows the statement itself inserted, -// updated or deleted (sqlite3_changes64), or 0 when it changed none, such as CREATE TABLE, which leaves -// sqlite3_changes64 at the previous write's count (ADFA-7131 comment 41489). +// returns (RETURNING) are read and dropped. Returns {changes, last_insert_rowid}: changes is the rows the +// statement itself inserted, updated or deleted (sqlite3_changes64), or 0 when it changed none, such as +// CREATE TABLE, which leaves sqlite3_changes64 at the previous write's count (ADFA-7131 comment 41489). +// last_insert_rowid is the rowid of the last row the statement inserted into a rowid table, and 0 when it +// inserted none (0 stands for null; a row inserted with rowid 0 reads as none, accepted). Inserts made +// by a trigger do not count: SQLite restores the value when the trigger ends. static jlongArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstring sql, jobjectArray args, jlong deadline_ms) { (void)cls; sqlite3 *db = (sqlite3 *)(intptr_t)handle; @@ -559,6 +562,9 @@ static jlongArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstring handler_set = 1; sqlite3_int64 total_before = sqlite3_total_changes64(db); + // the connection is cached and keeps its value across statements: without this an UPDATE would + // report the rowid of an earlier execute's INSERT + sqlite3_set_last_insert_rowid(db, 0); while ((rc = sqlite3_step(st)) == SQLITE_ROW) {} if (rc != SQLITE_DONE) { if (dl.hit && rc == SQLITE_INTERRUPT && dl.capped) { @@ -572,9 +578,11 @@ static jlongArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstring else throw_engine(env, rc, sqlite3_errmsg(db)); goto done; } - jlong changes = sqlite3_total_changes64(db) == total_before ? 0 : (jlong)sqlite3_changes64(db); - result = (*env)->NewLongArray(env, 1); - if (result) (*env)->SetLongArrayRegion(env, result, 0, 1, &changes); + jlong out[2]; + out[0] = sqlite3_total_changes64(db) == total_before ? 0 : (jlong)sqlite3_changes64(db); + out[1] = (jlong)sqlite3_last_insert_rowid(db); + result = (*env)->NewLongArray(env, 2); + if (result) (*env)->SetLongArrayRegion(env, result, 0, 2, out); done: if (handler_set) sqlite3_progress_handler(db, 0, NULL, NULL); diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index 1c70446902..fb9ec82a02 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt @@ -89,6 +89,12 @@ data class ExecuteResult( * triggers or foreign key actions); 0 for a statement that changed no row, such as CREATE TABLE. */ val changes: Long, + /** + * The rowid of the last row the statement inserted into a rowid table, or null when it inserted none + * (an UPDATE, a WITHOUT ROWID table, `INSERT OR IGNORE` that ignored the row). Inserts made by + * triggers do not count. A row inserted with rowid 0 reads as null. + */ + val lastInsertRowid: Long?, ) data class AppConnection( diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt index 93f5dc5233..114a75ddd3 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt @@ -49,7 +49,10 @@ internal object NativeBridge { deadlineMillis: Long, ): Array - /** `{changes}` of one statement that writes (see [ServerConnection.execute]). Throws [DebugEngineException]. */ + /** + * `{changes, last_insert_rowid}` of one statement that writes (see [ServerConnection.execute]); the + * rowid is 0 when the statement inserted no row into a rowid table. Throws [DebugEngineException]. + */ @JvmStatic external fun execute( handle: Long, diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt index 1e2d596069..b473512065 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt @@ -121,7 +121,7 @@ class NativeDebugEngine : DebugEngine { ): ExecuteResult { check(handle != 0L) { "the connection is closed" } val result = NativeBridge.execute(handle, sql, Array(args.size) { bindable(args[it]) }, deadlineMillis) - return ExecuteResult(changes = result[0]) + return ExecuteResult(changes = result[0], lastInsertRowid = result[1].takeIf { it != 0L }) } override fun close() { diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index af974c2669..b5e920dc5c 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -286,7 +286,9 @@ class DatabaseTools internal constructor( "Runs one SQL statement that writes, such as INSERT, UPDATE, DELETE, CREATE, DROP, ALTER or a PRAGMA that " + "stores a value, on the app's database, in autocommit: it is committed at once and cannot be undone. " + "Returns changes, the rows the statement itself inserted, updated or deleted (not those of triggers or " + - "foreign key actions), and 0 for one that changes no row, such as CREATE TABLE. One statement per call; " + + "foreign key actions), and 0 for one that changes no row, such as CREATE TABLE, and last_insert_rowid, " + + "the rowid of the last row it inserted into a rowid table, or null when it inserted none (an UPDATE, " + + "a WITHOUT ROWID table, an ignored row; rows inserted by triggers do not count). One statement per call; " + "BEGIN, COMMIT, ROLLBACK and SAVEPOINT are refused, so several statements cannot be made atomic. " + "A statement that does not write is refused: use query. Rows from RETURNING are not returned. " + "Also refused: ATTACH, and PRAGMA locking_mode, busy_timeout, query_only, writable_schema, the heap limits, " + @@ -475,7 +477,9 @@ class DatabaseTools internal constructor( val sql = stringArg(args, "sql") val bind = bindArgs(args) val result = withConnection(call, checkedPath(call, args), writable = true) { it.execute(sql, bind, call.deadline) } - return JSONObject().put("changes", encodeLong(result.changes)) + return JSONObject() + .put("changes", encodeLong(result.changes)) + .put("last_insert_rowid", result.lastInsertRowid?.let { encodeLong(it) } ?: JSONObject.NULL) } private fun explain( diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt index 926451fb34..0a7117d66f 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/engine/FakeDebugEngine.kt @@ -10,7 +10,7 @@ class FakeDebugEngine( QueryResult(emptyList(), emptyList(), 0, false) }, /** Answers [ServerConnection.execute] on a writable connection; a read-only one refuses, as the authorizer does. */ - var executeAnswer: (path: String, sql: String, args: List) -> ExecuteResult = { _, _, _ -> ExecuteResult(0) }, + var executeAnswer: (path: String, sql: String, args: List) -> ExecuteResult = { _, _, _ -> ExecuteResult(0, null) }, ) : DebugEngine { val appConnections = mutableListOf() diff --git a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt index ad95affea3..3a5dab2422 100644 --- a/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt +++ b/subprojects/sqlite-debugger/src/test/java/org/appdevforall/sqlitedebugger/mcp/DatabaseToolsTest.kt @@ -1163,7 +1163,7 @@ class DatabaseToolsTest { val ran = mutableListOf>>() engine.executeAnswer = { _, sql, args -> ran += sql to args - ExecuteResult(changes = 3) + ExecuteResult(changes = 3, lastInsertRowid = null) } val t = tools ok("query", db().put("sql", "select 1"), t) @@ -1178,10 +1178,23 @@ class DatabaseToolsTest { @Test fun executeReportsChangesPastTwoToTheFiftyThirdAsAString() { engine.appConnections += conn(1, "/data/a.db") - engine.executeAnswer = { _, _, _ -> ExecuteResult(changes = 1L shl 60) } + engine.executeAnswer = { _, _, _ -> ExecuteResult(changes = 1L shl 60, lastInsertRowid = null) } assertEquals((1L shl 60).toString(), ok("execute", db().put("sql", "delete from t")).getString("changes")) } + @Test fun executeReportsLastInsertRowidAsANumberOrNull() { + engine.appConnections += conn(1, "/data/a.db") + engine.executeAnswer = { _, _, _ -> ExecuteResult(changes = 1, lastInsertRowid = 42) } + val inserted = ok("execute", db().put("sql", "insert into t values (1)")) + assertEquals(42, inserted.getInt("last_insert_rowid")) + engine.executeAnswer = { _, _, _ -> ExecuteResult(changes = 1, lastInsertRowid = 1L shl 60) } + assertEquals((1L shl 60).toString(), ok("execute", db().put("sql", "insert into t values (1)")).getString("last_insert_rowid")) + engine.executeAnswer = { _, _, _ -> ExecuteResult(changes = 1, lastInsertRowid = null) } + val updated = ok("execute", db().put("sql", "update t set a = 1")) + assertTrue(updated.has("last_insert_rowid")) + assertTrue(updated.isNull("last_insert_rowid")) + } + @Test fun executeErrorsCarryTheSqliteCode() { engine.appConnections += conn(1, "/data/a.db") engine.executeAnswer = { _, _, _ -> throw DebugEngineException(DebugEngineException.SQLITE_AUTH, "not authorized") } diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 2577a586f0..5f0605689f 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -90,10 +90,16 @@ static Set set(Long... v) { static long exec(long h, String sql, Object... args) throws DebugEngineException { long[] r = NativeBridge.execute(h, sql, args, FAR); - eq(r.length, 1, "execute returns {changes}"); + eq(r.length, 2, "execute returns {changes, last_insert_rowid}"); return r[0]; } + /** The rowid execute reports, or null (0 on the wire) when the statement inserted no row. */ + static Long rowid(long h, String sql, Object... args) throws DebugEngineException { + long r = NativeBridge.execute(h, sql, args, FAR)[1]; + return r == 0 ? null : r; + } + static int execCode(long h, String sql, Object[] args, long deadline) { try { NativeBridge.execute(h, sql, args, deadline); @@ -135,6 +141,28 @@ static void execute(Path dir, String path, long app) throws Exception { eq(Helper.exec(app, "DELETE FROM t WHERE id IN (6002, 6003)"), 0, "the app's own connection writes after them"); eq(Helper.autocommit(app), 1, "and the app's connection is in autocommit"); + // last_insert_rowid: the writable connection is cached, so SQLite's value outlives each statement + eq(exec(w, "CREATE TABLE lr(a UNIQUE)"), 0L, "create lr"); + eq(exec(w, "CREATE TABLE lrw(a PRIMARY KEY) WITHOUT ROWID"), 0L, "create lrw"); + eq(rowid(w, "INSERT INTO lr VALUES(1)"), 1L, "INSERT reports its rowid"); + eq(rowid(w, "INSERT INTO lr VALUES(2)"), 2L, "the next INSERT reports the next rowid"); + eq(rowid(w, "UPDATE lr SET a = a + 10"), null, "an UPDATE after INSERTs reports null, not their rowid"); + eq(rowid(w, "INSERT INTO lr VALUES(3)"), 3L, "an INSERT again"); + eq(rowid(w, "INSERT INTO lrw VALUES(1)"), null, "INSERT into a WITHOUT ROWID table: null, not the previous rowid"); + eq(rowid(w, "INSERT INTO lr VALUES(4)"), 4L, "an INSERT again"); + eq(rowid(w, "INSERT OR IGNORE INTO lr VALUES(4)"), null, "INSERT OR IGNORE that inserts nothing: null"); + eq(rowid(w, "INSERT INTO lr VALUES(5), (6), (7)"), 7L, "a multi-row INSERT reports the last row's rowid"); + eq(rowid(w, "DELETE FROM lr"), null, "a DELETE reports null"); + // SQLite restores the value when a trigger ends, so inserts made only by a trigger report null + eq(exec(w, "CREATE TABLE lt(a)"), 0L, "create lt"); + eq(exec(w, "CREATE TRIGGER lt_up AFTER UPDATE ON lt BEGIN INSERT INTO lr VALUES(100); END"), 0L, "create trigger"); + eq(rowid(w, "INSERT INTO lt VALUES(1)"), 1L, "an INSERT with no trigger on it reports its rowid"); + eq(rowid(w, "UPDATE lt SET a = 2"), null, "an UPDATE whose trigger inserts a row reports null"); + eq(q(r, "SELECT count(*) FROM lr").rows.get(0)[0], 1L, "the trigger did insert"); + eq(exec(w, "DROP TABLE lt"), 0L, "drop lt"); + eq(exec(w, "DROP TABLE lr"), 0L, "drop lr"); + eq(exec(w, "DROP TABLE lrw"), 0L, "drop lrw"); + // a statement that does not write belongs to query eq(execRefusal(w, "SELECT 1"), "1 the statement does not write; run it with query", "a SELECT is refused"); eq(execRefusal(w, "PRAGMA user_version"), "1 the statement does not write; run it with query", "a PRAGMA read is refused"); From 8c2f6ac61ea283713b1e6d2c9243a9c0695e1e76 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 23:54:28 -0800 Subject: [PATCH 4/6] ADFA-7298 Report rowid 0 from execute: use INT64_MIN, not 0, for "no row inserted" b73b9f71c reset sqlite3_last_insert_rowid to 0 before each statement and reported only non-zero values, so a row inserted with rowid 0 read as null. 0 is SQLite's own "none" for sqlite3_last_insert_rowid, but it is also a valid rowid: an explicit `INSERT ... (rowid) VALUES (0, ...)`, or an automatic one when the largest rowid is -1. David chose (2026-11-25) to reset to INT64_MIN instead, the one value SQLite never assigns itself (an empty table starts at 1, then the largest rowid plus 1, then random positive ones when that is the maximum). Now 0 and negative rowids are reported as they are, and only a row inserted explicitly with rowid -9223372036854775808 reads as null (accepted, in the README). The JNI layer resets to INT64_MIN; NativeDebugEngine maps Long.MIN_VALUE to null. KDoc, the C comment and the README say so. Tests: JNI checks that an INSERT with rowid 0 reports 0 and one with rowid -5 reports -5; the null cases are unchanged. Revert proof: with the reset and the decoding back at 0, only "an INSERT with rowid 0 reports 0, not null: null vs 0" fails. test.sh (system JDK): ASan+UBSan 15919 checks, TSan 15909, JNI 319, 0 failures. :subprojects:sqlite-debugger: testDebugUnitTest and spotlessCheck pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlite-debugger/src/main/cpp/sqlitedbg_jni.c | 10 ++++++---- .../appdevforall/sqlitedebugger/engine/DebugEngine.kt | 3 ++- .../appdevforall/sqlitedebugger/engine/NativeBridge.kt | 3 ++- .../sqlitedebugger/engine/NativeDebugEngine.kt | 2 +- .../sqlite-debugger/src/test/jni/JniQueryTest.java | 8 ++++++-- 6 files changed, 18 insertions(+), 10 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 0b9af78712..195faebba6 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -35,7 +35,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Debug builds only.** `DebuggerStartup.onCreate` throws if the process is not debuggable, so a release build that includes the library by mistake crashes at once instead of opening a local server. - **Loopback HTTP, a random port and token per start.** `McpHttp` binds 127.0.0.1 only (port 0, so the system picks one) and requires `Authorization: Bearer `, a new 32-byte random token each process start. It also checks that the Host and any Origin name 127.0.0.1 or localhost, against DNS rebinding. At most 8 connections at once. The head of a request (request line and headers) must arrive within 5 s, from connecting for a connection's first request and from its first byte for later ones, and Host, Origin, path and token are checked before the body is read, so a client that trickles bytes or never authenticates frees its slot; a refused request closes the connection. It opens no event stream: GET gets 405. - **Read-only is a guard against accidents, not a security boundary.** Every tool but `execute` opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock across statements, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too; the JNI query path also rolls back any transaction left open (`sqlitedbg_end_transaction`, whose ROLLBACK is the one transaction statement the authorizer lets past), and a rollback that fails is the query's error. A server connection waits up to 3 s (`SQLITEDBG_SERVER_BUSY_MS`, fixed in C) for a lock the app holds, as in rollback-journal mode, and then reports `SQLITE_BUSY`. A statement that is running holds a lock, though: on a database that is not in WAL mode (rollback journal) a read holds a SHARED lock, and the app's own COMMIT waits for it only as long as requery's busy timeout, 2500 ms (`BUSY_TIMEOUT_MS` in requery/sqlite-android 3.49.0, `android_database_SQLiteConnection.cpp`). So the JNI query path, which every tool uses, reads `PRAGMA journal_mode` (without a value, so it only reads) on each call and stops a statement on a database that is not in WAL mode after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), with an error that says the database is not in WAL mode and to narrow the query or add a LIMIT. That also stops a `quick_check`, an `integrity_check` or a `get_stats` row count that runs longer than 1.5 s on such a database. A database in WAL mode keeps the 50 s limit, as readers do not block its writer. Anyone holding the token can run `execute`, so the token is the boundary, and the client decides which tools to allow (AI-Agent-MCP asks before each `execute`, ADFA-7300). -- **`execute` writes one statement, in autocommit (ADFA-7298).** Read-write is always available; there is no mode switch. `execute` runs on a second server connection per database, opened with `writable = true` (`SQLITE_OPEN_READWRITE`, never `SQLITE_OPEN_CREATE`) and cached apart from the read-only one, so a read never runs where writes are allowed. Its authorizer allows writes and schema changes and refuses what reaches the app rather than the data: transactions, savepoints, `ATTACH` (it would open a file the app may not have open), and `PRAGMA locking_mode`, `busy_timeout`, the heap limits, `temp_store_directory`, `query_only`, `writable_schema`, and setting `journal_mode` or `schema_version`; the read-only connection refuses them too. So a write cannot be part of a transaction: one statement per call, committed at once. A statement that does not write (`sqlite3_stmt_readonly`) is refused, to be run with `query`; rows from `RETURNING` are read and dropped. It binds `args` as `query` does and returns `changes`: `sqlite3_changes64`, or 0 when `sqlite3_total_changes64` did not move, since `sqlite3_changes64` keeps the previous write's count across a statement that changes no row, such as `CREATE TABLE` (ADFA-7131 comment 41489). `last_insert_rowid` is the rowid of the last row the statement inserted into a rowid table, or null when it inserted none (an `UPDATE`, a `WITHOUT ROWID` table, an ignored row). The writable connection is cached and SQLite keeps `sqlite3_last_insert_rowid` across statements, so the JNI layer sets it to 0 with `sqlite3_set_last_insert_rowid` before each statement and reports non-zero only; a row inserted with rowid 0 reads as null (accepted). Rows a trigger inserts do not count, as SQLite restores the value when the trigger ends. A write holds the database's write lock until it ends, in WAL mode too, and the app's own writes wait for it only as long as requery's 2500 ms busy timeout, so every `execute` is stopped after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), whatever the journal mode, and rolled back. Without that cap, a long write in WAL mode made the app's own insert fail with `SQLITE_BUSY` in the JNI test. The transaction backstop runs after `execute` as after `query`. The app is not told about the change: Room's observers and other caches keep what they read until they read again (the Room warning is ADFA-7299). +- **`execute` writes one statement, in autocommit (ADFA-7298).** Read-write is always available; there is no mode switch. `execute` runs on a second server connection per database, opened with `writable = true` (`SQLITE_OPEN_READWRITE`, never `SQLITE_OPEN_CREATE`) and cached apart from the read-only one, so a read never runs where writes are allowed. Its authorizer allows writes and schema changes and refuses what reaches the app rather than the data: transactions, savepoints, `ATTACH` (it would open a file the app may not have open), and `PRAGMA locking_mode`, `busy_timeout`, the heap limits, `temp_store_directory`, `query_only`, `writable_schema`, and setting `journal_mode` or `schema_version`; the read-only connection refuses them too. So a write cannot be part of a transaction: one statement per call, committed at once. A statement that does not write (`sqlite3_stmt_readonly`) is refused, to be run with `query`; rows from `RETURNING` are read and dropped. It binds `args` as `query` does and returns `changes`: `sqlite3_changes64`, or 0 when `sqlite3_total_changes64` did not move, since `sqlite3_changes64` keeps the previous write's count across a statement that changes no row, such as `CREATE TABLE` (ADFA-7131 comment 41489). `last_insert_rowid` is the rowid of the last row the statement inserted into a rowid table, or null when it inserted none (an `UPDATE`, a `WITHOUT ROWID` table, an ignored row). The writable connection is cached and SQLite keeps `sqlite3_last_insert_rowid` across statements, so the JNI layer sets it to -9223372036854775808 (`INT64_MIN`) with `sqlite3_set_last_insert_rowid` before each statement and reports any other value. Not 0, which is SQLite's own "none" but also a valid rowid: SQLite never assigns `INT64_MIN` itself (an empty table starts at 1, then the largest rowid plus 1, then random positive ones), so only a row inserted explicitly with that rowid reads as null (accepted). Rows a trigger inserts do not count, as SQLite restores the value when the trigger ends. A write holds the database's write lock until it ends, in WAL mode too, and the app's own writes wait for it only as long as requery's 2500 ms busy timeout, so every `execute` is stopped after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), whatever the journal mode, and rolled back. Without that cap, a long write in WAL mode made the app's own insert fail with `SQLITE_BUSY` in the JNI test. The transaction backstop runs after `execute` as after `query`. The app is not told about the change: Room's observers and other caches keep what they read until they read again (the Room warning is ADFA-7299). - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. Both checks fail with "unknown function" when a CHECK constraint or a NOT NULL virtual generated column calls such a function; a full `integrity_check` (`full: true`) also fails on an index on such an expression and on a partial index whose WHERE calls one, while `quick_check` (the default) does not fail on those two, and the description of `integrity_check` says to use it then. Views, triggers and other generated columns make neither fail (checked with SQLite 3.46). diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c index e035a5a580..7200d49ef9 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg_jni.c @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -528,8 +529,9 @@ static jobjectArray bridge_query(JNIEnv *env, jclass cls, jlong handle, jstring // returns (RETURNING) are read and dropped. Returns {changes, last_insert_rowid}: changes is the rows the // statement itself inserted, updated or deleted (sqlite3_changes64), or 0 when it changed none, such as // CREATE TABLE, which leaves sqlite3_changes64 at the previous write's count (ADFA-7131 comment 41489). -// last_insert_rowid is the rowid of the last row the statement inserted into a rowid table, and 0 when it -// inserted none (0 stands for null; a row inserted with rowid 0 reads as none, accepted). Inserts made +// last_insert_rowid is the rowid of the last row the statement inserted into a rowid table, and INT64_MIN +// when it inserted none: SQLite never assigns that rowid itself, so only a row inserted explicitly with +// it reads as none (accepted), while 0 and other negative rowids are reported as they are. Inserts made // by a trigger do not count: SQLite restores the value when the trigger ends. static jlongArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstring sql, jobjectArray args, jlong deadline_ms) { (void)cls; @@ -563,8 +565,8 @@ static jlongArray bridge_execute(JNIEnv *env, jclass cls, jlong handle, jstring sqlite3_int64 total_before = sqlite3_total_changes64(db); // the connection is cached and keeps its value across statements: without this an UPDATE would - // report the rowid of an earlier execute's INSERT - sqlite3_set_last_insert_rowid(db, 0); + // report the rowid of an earlier execute's INSERT. Not 0, SQLite's own "none": 0 is a valid rowid. + sqlite3_set_last_insert_rowid(db, INT64_MIN); while ((rc = sqlite3_step(st)) == SQLITE_ROW) {} if (rc != SQLITE_DONE) { if (dl.hit && rc == SQLITE_INTERRUPT && dl.capped) { diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index fb9ec82a02..2533ff3cc7 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt @@ -92,7 +92,8 @@ data class ExecuteResult( /** * The rowid of the last row the statement inserted into a rowid table, or null when it inserted none * (an UPDATE, a WITHOUT ROWID table, `INSERT OR IGNORE` that ignored the row). Inserts made by - * triggers do not count. A row inserted with rowid 0 reads as null. + * triggers do not count. A row inserted explicitly with rowid [Long.MIN_VALUE], which SQLite never + * assigns itself, reads as null; 0 and other negative rowids are reported. */ val lastInsertRowid: Long?, ) diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt index 114a75ddd3..2887e68fd3 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeBridge.kt @@ -51,7 +51,8 @@ internal object NativeBridge { /** * `{changes, last_insert_rowid}` of one statement that writes (see [ServerConnection.execute]); the - * rowid is 0 when the statement inserted no row into a rowid table. Throws [DebugEngineException]. + * rowid is [Long.MIN_VALUE] when the statement inserted no row into a rowid table. Throws + * [DebugEngineException]. */ @JvmStatic external fun execute( diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt index b473512065..b4467b8ca9 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/NativeDebugEngine.kt @@ -121,7 +121,7 @@ class NativeDebugEngine : DebugEngine { ): ExecuteResult { check(handle != 0L) { "the connection is closed" } val result = NativeBridge.execute(handle, sql, Array(args.size) { bindable(args[it]) }, deadlineMillis) - return ExecuteResult(changes = result[0], lastInsertRowid = result[1].takeIf { it != 0L }) + return ExecuteResult(changes = result[0], lastInsertRowid = result[1].takeIf { it != Long.MIN_VALUE }) } override fun close() { diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 5f0605689f..4d783f0028 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -94,10 +94,10 @@ static long exec(long h, String sql, Object... args) throws DebugEngineException return r[0]; } - /** The rowid execute reports, or null (0 on the wire) when the statement inserted no row. */ + /** The rowid execute reports, or null (Long.MIN_VALUE on the wire) when the statement inserted no row. */ static Long rowid(long h, String sql, Object... args) throws DebugEngineException { long r = NativeBridge.execute(h, sql, args, FAR)[1]; - return r == 0 ? null : r; + return r == Long.MIN_VALUE ? null : r; } static int execCode(long h, String sql, Object[] args, long deadline) { @@ -153,6 +153,10 @@ static void execute(Path dir, String path, long app) throws Exception { eq(rowid(w, "INSERT OR IGNORE INTO lr VALUES(4)"), null, "INSERT OR IGNORE that inserts nothing: null"); eq(rowid(w, "INSERT INTO lr VALUES(5), (6), (7)"), 7L, "a multi-row INSERT reports the last row's rowid"); eq(rowid(w, "DELETE FROM lr"), null, "a DELETE reports null"); + // 0 and negative rowids are rowids like any other + eq(rowid(w, "INSERT INTO lr(rowid, a) VALUES(0, 20)"), 0L, "an INSERT with rowid 0 reports 0, not null"); + eq(rowid(w, "INSERT INTO lr(rowid, a) VALUES(-5, 21)"), -5L, "an INSERT with a negative rowid reports it"); + eq(rowid(w, "DELETE FROM lr"), null, "a DELETE after them reports null"); // SQLite restores the value when a trigger ends, so inserts made only by a trigger report null eq(exec(w, "CREATE TABLE lt(a)"), 0L, "create lt"); eq(exec(w, "CREATE TRIGGER lt_up AFTER UPDATE ON lt BEGIN INSERT INTO lr VALUES(100); END"), 0L, "create trigger"); From d7c5350109eb48b9e3e73fa22bffce5572d75b88 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 25 Nov 2026 00:45:07 -0800 Subject: [PATCH 5/6] ADFA-7298 Refuse every PRAGMA that sets a value, except user_version on execute's connection The authorizer allowed every PRAGMA not on its deny list. SQLite applies a flag PRAGMA (foreign_keys, ignore_check_constraints, recursive_triggers, reverse_unordered_selects) while it prepares the statement, so execute refused the statement afterwards (sqlite3_stmt_readonly) but the flag had already changed on the cached writable connection, and a later execute could skip CHECK or foreign key enforcement. The read-only connection had the same gap for cache_size, temp_store, mmap_size and the like. A PRAGMA with an argument (second authorizer argument non-NULL) is now refused on both connection kinds unless it is table_info, table_xinfo, table_list, index_info, index_xinfo, index_list, foreign_key_list, foreign_key_check, integrity_check or quick_check, or it is user_version on a writable connection. A PRAGMA without an argument keeps the old rules (the deny list still applies to those names). This replaces the journal_mode/schema_version and user_version/application_id argument checks, which the allowlist covers. application_id = n, wal_checkpoint(m) and incremental_vacuum(n) are now refused on the writable connection too. Checked: the server's own PRAGMAs (journal_mode, page_count, page_size, freelist_count, quick_check, integrity_check) take no argument, so every tool keeps working; PRAGMA query_only=1 runs in sqlitedbg_open_server before the authorizer is installed. Table-valued pragma_* functions run their PRAGMA through the same authorizer (pragma_table_info('t') arrives as table_info with argument t); the ones with a setting form take no argument, so they cannot set anything (checked on SQLite 3.46.1 with a Python authorizer, and in the host tests on 3.49.1). Tests (host C tests and JniQueryTest): foreign_keys, ignore_check_constraints, recursive_triggers, reverse_unordered_selects, cache_size, temp_store, mmap_size and application_id settings are refused on both connections and read back unchanged; a CHECK-violating INSERT still fails after the refused ignore_check_constraints; user_version = 7 runs on the writable connection and is refused on the read-only one; table_info, index_list, quick_check and pragma_table_info still run on both. Revert proof: with the allowlist condition disabled, the host test fails ("not refused (writable 0): PRAGMA foreign_keys = OFF (101)", "changed (writable 0): ignore_check_constraints"); restored, it passes. CodeRabbit threads 4691761588 and 4692209624. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 4 +- .../sqlite-debugger/src/main/cpp/sqlitedbg.c | 31 +++-- .../sqlite-debugger/src/main/cpp/sqlitedbg.h | 5 +- .../sqlitedebugger/engine/DebugEngine.kt | 5 +- .../sqlitedebugger/mcp/DatabaseTools.kt | 25 ++-- .../src/test/c/sqlitedbg_test.c | 108 +++++++++++++++++- .../src/test/jni/JniQueryTest.java | 22 ++++ 7 files changed, 176 insertions(+), 24 deletions(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 195faebba6..a49c637661 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -34,8 +34,8 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Debug builds only.** `DebuggerStartup.onCreate` throws if the process is not debuggable, so a release build that includes the library by mistake crashes at once instead of opening a local server. - **Loopback HTTP, a random port and token per start.** `McpHttp` binds 127.0.0.1 only (port 0, so the system picks one) and requires `Authorization: Bearer `, a new 32-byte random token each process start. It also checks that the Host and any Origin name 127.0.0.1 or localhost, against DNS rebinding. At most 8 connections at once. The head of a request (request line and headers) must arrive within 5 s, from connecting for a connection's first request and from its first byte for later ones, and Host, Origin, path and token are checked before the body is read, so a client that trickles bytes or never authenticates frees its slot; a refused request closes the connection. It opens no event stream: GET gets 405. -- **Read-only is a guard against accidents, not a security boundary.** Every tool but `execute` opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock across statements, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too; the JNI query path also rolls back any transaction left open (`sqlitedbg_end_transaction`, whose ROLLBACK is the one transaction statement the authorizer lets past), and a rollback that fails is the query's error. A server connection waits up to 3 s (`SQLITEDBG_SERVER_BUSY_MS`, fixed in C) for a lock the app holds, as in rollback-journal mode, and then reports `SQLITE_BUSY`. A statement that is running holds a lock, though: on a database that is not in WAL mode (rollback journal) a read holds a SHARED lock, and the app's own COMMIT waits for it only as long as requery's busy timeout, 2500 ms (`BUSY_TIMEOUT_MS` in requery/sqlite-android 3.49.0, `android_database_SQLiteConnection.cpp`). So the JNI query path, which every tool uses, reads `PRAGMA journal_mode` (without a value, so it only reads) on each call and stops a statement on a database that is not in WAL mode after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), with an error that says the database is not in WAL mode and to narrow the query or add a LIMIT. That also stops a `quick_check`, an `integrity_check` or a `get_stats` row count that runs longer than 1.5 s on such a database. A database in WAL mode keeps the 50 s limit, as readers do not block its writer. Anyone holding the token can run `execute`, so the token is the boundary, and the client decides which tools to allow (AI-Agent-MCP asks before each `execute`, ADFA-7300). -- **`execute` writes one statement, in autocommit (ADFA-7298).** Read-write is always available; there is no mode switch. `execute` runs on a second server connection per database, opened with `writable = true` (`SQLITE_OPEN_READWRITE`, never `SQLITE_OPEN_CREATE`) and cached apart from the read-only one, so a read never runs where writes are allowed. Its authorizer allows writes and schema changes and refuses what reaches the app rather than the data: transactions, savepoints, `ATTACH` (it would open a file the app may not have open), and `PRAGMA locking_mode`, `busy_timeout`, the heap limits, `temp_store_directory`, `query_only`, `writable_schema`, and setting `journal_mode` or `schema_version`; the read-only connection refuses them too. So a write cannot be part of a transaction: one statement per call, committed at once. A statement that does not write (`sqlite3_stmt_readonly`) is refused, to be run with `query`; rows from `RETURNING` are read and dropped. It binds `args` as `query` does and returns `changes`: `sqlite3_changes64`, or 0 when `sqlite3_total_changes64` did not move, since `sqlite3_changes64` keeps the previous write's count across a statement that changes no row, such as `CREATE TABLE` (ADFA-7131 comment 41489). `last_insert_rowid` is the rowid of the last row the statement inserted into a rowid table, or null when it inserted none (an `UPDATE`, a `WITHOUT ROWID` table, an ignored row). The writable connection is cached and SQLite keeps `sqlite3_last_insert_rowid` across statements, so the JNI layer sets it to -9223372036854775808 (`INT64_MIN`) with `sqlite3_set_last_insert_rowid` before each statement and reports any other value. Not 0, which is SQLite's own "none" but also a valid rowid: SQLite never assigns `INT64_MIN` itself (an empty table starts at 1, then the largest rowid plus 1, then random positive ones), so only a row inserted explicitly with that rowid reads as null (accepted). Rows a trigger inserts do not count, as SQLite restores the value when the trigger ends. A write holds the database's write lock until it ends, in WAL mode too, and the app's own writes wait for it only as long as requery's 2500 ms busy timeout, so every `execute` is stopped after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), whatever the journal mode, and rolled back. Without that cap, a long write in WAL mode made the app's own insert fail with `SQLITE_BUSY` in the JNI test. The transaction backstop runs after `execute` as after `query`. The app is not told about the change: Room's observers and other caches keep what they read until they read again (the Room warning is ADFA-7299). +- **Read-only is a guard against accidents, not a security boundary.** Every tool but `execute` opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock across statements, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too. A PRAGMA with an argument (`PRAGMA x = v`, `PRAGMA x(v)`) is refused as well, unless it is `table_info`, `table_xinfo`, `table_list`, `index_info`, `index_xinfo`, `index_list`, `foreign_key_list`, `foreign_key_check`, `integrity_check` or `quick_check`: SQLite applies a flag such as `foreign_keys`, `ignore_check_constraints`, `recursive_triggers` or `cache_size` while it prepares the statement, so refusing the write afterwards would come too late, and no setting can be changed. A PRAGMA without an argument only reads, and the table-valued `pragma_*` functions are checked as the PRAGMA they run. The JNI query path also rolls back any transaction left open (`sqlitedbg_end_transaction`, whose ROLLBACK is the one transaction statement the authorizer lets past), and a rollback that fails is the query's error. A server connection waits up to 3 s (`SQLITEDBG_SERVER_BUSY_MS`, fixed in C) for a lock the app holds, as in rollback-journal mode, and then reports `SQLITE_BUSY`. A statement that is running holds a lock, though: on a database that is not in WAL mode (rollback journal) a read holds a SHARED lock, and the app's own COMMIT waits for it only as long as requery's busy timeout, 2500 ms (`BUSY_TIMEOUT_MS` in requery/sqlite-android 3.49.0, `android_database_SQLiteConnection.cpp`). So the JNI query path, which every tool uses, reads `PRAGMA journal_mode` (without a value, so it only reads) on each call and stops a statement on a database that is not in WAL mode after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), with an error that says the database is not in WAL mode and to narrow the query or add a LIMIT. That also stops a `quick_check`, an `integrity_check` or a `get_stats` row count that runs longer than 1.5 s on such a database. A database in WAL mode keeps the 50 s limit, as readers do not block its writer. Anyone holding the token can run `execute`, so the token is the boundary, and the client decides which tools to allow (AI-Agent-MCP asks before each `execute`, ADFA-7300). +- **`execute` writes one statement, in autocommit (ADFA-7298).** Read-write is always available; there is no mode switch. `execute` runs on a second server connection per database, opened with `writable = true` (`SQLITE_OPEN_READWRITE`, never `SQLITE_OPEN_CREATE`) and cached apart from the read-only one, so a read never runs where writes are allowed. Its authorizer allows writes and schema changes and refuses what reaches the app rather than the data: transactions, savepoints, `ATTACH` (it would open a file the app may not have open), and `PRAGMA locking_mode`, `busy_timeout`, the heap limits, `temp_store_directory`, `query_only` and `writable_schema` in any form, and every PRAGMA with an argument except the reads listed above and `user_version`, so `PRAGMA user_version = n` is the one setting it can change (the read-only connection refuses that too). So `application_id = n`, `wal_checkpoint(mode)` and `incremental_vacuum(n)` are refused on the writable connection as well; the read-only connection refuses the rest of this list too. So a write cannot be part of a transaction: one statement per call, committed at once. A statement that does not write (`sqlite3_stmt_readonly`) is refused, to be run with `query`; rows from `RETURNING` are read and dropped. It binds `args` as `query` does and returns `changes`: `sqlite3_changes64`, or 0 when `sqlite3_total_changes64` did not move, since `sqlite3_changes64` keeps the previous write's count across a statement that changes no row, such as `CREATE TABLE` (ADFA-7131 comment 41489). `last_insert_rowid` is the rowid of the last row the statement inserted into a rowid table, or null when it inserted none (an `UPDATE`, a `WITHOUT ROWID` table, an ignored row). The writable connection is cached and SQLite keeps `sqlite3_last_insert_rowid` across statements, so the JNI layer sets it to -9223372036854775808 (`INT64_MIN`) with `sqlite3_set_last_insert_rowid` before each statement and reports any other value. Not 0, which is SQLite's own "none" but also a valid rowid: SQLite never assigns `INT64_MIN` itself (an empty table starts at 1, then the largest rowid plus 1, then random positive ones), so only a row inserted explicitly with that rowid reads as null (accepted). Rows a trigger inserts do not count, as SQLite restores the value when the trigger ends. A write holds the database's write lock until it ends, in WAL mode too, and the app's own writes wait for it only as long as requery's 2500 ms busy timeout, so every `execute` is stopped after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), whatever the journal mode, and rolled back. Without that cap, a long write in WAL mode made the app's own insert fail with `SQLITE_BUSY` in the JNI test. The transaction backstop runs after `execute` as after `query`. The app is not told about the change: Room's observers and other caches keep what they read until they read again (the Room warning is ADFA-7299). - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. Both checks fail with "unknown function" when a CHECK constraint or a NOT NULL virtual generated column calls such a function; a full `integrity_check` (`full: true`) also fails on an index on such an expression and on a partial index whose WHERE calls one, while `quick_check` (the default) does not fail on those two, and the description of `integrity_check` says to use it then. Views, triggers and other generated columns make neither fail (checked with SQLite 3.46). diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index 83ad7fc5c6..62bd68ec42 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -394,6 +394,21 @@ void sqlitedbg_set_client_connected(int connected) { // The user data of a writable server connection's authorizer; a read-only one gets NULL. static const int k_writable = 1; +// PRAGMAs that read and take a table, an index or a check limit as their argument, the ones a client +// needs to read a schema. +static const char *const k_read_pragmas[] = {"table_info", "table_xinfo", "table_list", "index_info", "index_xinfo", + "index_list", "foreign_key_list", "foreign_key_check", "integrity_check", + "quick_check"}; + +// Whether a PRAGMA given an argument (PRAGMA x = v, PRAGMA x(v)) may run: a read of that kind, or +// user_version on a writable connection. +static int pragma_argument_allowed(const char *name, int writable) { + if (writable && sqlite3_stricmp(name, "user_version") == 0) return 1; + for (size_t i = 0; i < sizeof k_read_pragmas / sizeof k_read_pragmas[0]; i++) + if (sqlite3_stricmp(name, k_read_pragmas[i]) == 0) return 1; + return 0; +} + static int server_authorizer(void *writable, int action, const char *a1, const char *a2, const char *db, const char *trigger) { (void)db; @@ -435,27 +450,25 @@ static int server_authorizer(void *writable, int action, const char *a1, const c return tls_ending_transaction && a1 && strcmp(a1, "ROLLBACK") == 0 ? SQLITE_OK : SQLITE_DENY; case SQLITE_PRAGMA: // Refused on every server connection, as they would reach the app's own connections or its - // file format, not just data. PRAGMA table_info(t) also has a second argument, so only - // these names are checked. locking_mode=EXCLUSIVE keeps the lock after a statement, and + // file format, not just data. locking_mode=EXCLUSIVE keeps the lock after a statement, and // busy_timeout (any form) lets a statement wait on the app's lock for as long as the client // likes. The heap limits and temp_store_directory are process-wide. query_only is the - // server's own guard. writable_schema and a schema_version write can leave a schema the - // app's SQLite reads as corrupt, and a journal_mode change switches the mode under the - // app's connections. + // server's own guard. writable_schema can leave a schema the app's SQLite reads as corrupt. if (a1 && (sqlite3_stricmp(a1, "query_only") == 0 || sqlite3_stricmp(a1, "writable_schema") == 0 || sqlite3_stricmp(a1, "locking_mode") == 0 || sqlite3_stricmp(a1, "busy_timeout") == 0 || sqlite3_stricmp(a1, "hard_heap_limit") == 0 || sqlite3_stricmp(a1, "soft_heap_limit") == 0 || sqlite3_stricmp(a1, "temp_store_directory") == 0)) return SQLITE_DENY; - if (a1 && a2 && (sqlite3_stricmp(a1, "journal_mode") == 0 || sqlite3_stricmp(a1, "schema_version") == 0)) - return SQLITE_DENY; + // A PRAGMA with an argument sets a value, unless it is a read that takes a name or a limit. + // SQLite applies a setting while it prepares the statement, so refusing the write later + // (sqlite3_stmt_readonly) is too late: foreign_keys, ignore_check_constraints, journal_mode, + // schema_version, cache_size ... would stay changed on the cached connection. + if (a1 && a2 && !pragma_argument_allowed(a1, writable != NULL)) return SQLITE_DENY; if (writable) return SQLITE_OK; // Read-only: a PRAGMA that writes the file is a write. if (a1 && (sqlite3_stricmp(a1, "wal_checkpoint") == 0 || sqlite3_stricmp(a1, "incremental_vacuum") == 0 || sqlite3_stricmp(a1, "optimize") == 0)) return SQLITE_DENY; - if (a1 && a2 && (sqlite3_stricmp(a1, "user_version") == 0 || sqlite3_stricmp(a1, "application_id") == 0)) - return SQLITE_DENY; return SQLITE_OK; default: return SQLITE_OK; diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index 3076a3396b..253db86867 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -160,7 +160,10 @@ void sqlitedbg_set_client_connected(int connected); // ROLLBACK, SAVEPOINT and RELEASE, ATTACH and DETACH, and the PRAGMAs that would reach the app rather // than the data: locking_mode and busy_timeout (a client could hold a lock across statements, or wait // on the app's for as long as it likes), the process-wide hard_heap_limit, soft_heap_limit and -// temp_store_directory, query_only, writable_schema, and setting journal_mode or schema_version. +// temp_store_directory, query_only and writable_schema. A PRAGMA with an argument is refused too, as SQLite +// applies a setting while it prepares the statement, unless it reads (table_info, table_xinfo, table_list, +// index_info, index_xinfo, index_list, foreign_key_list, foreign_key_check, integrity_check, quick_check) +// or is user_version on a writable connection. // Read-only also sets PRAGMA query_only and refuses every write. Within one statement a lock is held // while it runs, so the JNI layer stops a read on a database that is not in WAL mode, and every // write, after SQLITEDBG_SERVER_NON_WAL_MS. Read-only mode guards against accidents; it is not a diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt index 2533ff3cc7..67afd007e6 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/engine/DebugEngine.kt @@ -34,8 +34,9 @@ interface DebugEngine { /** * Opens [path] for the server: read-only (an authorizer refuses writes) unless [writable]. Either - * way the authorizer refuses transactions and the PRAGMAs that would reach the app's own - * connections (sqlitedbg.h). Only a path one of [connections] has open may be passed: opening a + * way the authorizer refuses transactions, the PRAGMAs that would reach the app's own + * connections and every PRAGMA that sets a value, user_version on a writable one excepted (sqlitedbg.h). + * Only a path one of [connections] has open may be passed: opening a * database that Android's own SQLite has open, with requery's, can corrupt it (ADFA-7131, Design 3). * * @throws DebugEngineException if SQLite cannot open it, or no app connection has opened yet. diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index b5e920dc5c..e5e8ac8894 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -16,9 +16,10 @@ import java.util.TimerTask * The debugger's MCP tools. All but execute are read-only: they open server connections through * [engine] with `writable = false`, so SQLite's authorizer refuses a write whatever SQL a client * sends. execute (ADFA-7298) runs one statement that writes on a separate writable connection, in - * autocommit; on both, the authorizer refuses transactions and the PRAGMAs that would reach the - * app's own connections. Read-only was a guard against accidents, not a security boundary - * (ADFA-7131, D11); the client decides which tools to allow. A tool + * autocommit; on both, the authorizer refuses transactions, the PRAGMAs that would reach the + * app's own connections and every PRAGMA that sets a value (user_version on the writable one excepted). + * Read-only was a guard against accidents, not a security boundary (ADFA-7131, D11); the client decides + * which tools to allow. A tool * names a database by the path one of the app's own connections has open; any other path is * refused before the engine is called (opening a file Android's SQLite has open, with the * extension's SQLite, can corrupt it). @@ -102,6 +103,10 @@ class DatabaseTools internal constructor( "A statement is stopped and rolled back after 1.5 s (best effort: it can run up to about 3 s longer), in every " + "journal mode, so a long write does not make the app's own writes fail; change fewer rows per call." + private const val READ_PRAGMAS_NOTE = + "table_info, table_xinfo, table_list, index_info, index_xinfo, index_list, foreign_key_list, " + + "foreign_key_check, integrity_check or quick_check (no setting can be changed)" + /** Server connections never load what the app registers on its own connections (see the README). */ private const val APP_FUNCTIONS_NOTE = "Functions the app adds to its own connections, such as sqlite-js's stored JavaScript functions, do not exist " + @@ -271,7 +276,8 @@ class DatabaseTools internal constructor( "A result also stops at about " + "${MAX_TOTAL_BYTES / (1024 * 1024)} MiB of cell bytes (has_more is then true), though the first row always " + "comes back whole. Use offset to page. " + - "$PAGING_NOTE Writes are refused: use execute. $APP_FUNCTIONS_NOTE: read the rows or compute in plain SQL instead. $NON_WAL_NOTE", + "$PAGING_NOTE Writes are refused: use execute. A PRAGMA with an argument is refused unless it is " + + "$READ_PRAGMAS_NOTE. $APP_FUNCTIONS_NOTE: read the rows or compute in plain SQL instead. $NON_WAL_NOTE", databaseSchema( "sql" to prop("string", "The SQL statement."), "args" to JSONObject().put("type", "array").put("description", "Values for ? parameters: null, numbers or strings."), @@ -283,17 +289,18 @@ class DatabaseTools internal constructor( tool( "execute", "Run a statement that writes", - "Runs one SQL statement that writes, such as INSERT, UPDATE, DELETE, CREATE, DROP, ALTER or a PRAGMA that " + - "stores a value, on the app's database, in autocommit: it is committed at once and cannot be undone. " + + "Runs one SQL statement that writes, such as INSERT, UPDATE, DELETE, CREATE, DROP, ALTER or " + + "PRAGMA user_version = n, on the app's database, in autocommit: it is committed at once and cannot be undone. " + "Returns changes, the rows the statement itself inserted, updated or deleted (not those of triggers or " + "foreign key actions), and 0 for one that changes no row, such as CREATE TABLE, and last_insert_rowid, " + "the rowid of the last row it inserted into a rowid table, or null when it inserted none (an UPDATE, " + "a WITHOUT ROWID table, an ignored row; rows inserted by triggers do not count). One statement per call; " + "BEGIN, COMMIT, ROLLBACK and SAVEPOINT are refused, so several statements cannot be made atomic. " + "A statement that does not write is refused: use query. Rows from RETURNING are not returned. " + - "Also refused: ATTACH, and PRAGMA locking_mode, busy_timeout, query_only, writable_schema, the heap limits, " + - "temp_store_directory, and setting journal_mode or schema_version, as they would reach the app's own " + - "connections. $WRITE_NOTE The app is not told about the change: a screen showing this data may stay " + + "Also refused: ATTACH, every PRAGMA that takes a value except user_version (no setting can be " + + "changed), and PRAGMA locking_mode, busy_timeout, query_only, writable_schema, the heap limits and " + + "temp_store_directory in any form, as they would reach the app's own connections. $WRITE_NOTE " + + "The app is not told about the change: a screen showing this data may stay " + "stale until it reads it again. $APP_FUNCTIONS_NOTE.", databaseSchema( "sql" to prop("string", "The SQL statement."), diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index e3e36db88a..08ce59ed75 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -634,7 +634,7 @@ static void test_server(void) { CHECK_EQ(sqlite3_db_readonly(srv, "main"), 0); CHECK_EQ(step_all(srv, "INSERT INTO t VALUES(1234)"), SQLITE_DONE); CHECK_EQ(list_conns(&l), before); - // ADFA-7298: ordinary writes, schema changes and the PRAGMAs that only store data are allowed + // ADFA-7298: ordinary writes and schema changes are allowed CHECK_EQ(step_all(srv, "UPDATE t SET a=a WHERE a=1234"), SQLITE_DONE); CHECK_EQ(step_all(srv, "CREATE TABLE w(a)"), SQLITE_DONE); CHECK_EQ(step_all(srv, "CREATE INDEX wi ON w(a)"), SQLITE_DONE); @@ -724,6 +724,111 @@ static void test_server_holds_no_locks(void) { CHECK_EQ(sqlite3_close_v2(srv), SQLITE_OK); } +// The first column of the first row of a statement, or -1. +static long long first_int(sqlite3 *db, const char *sql) { + sqlite3_stmt *st; + long long v = -1; + if (sqlite3_prepare_v2(db, sql, -1, &st, NULL) != SQLITE_OK) return -1; + if (sqlite3_step(st) == SQLITE_ROW) v = sqlite3_column_int64(st, 0); + sqlite3_finalize(st); + return v; +} + +// ADFA-7298 review: SQLite applies a flag PRAGMA while it prepares the statement, so a PRAGMA with an +// argument is refused unless it is a read of a table, an index or a check limit (or user_version on a +// writable connection), and the setting is left as it was. +static void test_server_pragma_allowlist(void) { + char path[320]; + snprintf(path, sizeof path, "%s/pragmas.db", g_dir); + sqlite3 *app = open_app(path); + exec_ok(app, "CREATE TABLE pt(a INTEGER CHECK(a > 0))"); + exec_ok(app, "CREATE INDEX pi ON pt(a)"); + // settings whose value changes at prepare time, and others that only tune the connection + static const char *const settings[] = { + "PRAGMA foreign_keys = OFF", + "PRAGMA foreign_keys(0)", + "PRAGMA ignore_check_constraints = 1", + "PRAGMA recursive_triggers = 1", + "PRAGMA reverse_unordered_selects = 1", + "PRAGMA cache_size = 1", + "PRAGMA temp_store = 2", + "PRAGMA mmap_size = 0", + "PRAGMA application_id = 5", + }; + static const char *const flags[] = {"foreign_keys", "ignore_check_constraints", "recursive_triggers", + "reverse_unordered_selects", "cache_size", "temp_store", "mmap_size", + "application_id"}; + for (int writable = 0; writable < 2; writable++) { + sqlite3 *srv = NULL; + CHECK_EQ(sqlitedbg_open_server(path, writable, &srv), SQLITE_OK); + long long before[sizeof flags / sizeof flags[0]]; + char sql[64]; + for (size_t i = 0; i < sizeof flags / sizeof flags[0]; i++) { + snprintf(sql, sizeof sql, "PRAGMA %s", flags[i]); + before[i] = first_int(srv, sql); + } + for (size_t i = 0; i < sizeof settings / sizeof settings[0]; i++) { + int rc = step_all(srv, settings[i]); + if (rc != SQLITE_AUTH) fprintf(stderr, "not refused (writable %d): %s (%d)\n", writable, settings[i], rc); + CHECK_EQ(rc, SQLITE_AUTH); + } + for (size_t i = 0; i < sizeof flags / sizeof flags[0]; i++) { + snprintf(sql, sizeof sql, "PRAGMA %s", flags[i]); + long long now = first_int(srv, sql); + if (now != before[i]) fprintf(stderr, "changed (writable %d): %s\n", writable, flags[i]); + CHECK_EQ(now, before[i]); + } + if (writable) { + // ignore_check_constraints stayed off: a CHECK violation still fails + CHECK_EQ(step_all(srv, "INSERT INTO pt VALUES(-1)"), SQLITE_CONSTRAINT); + CHECK_EQ(step_all(srv, "INSERT INTO pt VALUES(1)"), SQLITE_DONE); + CHECK_EQ(step_all(srv, "DELETE FROM pt"), SQLITE_DONE); + // user_version is the one setting that runs + CHECK_EQ(step_all(srv, "PRAGMA user_version = 7"), SQLITE_DONE); + CHECK_EQ(first_int(srv, "PRAGMA user_version"), 7); + CHECK_EQ(step_all(srv, "PRAGMA user_version(0)"), SQLITE_DONE); + } else { + CHECK_EQ(step_all(srv, "PRAGMA user_version = 7"), SQLITE_AUTH); + CHECK_EQ(first_int(srv, "PRAGMA user_version"), 0); + } + // the reads a client needs to read a schema, with or without an argument + static const char *const reads[] = { + "PRAGMA table_info(pt)", + "PRAGMA table_xinfo(pt)", + "PRAGMA table_list(pt)", + "PRAGMA table_list", + "PRAGMA index_list(pt)", + "PRAGMA index_info(pi)", + "PRAGMA index_xinfo(pi)", + "PRAGMA foreign_key_list(pt)", + "PRAGMA foreign_key_check(pt)", + "PRAGMA foreign_key_check", + "PRAGMA quick_check", + "PRAGMA quick_check(5)", + "PRAGMA integrity_check(5)", + "PRAGMA main.table_info(pt)", + "PRAGMA foreign_keys", + "PRAGMA journal_mode", + "PRAGMA page_count", + "PRAGMA user_version", + "SELECT * FROM pragma_table_info('pt')", + "SELECT * FROM pragma_index_list('pt')", + "SELECT * FROM pragma_integrity_check", + "SELECT * FROM pragma_foreign_keys", + }; + for (size_t i = 0; i < sizeof reads / sizeof reads[0]; i++) { + int rc = step_all(srv, reads[i]); + if (rc != SQLITE_DONE) fprintf(stderr, "read refused (writable %d): %s (%d)\n", writable, reads[i], rc); + CHECK_EQ(rc, SQLITE_DONE); + } + // a table-valued PRAGMA function is authorized as the PRAGMA it runs, so it cannot set one + CHECK(step_all(srv, "SELECT * FROM pragma_cache_size(1)") != SQLITE_DONE); + CHECK_EQ(first_int(srv, "PRAGMA cache_size"), before[4]); + CHECK_EQ(sqlite3_close_v2(srv), SQLITE_OK); + } + CHECK_EQ(sqlite3_close(app), SQLITE_OK); +} + extern int (*const sqlitedbg_test_server_authorizer)(void *, int, const char *, const char *, const char *, const char *); // sqlitedbg.c, built with SQLITEDBG_TEST @@ -1110,6 +1215,7 @@ int main(int argc, char **argv) { test_server(); printf("# server holds no locks\n"); test_server_holds_no_locks(); + test_server_pragma_allowlist(); test_server_ends_transaction(); printf("# server waits for locks\n"); test_server_waits_for_locks(); diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index 4d783f0028..c106adbbe9 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -181,6 +181,28 @@ static void execute(Path dir, String path, long app) throws Exception { eq(execCode(w, "ROLLBACK", new Object[0], FAR), 23, "ROLLBACK refused"); eq(execCode(w, "PRAGMA journal_mode = DELETE", new Object[0], FAR), 23, "journal_mode change refused"); eq(execCode(w, "PRAGMA busy_timeout = 60000", new Object[0], FAR), 23, "busy_timeout refused"); + // a PRAGMA that sets a value is refused before it changes anything (SQLite applies a flag while preparing) + eq(exec(w, "CREATE TABLE pc(a INTEGER CHECK(a > 0))"), 0L, "a table with a CHECK"); + for (String sql : new String[] {"PRAGMA foreign_keys = OFF", "PRAGMA ignore_check_constraints = 1", + "PRAGMA recursive_triggers = 1", "PRAGMA reverse_unordered_selects = 1", "PRAGMA cache_size = 1"}) { + eq(execCode(w, sql, new Object[0], FAR), 23, sql + " refused: SQLITE_AUTH"); + eq(execCode(r, sql, new Object[0], FAR), 23, "read-only " + sql + " refused: SQLITE_AUTH"); + } + eq(q(w, "PRAGMA ignore_check_constraints").rows.get(0)[0], 0L, "ignore_check_constraints is still 0"); + eq(execCode(w, "INSERT INTO pc VALUES(-1)", new Object[0], FAR), 19, "a CHECK violation still fails: SQLITE_CONSTRAINT"); + eq(q(w, "SELECT count(*) FROM pc").rows.get(0)[0], 0L, "and wrote nothing"); + eq(execCode(r, "PRAGMA user_version = 7", new Object[0], FAR), 23, "read-only user_version = 7 refused: SQLITE_AUTH"); + eq(q(r, "PRAGMA user_version").rows.get(0)[0], 0L, "and not stored"); + // reads that take a table, an index or a limit still run, on both + for (long h : new long[] {w, r}) { + eq(refusal(h, "PRAGMA table_info(pc)"), null, "table_info(pc)"); + eq(refusal(h, "PRAGMA index_list(pc)"), null, "index_list(pc)"); + eq(refusal(h, "PRAGMA quick_check"), null, "quick_check"); + eq(refusal(h, "PRAGMA integrity_check(3)"), null, "integrity_check(3)"); + eq(refusal(h, "SELECT * FROM pragma_table_info('pc')"), null, "pragma_table_info('pc')"); + } + eq(q(r, "SELECT name FROM pragma_table_info('pc')").rows.get(0)[0], "a", "the columns of pc"); + eq(exec(w, "DROP TABLE pc"), 0L, "drop pc"); eq(execCode(w, "DELETE FROM t WHERE id = -1", new Object[0], System.currentTimeMillis() - 1), 9, "a deadline already past"); // a read-only connection still refuses a write through execute eq(execCode(r, "INSERT INTO t(id) VALUES(6004)", new Object[0], FAR), 23, "read-only connection: SQLITE_AUTH"); From 01413e038795a13c15d204e2eff85d729257f548 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 25 Nov 2026 00:49:45 -0800 Subject: [PATCH 6/6] ADFA-7298 Enforce foreign keys on execute's writable connection The app's own connections may run with foreign keys off (SQLite's default), so a debugger write through execute could leave orphan rows, or skip an ON DELETE CASCADE that the schema declares. sqlitedbg_open_server now turns foreign keys on for a writable connection with sqlite3_db_config(SQLITE_DBCONFIG_ENABLE_FKEY, 1), before any statement. db_config rather than a PRAGMA, so the authorizer (which now refuses PRAGMA foreign_keys) is not involved. ON DELETE and ON UPDATE actions now run for execute's deletes and updates, and a write the app could make with foreign keys off may be refused; the README and the execute tool description say so. The read-only connection is left alone. Checked: sqlite3_db_config is in the sqlite3ext.h api table (db_config), so the JNI build, which has no SQLITE_CORE and runs against a requery-like libsqlite3x.so, reaches it; the host C tests call it directly. SQLite's default is off: the host test asserts PRAGMA foreign_keys = 0 on a plain connection of its build, which sets no SQLITE_DEFAULT_FOREIGN_KEYS. Whether requery's shipped libsqlite3x.so sets that default is unverified (its compile options are not readable from the binary's strings); it makes no difference here, since the setting is forced on. Tests (host C tests and JniQueryTest): with a parent/child schema, FOREIGN KEY ... ON DELETE CASCADE, an execute INSERT of a child with no parent fails with a foreign key error and writes nothing, and an execute DELETE of a parent removes its children; PRAGMA foreign_keys reads 1 on the writable connection and 0 on the app's and the read-only one. Revert proof: with the db_config call disabled, the host test fails ("first_int(srv, "PRAGMA foreign_keys") == 1 (0 vs 1)", "INSERT INTO child VALUES(11, 99) == SQLITE_CONSTRAINT (101 vs 19)"); restored, it passes. CodeRabbit threads 4691761588 and 4692209624. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- .../sqlite-debugger/src/main/cpp/sqlitedbg.c | 3 ++ .../sqlite-debugger/src/main/cpp/sqlitedbg.h | 1 + .../sqlitedebugger/mcp/DatabaseTools.kt | 2 ++ .../src/test/c/sqlitedbg_test.c | 29 +++++++++++++++++++ .../src/test/jni/JniQueryTest.java | 11 +++++++ 6 files changed, 47 insertions(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index a49c637661..b6a52def94 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -35,7 +35,7 @@ The layout of `sqlitedbg_event_record` lives in `sqlitedbg.h`. The JNI layer han - **Debug builds only.** `DebuggerStartup.onCreate` throws if the process is not debuggable, so a release build that includes the library by mistake crashes at once instead of opening a local server. - **Loopback HTTP, a random port and token per start.** `McpHttp` binds 127.0.0.1 only (port 0, so the system picks one) and requires `Authorization: Bearer `, a new 32-byte random token each process start. It also checks that the Host and any Origin name 127.0.0.1 or localhost, against DNS rebinding. At most 8 connections at once. The head of a request (request line and headers) must arrive within 5 s, from connecting for a connection's first request and from its first byte for later ones, and Host, Origin, path and token are checked before the body is read, so a client that trickles bytes or never authenticates frees its slot; a refused request closes the connection. It opens no event stream: GET gets 405. - **Read-only is a guard against accidents, not a security boundary.** Every tool but `execute` opens its server connection with `writable = false`: `SQLITE_OPEN_READONLY`, `PRAGMA query_only` and an authorizer that refuses ordinary writes, transactions and savepoints, and `PRAGMA locking_mode` and `busy_timeout`, so a client cannot hold a lock across statements, and `hard_heap_limit`, `soft_heap_limit` and `temp_store_directory`, which SQLite applies process-wide, to the app's connections too. A PRAGMA with an argument (`PRAGMA x = v`, `PRAGMA x(v)`) is refused as well, unless it is `table_info`, `table_xinfo`, `table_list`, `index_info`, `index_xinfo`, `index_list`, `foreign_key_list`, `foreign_key_check`, `integrity_check` or `quick_check`: SQLite applies a flag such as `foreign_keys`, `ignore_check_constraints`, `recursive_triggers` or `cache_size` while it prepares the statement, so refusing the write afterwards would come too late, and no setting can be changed. A PRAGMA without an argument only reads, and the table-valued `pragma_*` functions are checked as the PRAGMA they run. The JNI query path also rolls back any transaction left open (`sqlitedbg_end_transaction`, whose ROLLBACK is the one transaction statement the authorizer lets past), and a rollback that fails is the query's error. A server connection waits up to 3 s (`SQLITEDBG_SERVER_BUSY_MS`, fixed in C) for a lock the app holds, as in rollback-journal mode, and then reports `SQLITE_BUSY`. A statement that is running holds a lock, though: on a database that is not in WAL mode (rollback journal) a read holds a SHARED lock, and the app's own COMMIT waits for it only as long as requery's busy timeout, 2500 ms (`BUSY_TIMEOUT_MS` in requery/sqlite-android 3.49.0, `android_database_SQLiteConnection.cpp`). So the JNI query path, which every tool uses, reads `PRAGMA journal_mode` (without a value, so it only reads) on each call and stops a statement on a database that is not in WAL mode after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), with an error that says the database is not in WAL mode and to narrow the query or add a LIMIT. That also stops a `quick_check`, an `integrity_check` or a `get_stats` row count that runs longer than 1.5 s on such a database. A database in WAL mode keeps the 50 s limit, as readers do not block its writer. Anyone holding the token can run `execute`, so the token is the boundary, and the client decides which tools to allow (AI-Agent-MCP asks before each `execute`, ADFA-7300). -- **`execute` writes one statement, in autocommit (ADFA-7298).** Read-write is always available; there is no mode switch. `execute` runs on a second server connection per database, opened with `writable = true` (`SQLITE_OPEN_READWRITE`, never `SQLITE_OPEN_CREATE`) and cached apart from the read-only one, so a read never runs where writes are allowed. Its authorizer allows writes and schema changes and refuses what reaches the app rather than the data: transactions, savepoints, `ATTACH` (it would open a file the app may not have open), and `PRAGMA locking_mode`, `busy_timeout`, the heap limits, `temp_store_directory`, `query_only` and `writable_schema` in any form, and every PRAGMA with an argument except the reads listed above and `user_version`, so `PRAGMA user_version = n` is the one setting it can change (the read-only connection refuses that too). So `application_id = n`, `wal_checkpoint(mode)` and `incremental_vacuum(n)` are refused on the writable connection as well; the read-only connection refuses the rest of this list too. So a write cannot be part of a transaction: one statement per call, committed at once. A statement that does not write (`sqlite3_stmt_readonly`) is refused, to be run with `query`; rows from `RETURNING` are read and dropped. It binds `args` as `query` does and returns `changes`: `sqlite3_changes64`, or 0 when `sqlite3_total_changes64` did not move, since `sqlite3_changes64` keeps the previous write's count across a statement that changes no row, such as `CREATE TABLE` (ADFA-7131 comment 41489). `last_insert_rowid` is the rowid of the last row the statement inserted into a rowid table, or null when it inserted none (an `UPDATE`, a `WITHOUT ROWID` table, an ignored row). The writable connection is cached and SQLite keeps `sqlite3_last_insert_rowid` across statements, so the JNI layer sets it to -9223372036854775808 (`INT64_MIN`) with `sqlite3_set_last_insert_rowid` before each statement and reports any other value. Not 0, which is SQLite's own "none" but also a valid rowid: SQLite never assigns `INT64_MIN` itself (an empty table starts at 1, then the largest rowid plus 1, then random positive ones), so only a row inserted explicitly with that rowid reads as null (accepted). Rows a trigger inserts do not count, as SQLite restores the value when the trigger ends. A write holds the database's write lock until it ends, in WAL mode too, and the app's own writes wait for it only as long as requery's 2500 ms busy timeout, so every `execute` is stopped after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), whatever the journal mode, and rolled back. Without that cap, a long write in WAL mode made the app's own insert fail with `SQLITE_BUSY` in the JNI test. The transaction backstop runs after `execute` as after `query`. The app is not told about the change: Room's observers and other caches keep what they read until they read again (the Room warning is ADFA-7299). +- **`execute` writes one statement, in autocommit (ADFA-7298).** Read-write is always available; there is no mode switch. `execute` runs on a second server connection per database, opened with `writable = true` (`SQLITE_OPEN_READWRITE`, never `SQLITE_OPEN_CREATE`) and cached apart from the read-only one, so a read never runs where writes are allowed. Its authorizer allows writes and schema changes and refuses what reaches the app rather than the data: transactions, savepoints, `ATTACH` (it would open a file the app may not have open), and `PRAGMA locking_mode`, `busy_timeout`, the heap limits, `temp_store_directory`, `query_only` and `writable_schema` in any form, and every PRAGMA with an argument except the reads listed above and `user_version`, so `PRAGMA user_version = n` is the one setting it can change (the read-only connection refuses that too). So `application_id = n`, `wal_checkpoint(mode)` and `incremental_vacuum(n)` are refused on the writable connection as well; the read-only connection refuses the rest of this list too. The writable connection also enforces foreign keys (`sqlite3_db_config` with `SQLITE_DBCONFIG_ENABLE_FKEY`, set when it is opened), whatever the app's own connections do, so a write cannot leave orphan rows: `ON DELETE` and `ON UPDATE` actions run for its deletes and updates (their rows are not in `changes`), and a write the app itself could make with foreign keys off may be refused. SQLite's default is off (`SQLITE_DEFAULT_FOREIGN_KEYS` is 0, which the host tests confirm on their build); the read-only connection leaves it alone. So a write cannot be part of a transaction: one statement per call, committed at once. A statement that does not write (`sqlite3_stmt_readonly`) is refused, to be run with `query`; rows from `RETURNING` are read and dropped. It binds `args` as `query` does and returns `changes`: `sqlite3_changes64`, or 0 when `sqlite3_total_changes64` did not move, since `sqlite3_changes64` keeps the previous write's count across a statement that changes no row, such as `CREATE TABLE` (ADFA-7131 comment 41489). `last_insert_rowid` is the rowid of the last row the statement inserted into a rowid table, or null when it inserted none (an `UPDATE`, a `WITHOUT ROWID` table, an ignored row). The writable connection is cached and SQLite keeps `sqlite3_last_insert_rowid` across statements, so the JNI layer sets it to -9223372036854775808 (`INT64_MIN`) with `sqlite3_set_last_insert_rowid` before each statement and reports any other value. Not 0, which is SQLite's own "none" but also a valid rowid: SQLite never assigns `INT64_MIN` itself (an empty table starts at 1, then the largest rowid plus 1, then random positive ones), so only a row inserted explicitly with that rowid reads as null (accepted). Rows a trigger inserts do not count, as SQLite restores the value when the trigger ends. A write holds the database's write lock until it ends, in WAL mode too, and the app's own writes wait for it only as long as requery's 2500 ms busy timeout, so every `execute` is stopped after 1.5 s (`SQLITEDBG_SERVER_NON_WAL_MS`), whatever the journal mode, and rolled back. Without that cap, a long write in WAL mode made the app's own insert fail with `SQLITE_BUSY` in the JNI test. The transaction backstop runs after `execute` as after `query`. The app is not told about the change: Room's observers and other caches keep what they read until they read again (the Room warning is ADFA-7299). - **Only databases an app connection has open.** `DatabaseTools` refuses any other path before the engine is called: opening a file Android's own SQLite has open, with requery's, can corrupt it. The extension has no SQLite API until an app connection has opened, so `sqlitedbg_open_server` returns `SQLITE_MISUSE` before that. - **The app's connections are never altered.** The extension never sets the progress handler or the update hook of an app connection: requery sets and clears the progress handler around cancellable statements, and the update hook belongs to the app. Only server connections use a progress handler, for the time limit. - **The app's own functions are not available.** Every tool runs on a server connection (`sqlitedbg_open_server`), never on one of the app's connections, which the SQLite debugger does not alter. SQLite registers functions per connection, so a server connection has only SQLite's built-in functions and those of extensions registered for every connection with `sqlite3_auto_extension`. What the app adds to its own connections is missing: requery's `SQLiteCustomFunction`s and `SQLiteCustomExtension`s, among them sqlite-js and the JavaScript functions it loads from `js_functions`. SQL that calls one, directly or through a view, fails with "no such function", although the app's own queries run it. The descriptions of `query` and `explain_query_plan` say so, so the agent reads the rows or computes in plain SQL instead. Both checks fail with "unknown function" when a CHECK constraint or a NOT NULL virtual generated column calls such a function; a full `integrity_check` (`full: true`) also fails on an index on such an expression and on a partial index whose WHERE calls one, while `quick_check` (the default) does not fail on those two, and the description of `integrity_check` says to use it then. Views, triggers and other generated columns make neither fail (checked with SQLite 3.46). diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c index 62bd68ec42..0c28ceafbe 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.c @@ -501,6 +501,9 @@ int sqlitedbg_open_server(const char *path, int writable, sqlite3 **db) { int rc = sqlite3_open_v2(path, db, writable ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY, NULL); tls_opening_server = 0; if (rc == SQLITE_OK && !writable) rc = sqlite3_exec(*db, "PRAGMA query_only=1", NULL, NULL, NULL); + // A write must not leave orphan rows whatever the app's own connections do. db_config, not a PRAGMA: + // the authorizer refuses PRAGMA foreign_keys, and is not installed yet. + if (rc == SQLITE_OK && writable) rc = sqlite3_db_config(*db, SQLITE_DBCONFIG_ENABLE_FKEY, 1, NULL); if (rc == SQLITE_OK) rc = sqlite3_set_authorizer(*db, server_authorizer, writable ? (void *)&k_writable : NULL); // In rollback-journal mode a reader fails at once while the app holds a write lock. Wait a little, // well under the tools' 50 s deadline; the client cannot change it (PRAGMA busy_timeout is refused). diff --git a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h index 253db86867..e322b9084f 100644 --- a/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h +++ b/subprojects/sqlite-debugger/src/main/cpp/sqlitedbg.h @@ -164,6 +164,7 @@ void sqlitedbg_set_client_connected(int connected); // applies a setting while it prepares the statement, unless it reads (table_info, table_xinfo, table_list, // index_info, index_xinfo, index_list, foreign_key_list, foreign_key_check, integrity_check, quick_check) // or is user_version on a writable connection. +// A writable connection also enforces foreign keys, whatever the app's connections do. // Read-only also sets PRAGMA query_only and refuses every write. Within one statement a lock is held // while it runs, so the JNI layer stops a read on a database that is not in WAL mode, and every // write, after SQLITEDBG_SERVER_NON_WAL_MS. Read-only mode guards against accidents; it is not a diff --git a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt index e5e8ac8894..59ac607c9a 100644 --- a/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt +++ b/subprojects/sqlite-debugger/src/main/java/org/appdevforall/sqlitedebugger/mcp/DatabaseTools.kt @@ -297,6 +297,8 @@ class DatabaseTools internal constructor( "a WITHOUT ROWID table, an ignored row; rows inserted by triggers do not count). One statement per call; " + "BEGIN, COMMIT, ROLLBACK and SAVEPOINT are refused, so several statements cannot be made atomic. " + "A statement that does not write is refused: use query. Rows from RETURNING are not returned. " + + "Foreign keys are enforced here whatever the app's own connections do: ON DELETE and ON UPDATE actions " + + "run, and a write the app could make with foreign keys off may be refused. " + "Also refused: ATTACH, every PRAGMA that takes a value except user_version (no setting can be " + "changed), and PRAGMA locking_mode, busy_timeout, query_only, writable_schema, the heap limits and " + "temp_store_directory in any form, as they would reach the app's own connections. $WRITE_NOTE " + diff --git a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c index 08ce59ed75..5af550f109 100644 --- a/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c +++ b/subprojects/sqlite-debugger/src/test/c/sqlitedbg_test.c @@ -829,6 +829,34 @@ static void test_server_pragma_allowlist(void) { CHECK_EQ(sqlite3_close(app), SQLITE_OK); } +// ADFA-7298 review: a writable server connection enforces foreign keys, whatever the app's connection does. +static void test_server_foreign_keys(void) { + char path[320]; + snprintf(path, sizeof path, "%s/fk.db", g_dir); + sqlite3 *app = open_app(path); + // SQLite's default here (no SQLITE_DEFAULT_FOREIGN_KEYS in the build): off + CHECK_EQ(first_int(app, "PRAGMA foreign_keys"), 0); + exec_ok(app, "CREATE TABLE parent(id INTEGER PRIMARY KEY)"); + exec_ok(app, "CREATE TABLE child(id INTEGER PRIMARY KEY, p INTEGER REFERENCES parent(id) ON DELETE CASCADE)"); + exec_ok(app, "INSERT INTO parent VALUES(1)"); + exec_ok(app, "INSERT INTO child VALUES(10, 1)"); + + sqlite3 *srv = NULL; + CHECK_EQ(sqlitedbg_open_server(path, 1, &srv), SQLITE_OK); + CHECK_EQ(first_int(srv, "PRAGMA foreign_keys"), 1); + CHECK_EQ(step_all(srv, "INSERT INTO child VALUES(11, 99)"), SQLITE_CONSTRAINT); + CHECK_EQ(first_int(app, "SELECT count(*) FROM child WHERE id = 11"), 0); + CHECK_EQ(step_all(srv, "DELETE FROM parent WHERE id = 1"), SQLITE_DONE); + CHECK_EQ(first_int(app, "SELECT count(*) FROM child"), 0); + // the app's own connection is untouched, and a read-only server connection does not enforce + CHECK_EQ(first_int(app, "PRAGMA foreign_keys"), 0); + CHECK_EQ(sqlite3_close_v2(srv), SQLITE_OK); + CHECK_EQ(sqlitedbg_open_server(path, 0, &srv), SQLITE_OK); + CHECK_EQ(first_int(srv, "PRAGMA foreign_keys"), 0); + CHECK_EQ(sqlite3_close_v2(srv), SQLITE_OK); + CHECK_EQ(sqlite3_close(app), SQLITE_OK); +} + extern int (*const sqlitedbg_test_server_authorizer)(void *, int, const char *, const char *, const char *, const char *); // sqlitedbg.c, built with SQLITEDBG_TEST @@ -1216,6 +1244,7 @@ int main(int argc, char **argv) { printf("# server holds no locks\n"); test_server_holds_no_locks(); test_server_pragma_allowlist(); + test_server_foreign_keys(); test_server_ends_transaction(); printf("# server waits for locks\n"); test_server_waits_for_locks(); diff --git a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java index c106adbbe9..2195f295bd 100644 --- a/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java +++ b/subprojects/sqlite-debugger/src/test/jni/JniQueryTest.java @@ -203,6 +203,17 @@ static void execute(Path dir, String path, long app) throws Exception { } eq(q(r, "SELECT name FROM pragma_table_info('pc')").rows.get(0)[0], "a", "the columns of pc"); eq(exec(w, "DROP TABLE pc"), 0L, "drop pc"); + // foreign keys are enforced on this connection, whatever the app's own connections do + eq(exec(w, "CREATE TABLE fp(id INTEGER PRIMARY KEY)"), 0L, "create fp"); + eq(exec(w, "CREATE TABLE fc(id INTEGER PRIMARY KEY, p INTEGER REFERENCES fp(id) ON DELETE CASCADE)"), 0L, "create fc"); + eq(exec(w, "INSERT INTO fp VALUES(1)"), 1L, "a parent"); + eq(exec(w, "INSERT INTO fc VALUES(10, 1)"), 1L, "a child with its parent"); + eq(execRefusal(w, "INSERT INTO fc VALUES(11, 99)"), "19 FOREIGN KEY constraint failed", "a child with no parent is refused"); + eq(q(w, "SELECT count(*) FROM fc WHERE id = 11").rows.get(0)[0], 0L, "and nothing is written"); + eq(exec(w, "DELETE FROM fp WHERE id = 1"), 1L, "deleting the parent: changes 1, not the cascaded rows"); + eq(q(w, "SELECT count(*) FROM fc").rows.get(0)[0], 0L, "removes its children"); + eq(exec(w, "DROP TABLE fc"), 0L, "drop fc"); + eq(exec(w, "DROP TABLE fp"), 0L, "drop fp"); eq(execCode(w, "DELETE FROM t WHERE id = -1", new Object[0], System.currentTimeMillis() - 1), 9, "a deadline already past"); // a read-only connection still refuses a write through execute eq(execCode(r, "INSERT INTO t(id) VALUES(6004)", new Object[0], FAR), 23, "read-only connection: SQLITE_AUTH");