diff --git a/README.md b/README.md index 497c046..0a4e958 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ page size). tvOS, watchOS and Linux/Windows native (non-JVM) targets are not off ## Install + ```kotlin // build.gradle.kts of a Kotlin Multiplatform module kotlin { @@ -71,6 +72,7 @@ kotlin { } } ``` + `androidx.sqlite:sqlite` is an `api` dependency, so `SQLiteDriver` and the connection types are available without declaring it. @@ -238,7 +240,7 @@ SQL that compiles to nothing (empty, whitespace or comments only) is rejected wi ### Maintenance: `Sealite` ```kotlin -Sealite.check(path, key) // Ok | Missing | NotEncrypted | WrongKey, file untouched +Sealite.check(path, key) // Ok | Missing | NotEncrypted | WrongKey Sealite.rekey(path, oldKey, newKey) // change the key in place (close other connections first) Sealite.encryptPlaintext(plain, encrypted, key) // encrypted copy of an unencrypted database Sealite.errorOf(throwable) // SealiteError? from any exception @@ -248,9 +250,11 @@ Sealite.versions // what is linked in, see below Every function has an overload that takes a `SealiteConfig`. `Sealite.check` lets the app branch before Room opens the file. It opens the file read-only and -never writes to it (SQLite may still create a `-shm` file next to a WAL database); an empty file is +does not write to it (SQLite may still create a `-shm` file next to a WAL database); an empty file is `Ok` (a new database), a plaintext header is `NotEncrypted`, and anything the key does not open, -including random bytes, is `WrongKey`. +including random bytes, is `WrongKey`. The one exception: if a crash left an unfinished transaction +in a `-journal` file, SQLite has to roll it back before the database can be read, so `check` does +that first, as the next open by anyone would, and then answers. **`Sealite.rekey`** re-encrypts in place from `oldKey` to `newKey`. It needs the file to itself: close the `RoomDatabase` first. The file is locked exclusively for the whole operation, so a diff --git a/release-please-config.json b/release-please-config.json index 8c747c3..537775d 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -14,6 +14,10 @@ { "type": "generic", "path": "gradle.properties" + }, + { + "type": "generic", + "path": "README.md" } ] } diff --git a/sealite/Module.md b/sealite/Module.md index 1572e02..065f6c3 100644 --- a/sealite/Module.md +++ b/sealite/Module.md @@ -23,7 +23,8 @@ val db = Room.databaseBuilder(name = path) Without Room: ```kotlin -SealiteDriver(SealiteKey.raw(databaseKey)).use { driver -> +val driver = SealiteKey.raw(databaseKey).use { SealiteDriver(it) } // closes the temporary key +driver.use { driver.open(path).use { connection -> connection.prepare("SELECT count(*) FROM sqlite_schema").use { it.step() } } @@ -56,8 +57,9 @@ right key) stay `androidx.sqlite.SQLiteException`. ## Maintenance -- `Sealite.check` tells, without writing, whether a key opens a file: `Ok`, `Missing`, - `NotEncrypted` or `WrongKey`. +- `Sealite.check` tells whether a key opens a file: `Ok`, `Missing`, `NotEncrypted` or `WrongKey`. + It does not write, except to roll back a transaction that a crash left unfinished in a `-journal` + file. - `Sealite.rekey` changes the key in place and needs the file to itself. It is atomic: after a crash the file is entirely under the old or entirely under the new key. Persist the new key as pending before the call, make it current only after the call returned, and on a failure with diff --git a/sealite/src/commonMain/kotlin/io/github/pasichdev/sealite/Sealite.kt b/sealite/src/commonMain/kotlin/io/github/pasichdev/sealite/Sealite.kt index 62e7f78..e4ce31d 100644 --- a/sealite/src/commonMain/kotlin/io/github/pasichdev/sealite/Sealite.kt +++ b/sealite/src/commonMain/kotlin/io/github/pasichdev/sealite/Sealite.kt @@ -76,7 +76,10 @@ public object Sealite { /** * Tells whether [key] opens the database at [path] with [config]. The file is opened - * read-only and never written (SQLite may still create a `-shm` file next to a WAL database). + * read-only and not written (SQLite may still create a `-shm` file next to a WAL database), + * with one exception: when a crash left an unfinished transaction in a `-journal` file, SQLite + * can not read the database before rolling it back, so that happens here, as it would on the + * next open by anyone. The answer is then for the rolled-back file, whichever key was tried. */ @JvmStatic public fun check(path: String, key: SealiteKey, config: SealiteConfig): CheckResult { @@ -84,13 +87,25 @@ public object Sealite { if (header.isEmpty()) return CheckResult.Ok if (header.contentEquals(PLAINTEXT_HEADER)) return CheckResult.NotEncrypted return try { - OpenSequence.openVerified(path, OPEN_READONLY, key, config).close() + openForCheck(path, key, config).close() CheckResult.Ok } catch (e: SealiteException) { wrongKeyOrRethrow(e) } } + /** + * Read-only, unless a crash left a hot journal next to the file: SQLite refuses to read such a + * database through a read-only connection (`SQLITE_READONLY_ROLLBACK`), so it is opened + * read-write, which rolls the unfinished transaction back as the next open by anyone would. + */ + private fun openForCheck(path: String, key: SealiteKey, config: SealiteConfig): RawDb = try { + OpenSequence.openVerified(path, OPEN_READONLY, key, config) + } catch (e: SQLiteException) { + if (!OpenSequence.reports(e.message, SQLITE_READONLY_ROLLBACK)) throw e + OpenSequence.openVerified(path, OPEN_READWRITE, key, config) + } + // Any other error is defensive: a plaintext file is answered above, and a linked SQLite without // encryption or a connection that is not keyed would need a broken build, not a test file. @ExcludeFromCoverage @@ -415,6 +430,7 @@ public object Sealite { private const val RAW_KEY_SIZE = 32 private const val MAX_CAUSE_DEPTH = 16 private const val SQLITE_BUSY = 5 + private const val SQLITE_READONLY_ROLLBACK = 776 // SQLITE_READONLY | (3 << 8) private const val OPEN_READONLY = 0x00000001 private const val OPEN_READWRITE = 0x00000002 private const val OPEN_CREATE = 0x00000004 diff --git a/sealite/src/commonMain/kotlin/io/github/pasichdev/sealite/internal/OpenSequence.kt b/sealite/src/commonMain/kotlin/io/github/pasichdev/sealite/internal/OpenSequence.kt index 691c828..e5f2d9d 100644 --- a/sealite/src/commonMain/kotlin/io/github/pasichdev/sealite/internal/OpenSequence.kt +++ b/sealite/src/commonMain/kotlin/io/github/pasichdev/sealite/internal/OpenSequence.kt @@ -126,6 +126,9 @@ internal object OpenSequence { val match = ERROR_CODE.find(message) ?: return null return match.groupValues[1].toIntOrNull() } + + /** True when [message] reports exactly the result code [code] (extended codes are on). */ + internal fun reports(message: String?, code: Int): Boolean = errorCodeOf(message) == code } internal fun RawDb.exec(sql: String) { diff --git a/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/CheckTest.kt b/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/CheckTest.kt index efbf417..ed1637a 100644 --- a/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/CheckTest.kt +++ b/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/CheckTest.kt @@ -3,11 +3,13 @@ package io.github.pasichdev.sealite +import androidx.sqlite.execSQL import kotlin.random.Random import kotlin.test.AfterTest import kotlin.test.Test import kotlin.test.assertContentEquals import kotlin.test.assertEquals +import kotlin.test.assertNotNull class CheckTest { private val paths = mutableListOf() @@ -60,4 +62,41 @@ class CheckTest { assertEquals(Sealite.CheckResult.Ok, Sealite.check(path, rawKey(1))) assertEquals(Sealite.CheckResult.WrongKey, Sealite.check(path, rawKey(2))) } + + /** + * The files a process killed in the middle of a large write leaves behind: the database with some + * pages already changed, and the journal that undoes them. Returns the path and the committed rows. + */ + private fun crashedInTheMiddleOfAWrite(): Pair> { + val path = newPath() + val image = newPath() + return withDb(path, rawKey(1)) { db -> + db.execSQL("CREATE TABLE t (id INTEGER PRIMARY KEY, body TEXT NOT NULL)") + db.execSQL( + "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 4000) " + + "INSERT INTO t (body) SELECT hex(randomblob(200)) FROM c", + ) + val committed = db.column("SELECT body FROM t ORDER BY id") + // A cache of five pages makes the transaction write its pages to the file before it commits. + db.execSQL("PRAGMA cache_size = 5") + db.execSQL("BEGIN") + db.execSQL("UPDATE t SET body = hex(randomblob(200))") + writeFileBytes(image, assertNotNull(readFileBytes(path))) + writeFileBytes("$image-journal", assertNotNull(readFileBytes("$path-journal"), "no journal")) + db.execSQL("ROLLBACK") + image to committed + } + } + + @Test + fun aDatabaseACrashLeftWithAHotJournalIsAnsweredForBothKeysAndRolledBack() { + val (image, committed) = crashedInTheMiddleOfAWrite() + assertEquals(Sealite.CheckResult.WrongKey, Sealite.check(image, rawKey(2))) + assertEquals(Sealite.CheckResult.Ok, Sealite.check(image, rawKey(1))) + assertEquals(null, readFileBytes("$image-journal"), "the journal was rolled back") + withDb(image, rawKey(1)) { db -> + assertEquals("ok", db.scalar("PRAGMA integrity_check")) + assertEquals(committed, db.column("SELECT body FROM t ORDER BY id")) + } + } } diff --git a/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/OpenSequenceTest.kt b/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/OpenSequenceTest.kt index 1afb2dd..7a4aebd 100644 --- a/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/OpenSequenceTest.kt +++ b/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/OpenSequenceTest.kt @@ -116,4 +116,12 @@ class OpenSequenceTest { assertEquals(null, OpenSequence.errorCodeOf("no code here")) assertEquals(null, OpenSequence.errorCodeOf("Error code: 99999999999")) } + + @Test + fun aMessageReportsExactlyItsOwnCode() { + assertTrue(OpenSequence.reports("Error code: 776, message: attempt to write a readonly database", 776)) + assertFalse(OpenSequence.reports("Error code: 8, message: attempt to write a readonly database", 776)) + assertFalse(OpenSequence.reports("no code here", 776)) + assertFalse(OpenSequence.reports(null, 776)) + } } diff --git a/sealite/src/jvmMain/kotlin/io/github/pasichdev/sealite/internal/NativeLibraryLoader.jvm.kt b/sealite/src/jvmMain/kotlin/io/github/pasichdev/sealite/internal/NativeLibraryLoader.jvm.kt index 81f787b..9467b52 100644 --- a/sealite/src/jvmMain/kotlin/io/github/pasichdev/sealite/internal/NativeLibraryLoader.jvm.kt +++ b/sealite/src/jvmMain/kotlin/io/github/pasichdev/sealite/internal/NativeLibraryLoader.jvm.kt @@ -128,7 +128,7 @@ internal actual object NativeLibraryLoader { } check(expected.matches(Regex("[0-9a-f]{64}"))) { "Malformed checksum file for $libName" } - val dir = privateCacheDir() ?: freshPrivateDir() + val dir = privateCacheDir() ?: freshPrivateDir(libName) val target = File(dir, libName) // A planted symlink must not redirect the hash check or the load. if (Files.isSymbolicLink(target.toPath())) Files.delete(target.toPath()) @@ -210,11 +210,17 @@ internal actual object NativeLibraryLoader { return permissions == PosixFilePermissions.fromString("rwx------") } - /** A new directory only this process and user can use, for when the cache directory is unsafe. */ - private fun freshPrivateDir(): File { - val dir = createPrivateTempDirectory() - dir.toFile().deleteOnExit() - return dir.toFile() + /** + * A new directory only this process and user can use, for when the cache directory is unsafe. + * Nothing else will ever use it, so it is removed with its library when the JVM exits. + */ + private fun freshPrivateDir(libName: String): File { + val dir = createPrivateTempDirectory().toFile() + // Deleted in reverse order of registration: the library first, because a directory is only + // removed once it is empty. + dir.deleteOnExit() + File(dir, libName).deleteOnExit() + return dir } // The Windows branch (no POSIX attributes) can not run on the hosts that measure coverage. diff --git a/sealite/src/jvmTest/kotlin/io/github/pasichdev/sealite/LoaderChildJvm.kt b/sealite/src/jvmTest/kotlin/io/github/pasichdev/sealite/LoaderChildJvm.kt new file mode 100644 index 0000000..c69fdc1 --- /dev/null +++ b/sealite/src/jvmTest/kotlin/io/github/pasichdev/sealite/LoaderChildJvm.kt @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 pasichdev + +package io.github.pasichdev.sealite + +import java.io.File + +/** + * The entry point of the JVM that [LoaderExitTest] starts: extracts the fixture library the way the + * loader does and prints where it went, so the test can look at what is left once this JVM is gone. + */ +fun main() { + val extracted = LoaderReflection.call("extractVerified", "natives/fixture_good", "libfixture.so") + println(extracted.path) +} diff --git a/sealite/src/jvmTest/kotlin/io/github/pasichdev/sealite/LoaderExitTest.kt b/sealite/src/jvmTest/kotlin/io/github/pasichdev/sealite/LoaderExitTest.kt new file mode 100644 index 0000000..5b0a5a3 --- /dev/null +++ b/sealite/src/jvmTest/kotlin/io/github/pasichdev/sealite/LoaderExitTest.kt @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 pasichdev + +package io.github.pasichdev.sealite + +import java.io.File +import java.nio.file.FileSystems +import java.nio.file.Files +import java.util.concurrent.TimeUnit +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** What the loader leaves on disk when its JVM exits; that needs a JVM of its own. */ +class LoaderExitTest { + private val cleanUp = mutableListOf() + + @AfterTest + fun removeTemporaryFiles() { + cleanUp.forEach { it.deleteRecursively() } + cleanUp.clear() + } + + private val posix = FileSystems.getDefault().supportedFileAttributeViews().contains("posix") + + private fun tempDir(prefix: String): File = Files.createTempDirectory(prefix).toFile().canonicalFile.also { + cleanUp += it + } + + @Test + fun theFreshPrivateDirectoryIsRemovedWhenTheJvmExits() { + // Windows keeps a loaded library locked, and reaches the fresh directory only after an I/O error. + if (!posix) return + val temp = tempDir("sealite-tmp") + // A home that is a file: no cache directory can exist under it, so the loader falls back. + val home = File(tempDir("sealite-home"), "home").also { it.writeText("not a directory") } + val java = File(System.getProperty("java.home"), "bin/java").path + val process = + ProcessBuilder( + java, + "-cp", + System.getProperty("java.class.path"), + "-Djava.io.tmpdir=${temp.path}", + "-Duser.home=${home.path}", + "io.github.pasichdev.sealite.LoaderChildJvmKt", + ).redirectErrorStream(true).start() + val output = process.inputStream.bufferedReader().readText() + assertTrue(process.waitFor(2, TimeUnit.MINUTES), "the child JVM did not exit") + assertEquals(0, process.exitValue(), output) + + val extracted = File(output.trim().lines().last()) + assertEquals(temp, extracted.parentFile.parentFile.canonicalFile, output) + assertTrue(extracted.parentFile.name.startsWith("sealite-"), output) + assertEquals(emptyList(), temp.list().orEmpty().toList(), "left in the temporary directory") + } +}