Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ page size). tvOS, watchOS and Linux/Windows native (non-JVM) targets are not off

## Install

<!-- x-release-please-start-version -->
```kotlin
// build.gradle.kts of a Kotlin Multiplatform module
kotlin {
Expand All @@ -71,6 +72,7 @@ kotlin {
}
}
```
<!-- x-release-please-end -->

`androidx.sqlite:sqlite` is an `api` dependency, so `SQLiteDriver` and the connection types are
available without declaring it.
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
4 changes: 4 additions & 0 deletions release-please-config.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
{
"type": "generic",
"path": "gradle.properties"
},
{
"type": "generic",
"path": "README.md"
}
]
}
Expand Down
8 changes: 5 additions & 3 deletions sealite/Module.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ val db = Room.databaseBuilder<AppDatabase>(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() }
}
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,21 +76,36 @@ 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 {
val header = readFileHeader(path, PLAINTEXT_HEADER.size) ?: return CheckResult.Missing
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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>()
Expand Down Expand Up @@ -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<String, List<String>> {
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"))
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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<File>("extractVerified", "natives/fixture_good", "libfixture.so")
println(extracted.path)
}
Original file line number Diff line number Diff line change
@@ -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<File>()

@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")
}
}
Loading