Modern Apps git

← Modern-Apps.git

library/room: ATTACH DATABASE statements escape their SQL literals

Commit
5af5eedde60d1b1795d9a5783156da244412f867
Author
Vayun Mathur <[email protected]>
When
2026-12-01 09:58 UTC (5 days ago)
Parents
9699062
Three ATTACH statements interpolated values raw into SQL:
encryptExistingDatabase's temp path and password, and the
backup codec's output/input paths. An explicit password
containing a quote (any user-derived passphrase, e.g. don't)
terminated the literal early โ€” a syntax error escaping
openRoomDatabase (only SQLiteNotADatabaseException is
caught) and crashing database open on every launch; a
crafted value could break out of the literal entirely
(statements run via sqlite3_exec). Quoted file paths failed
the same way. The keystore-generated Base64 passphrase is
quote-free, which is why the default path never hit this.

All three statements now go through sqlStringLiteral
(single-quote wrapping with quote doubling per SQL rules).
Four host regression tests pin the escaping including the
full statement, plus a device test (plaintext DB -> encrypt
with a quoted password -> reopen, row intact;
compile-verified โ€” no device attached). Cache-by-class,
migration resolution and the import swap rollback were
audited and cleared. Verified: :library:room:
testDebugUnitTest 39 tests pass; compileDebugAndroidTest-
Kotlin passes; lint no issues.

Diff

library/room/src/androidTest/java/com/vayunmathur/library/room/QuotedPasswordDeviceTest.kt
diff --git a/library/room/src/androidTest/java/com/vayunmathur/library/room/QuotedPasswordDeviceTest.kt b/library/room/src/androidTest/java/com/vayunmathur/library/room/QuotedPasswordDeviceTest.ktnew file mode 100644index 0000000000..28e812468c--- /dev/null+++ b/library/room/src/androidTest/java/com/vayunmathur/library/room/QuotedPasswordDeviceTest.kt@@ -0,0 +1,46 @@+package com.vayunmathur.library.room++import android.content.Context+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import java.io.File+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith++/** Regression: a password containing a single quote must encrypt a plaintext DB. */+@RunWith(AndroidJUnit4::class)+class QuotedPasswordDeviceTest {++    private val context: Context get() = InstrumentationRegistry.getInstrumentation().targetContext++    @Test+    fun encryptExistingDatabaseWithQuotedPassword() {+        val name = "device-quoted-pw"+        val file = context.getDatabasePath(name)+        file.delete()+        File("${file.path}-wal").delete()+        File("${file.path}-shm").delete()+        File("${file.path}-journal").delete()+        file.parentFile?.mkdirs()+        val plain = android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(file, null)+        plain.execSQL("CREATE TABLE Note (body TEXT)")+        plain.execSQL("INSERT INTO Note VALUES ('hello')")+        plain.close()++        encryptExistingDatabase(context, name, "don't")++        loadSqlCipher()+        val db = net.zetetic.database.sqlcipher.SQLiteDatabase.openDatabase(+            file.absolutePath, "don't", null,+            net.zetetic.database.sqlcipher.SQLiteDatabase.OPEN_READONLY, null,+        )+        db.rawQuery("SELECT body FROM Note", null).use { cursor ->+            assertTrue(cursor.moveToFirst())+            assertEquals("hello", cursor.getString(0))+        }+        db.close()+        file.delete()+    }+}
library/room/src/main/java/com/vayunmathur/library/room/SqlCipher.kt
diff --git a/library/room/src/main/java/com/vayunmathur/library/room/SqlCipher.kt b/library/room/src/main/java/com/vayunmathur/library/room/SqlCipher.ktindex 40f7c9f173..827fd5aa65 100644--- a/library/room/src/main/java/com/vayunmathur/library/room/SqlCipher.kt+++ b/library/room/src/main/java/com/vayunmathur/library/room/SqlCipher.kt@@ -27,6 +27,9 @@ fun loadSqlCipher() {  private const val TAG = "SqlCipher" +/** Quotes [value] as a SQL string literal: single quotes are doubled, per SQL rules. */+internal fun sqlStringLiteral(value: String): String = "'" + value.replace("'", "''") + "'"+ /**  * Reified convenience wrapper. Prefer obtaining databases through a  * [RoomRepository] subclass rather than calling this directly โ€” a follow-up@@ -200,7 +203,10 @@ fun encryptExistingDatabase(context: Context, dbName: String, password: String)             null         )         db.rawExecSQL("PRAGMA cipher_compatibility = 4")-        db.rawExecSQL("ATTACH DATABASE '${tempFile.absolutePath}' AS encrypted KEY '${password}'")+        db.rawExecSQL(+            "ATTACH DATABASE ${sqlStringLiteral(tempFile.absolutePath)} AS encrypted " ++                "KEY ${sqlStringLiteral(password)}",+        )         db.rawExecSQL("SELECT sqlcipher_export('encrypted')")         db.rawExecSQL("DETACH DATABASE encrypted")         db.close()
library/room/src/main/java/com/vayunmathur/library/room/SqlCipherDbCodec.kt
diff --git a/library/room/src/main/java/com/vayunmathur/library/room/SqlCipherDbCodec.kt b/library/room/src/main/java/com/vayunmathur/library/room/SqlCipherDbCodec.ktindex d56d99776f..3ccc1e2e04 100644--- a/library/room/src/main/java/com/vayunmathur/library/room/SqlCipherDbCodec.kt+++ b/library/room/src/main/java/com/vayunmathur/library/room/SqlCipherDbCodec.kt@@ -47,7 +47,7 @@ object SqlCipherDbCodec : DbBackupCodec {             null         )         db.rawExecSQL("PRAGMA cipher_compatibility = 4")-        db.rawExecSQL("ATTACH DATABASE '$outputPath' AS plaintext KEY ''")+        db.rawExecSQL("ATTACH DATABASE ${sqlStringLiteral(outputPath)} AS plaintext KEY ''")         db.rawExecSQL("SELECT sqlcipher_export('plaintext')")         db.rawExecSQL("DETACH DATABASE plaintext")         db.close()@@ -106,7 +106,9 @@ object SqlCipherDbCodec : DbBackupCodec {         )         try {             db.rawExecSQL("PRAGMA cipher_compatibility = 4")-            db.rawExecSQL("ATTACH DATABASE '${inputFile.canonicalPath}' AS plaintext KEY ''")+            db.rawExecSQL(+                "ATTACH DATABASE ${sqlStringLiteral(inputFile.canonicalPath)} AS plaintext KEY ''",+            )             try {                 db.rawExecSQL("SELECT sqlcipher_export('main', 'plaintext')")             } finally {
library/room/src/test/java/com/vayunmathur/library/room/SqlStringLiteralTest.kt
diff --git a/library/room/src/test/java/com/vayunmathur/library/room/SqlStringLiteralTest.kt b/library/room/src/test/java/com/vayunmathur/library/room/SqlStringLiteralTest.ktnew file mode 100644index 0000000000..5f2ba4a2ab--- /dev/null+++ b/library/room/src/test/java/com/vayunmathur/library/room/SqlStringLiteralTest.kt@@ -0,0 +1,36 @@+package com.vayunmathur.library.room++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class SqlStringLiteralTest {++    @Test+    fun `a plain value is wrapped in single quotes`() {+        assertEquals("'pw'", sqlStringLiteral("pw"))+        assertEquals("''", sqlStringLiteral(""))+    }++    @Test+    fun `single quotes in a password are doubled, not terminated early`() {+        // Regression: encryptExistingDatabase interpolated the password raw,+        // so this input produced ATTACH ... KEY 'don't' (syntax error, and a+        // break-out of the literal under sqlite3_exec).+        assertEquals("'don''t'", sqlStringLiteral("don't"))+        assertEquals("'''x'''", sqlStringLiteral("'x'"))+        assertEquals("'a''b''c'", sqlStringLiteral("a'b'c"))+    }++    @Test+    fun `single quotes in a file path are doubled`() {+        assertEquals("'/data/it''s a.db'", sqlStringLiteral("/data/it's a.db"))+    }++    @Test+    fun `the attach statement for a quoted password stays one literal`() {+        val sql = "ATTACH DATABASE ${sqlStringLiteral("/tmp/x_temp")} AS encrypted " ++            "KEY ${sqlStringLiteral("don't")}"+        assertTrue(sql.endsWith("KEY 'don''t'"), sql)+    }+}