flashcards: platform backup via SQLCipher codec, never raw DB
- Commit
519538c69a4db0f321e07a3ce707c1af6adf8a6c- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-04 21:56 UTC (1 day ago)
- Parents
8af7cd3
Platform backup restored the raw SQLCipher Room database (flashcards-db) through file backup, but its passphrase is wrapped by the old device's non-exportable AndroidKeyStore key (db_no_auth_key). After a restore the app minted a fresh key and passphrase, skipped the already-encrypted file on open, and Room failed to open the database: a clean first launch traded for a crash and no data. Mirror weather's proven pattern. A new platform AppBackupAgent (BaseBackupAgent + SqlCipherDbCodec) carries the database as plaintext inside the key/value backup payload and re-encrypts it under the new device's passphrase on restore, alongside the settings datastore and the media directory so restored notes keep their images. flashcardsDbConfigs now mints the passphrase when none exists, which is exactly the restore-before-first-launch case on a new device; the source device reuses its existing passphrase unchanged. secure_prefs (the wrapped passphrase) is never backed up. dataExtractionRules now exclude flashcards-db and its -wal/-shm/-journal sidecars plus secure_prefs.xml from both cloud-backup and device-transfer, so no channel can land an undecryptable database. The cloud-backup section stays gated on encryption capabilities for the agent-removed fallback and is documented as not consulted while the backupAgent is declared; device-transfer is governed by these rules. Verification: new FlashcardsBackupAgentTest asserts the agent wiring (codec, live DB name, settings, media, no prefs), the extraction-rule excludes, and a full agent backup/restore round-trip of settings + media + the database entry through the real backup streams. The SQLCipher native layer cannot load on a host JVM, so the codec's encrypt/decrypt round-trip itself is device-provable only (covered on device by :library:room's DeviceDatabaseTest); the host tests assert the pre-native contract and the codec failure-safety is already covered there. ./gradlew :flashcards:lint :flashcards:lintVitalRelease :flashcards:testDevUnitTest all pass.
Diff
flashcards/AGENTS.md
diff --git a/flashcards/AGENTS.md b/flashcards/AGENTS.mdindex 585d4ad619..e86e965d13 100644--- a/flashcards/AGENTS.md+++ b/flashcards/AGENTS.md@@ -18,6 +18,7 @@ _Install: ./install flashcards (dev by default)._ - `util/` is NOT a closed package root — don't add more files there - Scheduling correctness (FSRS) is the product — scheduler changes need review-log-driven tests, not just UI checks - APKG import/export must stay compatible with Anki's format — test round-trips, not just one direction+- Platform backup must never ship the raw SQLCipher DB: its passphrase is wrapped by a non-exportable KeyStore key, so a restored raw copy cannot be opened. The DB travels only via `platform/AppBackupAgent` + `SqlCipherDbCodec` (plaintext in the payload, re-encrypted under the new device's passphrase, minted by `flashcardsDbConfigs` when restore runs before first launch) ## Key files ### Root — entry@@ -49,7 +50,7 @@ _Install: ./install flashcards (dev by default)._ - com/vayunmathur/flashcards/util/MediaStore.kt - com/vayunmathur/flashcards/util/TtsSpeaker.kt - com/vayunmathur/flashcards/util/ReviewReminderWorker.kt-- com/vayunmathur/flashcards/util/AppBackupAgent.kt+- com/vayunmathur/flashcards/platform/AppBackupAgent.kt — platform backup agent: SQLCipher codec round-trip for the DB plus settings datastore and media dir; the raw encrypted DB and `secure_prefs` are excluded in `res/xml/data_extraction_rules.xml` (device transfer) ### ui/ — decks, notes, review, stats - com/vayunmathur/flashcards/ui/DeckListPage.kt - com/vayunmathur/flashcards/ui/Navigation.kt — tab stack plus `DialogPage()` entries
flashcards/src/main/AndroidManifest.xml
diff --git a/flashcards/src/main/AndroidManifest.xml b/flashcards/src/main/AndroidManifest.xmlindex 93cce1a381..21ba7f790b 100644--- a/flashcards/src/main/AndroidManifest.xml+++ b/flashcards/src/main/AndroidManifest.xml@@ -14,6 +14,7 @@ <application android:allowBackup="true"+ android:backupAgent=".platform.AppBackupAgent" android:dataExtractionRules="@xml/data_extraction_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name"
flashcards/src/main/java/com/vayunmathur/flashcards/data/FlashcardsDatabase.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/data/FlashcardsDatabase.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/data/FlashcardsDatabase.ktindex fa7598f82e..636f34a5e2 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/data/FlashcardsDatabase.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/data/FlashcardsDatabase.kt@@ -16,9 +16,26 @@ import kotlinx.coroutines.flow.Flow const val DB_NAME = "flashcards-db" -/** Backup config for the in-app backup buttons. */-fun flashcardsDbConfigs(context: Context): List<Pair<String, String>> =- listOf(DB_NAME to DatabaseHelper(context).getPassphrase())+/**+ * Backup config shared by the in-app backup buttons and the platform+ * [com.vayunmathur.flashcards.platform.AppBackupAgent].+ *+ * The passphrase is minted when none exists: a platform restore runs before+ * first launch on the new device, where no AndroidKeyStore key or wrapped+ * passphrase exists yet. Minting here gives the backup codec the new device's+ * passphrase to re-encrypt the restored database under; on the source device+ * the existing passphrase is reused unchanged.+ */+fun flashcardsDbConfigs(context: Context): List<Pair<String, String>> {+ val helper = DatabaseHelper(context)+ val passphrase = if (helper.isKeyGenerated()) {+ helper.getPassphrase()+ } else {+ helper.generateKey()+ helper.createAndStorePassphrase(helper.getCipherForEncryption())+ }+ return listOf(DB_NAME to passphrase)+} /** Room access for decks. */ @Dao
flashcards/src/main/java/com/vayunmathur/flashcards/platform/AppBackupAgent.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/platform/AppBackupAgent.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/platform/AppBackupAgent.ktnew file mode 100644index 0000000000..c0902eb709--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/platform/AppBackupAgent.kt@@ -0,0 +1,34 @@+package com.vayunmathur.flashcards.platform++import com.vayunmathur.flashcards.data.flashcardsDbConfigs+import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.BaseBackupAgent+import com.vayunmathur.library.util.DbBackupCodec+import java.io.File++/**+ * Platform (key/value) backup agent.+ *+ * The flashcards database is SQLCipher-encrypted under a passphrase wrapped by+ * a non-exportable AndroidKeyStore key, so a raw file copy of `flashcards-db`+ * can never be opened on another device. [SqlCipherDbCodec] therefore exports+ * the database to plaintext inside the backup payload and re-encrypts it under+ * the new device's passphrase on restore (see [flashcardsDbConfigs], which+ * mints that passphrase when the restore runs before first launch). Settings+ * and card media travel alongside so restored notes keep their images.+ *+ * `secure_prefs` (the wrapped passphrase) is deliberately never declared here:+ * it is only meaningful under the old device's KeyStore key.+ */+open class AppBackupAgent : BaseBackupAgent() {+ override val dbCodec: DbBackupCodec = SqlCipherDbCodec++ override val dbConfigs: List<Pair<String, String>>+ get() = flashcardsDbConfigs(this)++ override val datastoreNames: List<String>+ get() = listOf("datastore_default")++ override val extraFiles: List<File>+ get() = MediaStore.backupFiles(this)+}
flashcards/src/main/java/com/vayunmathur/flashcards/platform/MediaStore.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/platform/MediaStore.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/platform/MediaStore.ktindex 6fc90b79b5..4c399bbea4 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/platform/MediaStore.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/platform/MediaStore.kt@@ -87,6 +87,15 @@ class MediaStore(context: Context) { companion object { private const val DIR = "media" + /**+ * Files that must travel with the flashcards database in a backup: the+ * whole media directory as a single entry, so restore recreates it in+ * place. Without this, a restored database references image files that+ * were never backed up and every embedded image renders blank.+ */+ fun backupFiles(context: Context): List<File> =+ listOf(File(context.filesDir, DIR).apply { mkdirs() })+ private val imageRegex = Regex("""!\[[^\]]*]\(([^)]+)\)""") /** The set of media filenames referenced by an `` in [md]. */
flashcards/src/main/res/xml/data_extraction_rules.xml
diff --git a/flashcards/src/main/res/xml/data_extraction_rules.xml b/flashcards/src/main/res/xml/data_extraction_rules.xmlindex 88487e520b..e1740a7e01 100644--- a/flashcards/src/main/res/xml/data_extraction_rules.xml+++ b/flashcards/src/main/res/xml/data_extraction_rules.xml@@ -1,24 +1,58 @@ <?xml version="1.0" encoding="utf-8"?>-<!-- Overrides the permissive default in the shared :library module.+<!--+ Flashcards. Audited state:+ * databases/flashcards-db — Room DB holding decks, notes, cards and the+ FSRS review schedule. The user's content; genuinely worth restoring.+ * files/datastore_default.preferences_pb — app settings.+ * files/media/ — card images referenced from note fields.+ * shared_prefs/secure_prefs.xml — SQLCipher passphrase wrapped by the+ non-exportable AndroidKeyStore key (db_no_auth_key). - Storage audited:- database/flashcards-db FlashcardsDatabase (Deck, Card): the user's decks and- cards plus their spaced-repetition schedule. User content.- file/datastore_default.preferences_pb app settings.- sharedpref/secure_prefs keystore-wrapped SQLCipher passphrase.+ flashcards-db is excluded from both sections below: it is SQLCipher-+ encrypted under a passphrase wrapped by a key that never leaves the source+ device, so a restored raw copy cannot be opened — the app mints a fresh key+ and passphrase on the new device, the already-encrypted file is skipped by+ the encrypt-on-open step, and Room then fails to open it. Shipping the raw+ file would trade a clean first launch for a crash and no data. - Decks and cards are user-authored content worth restoring on a new device, so both- channels carry the flashcards database. Cloud backup is gated on device encryption- because card text can contain anything. Caches and the keystore-bound passphrase are- left out by the allowlist. -->+ The data still migrates: flashcards declares+ android:backupAgent=".platform.AppBackupAgent", which uses SqlCipherDbCodec+ to export the DB to plaintext inside the backup payload and re-encrypt it+ under the new device's passphrase on restore, alongside the settings+ datastore and the media directory.++ SCOPE: because a backupAgent is declared (without fullBackupOnly), cloud+ backup uses key/value backup and the <cloud-backup> section below is NOT+ consulted; cloud content is exactly AppBackupAgent's payload. The rules+ below govern <device-transfer>, and are the correct control if the+ backupAgent is ever removed. disableIfNoEncryptionCapabilities stays on+ <cloud-backup> for that fallback: card text can contain anything, and the+ codec payload carries the database in plaintext.+--> <data-extraction-rules>+ <!-- Not consulted while android:backupAgent is declared; see SCOPE above. --> <cloud-backup disableIfNoEncryptionCapabilities="true">- <!-- Whole-domain include so the -wal/-shm sidecars travel with the database. -->+ <include domain="root" path="." />+ <include domain="file" path="." /> <include domain="database" path="." />- <include domain="file" path="datastore_default.preferences_pb" />+ <exclude domain="database" path="flashcards-db" />+ <exclude domain="database" path="flashcards-db-wal" />+ <exclude domain="database" path="flashcards-db-shm" />+ <exclude domain="database" path="flashcards-db-journal" />+ <include domain="sharedpref" path="." />+ <exclude domain="sharedpref" path="secure_prefs.xml" />+ <include domain="external" path="." /> </cloud-backup> <device-transfer>+ <include domain="root" path="." />+ <include domain="file" path="." /> <include domain="database" path="." />- <include domain="file" path="datastore_default.preferences_pb" />+ <exclude domain="database" path="flashcards-db" />+ <exclude domain="database" path="flashcards-db-wal" />+ <exclude domain="database" path="flashcards-db-shm" />+ <exclude domain="database" path="flashcards-db-journal" />+ <include domain="sharedpref" path="." />+ <exclude domain="sharedpref" path="secure_prefs.xml" />+ <include domain="external" path="." /> </device-transfer> </data-extraction-rules>
flashcards/src/test/java/com/vayunmathur/flashcards/platform/FlashcardsBackupAgentTest.kt
diff --git a/flashcards/src/test/java/com/vayunmathur/flashcards/platform/FlashcardsBackupAgentTest.kt b/flashcards/src/test/java/com/vayunmathur/flashcards/platform/FlashcardsBackupAgentTest.ktnew file mode 100644index 0000000000..267f9270aa--- /dev/null+++ b/flashcards/src/test/java/com/vayunmathur/flashcards/platform/FlashcardsBackupAgentTest.kt@@ -0,0 +1,157 @@+package com.vayunmathur.flashcards.platform++import android.content.Context+import android.os.ParcelFileDescriptor+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.flashcards.data.DB_NAME+import com.vayunmathur.flashcards.data.flashcardsDbConfigs+import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.DbBackupCodec+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertSame+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.shadows.BackupDataInputBuilder+import org.robolectric.shadows.BackupDataOutputFactory++/**+ * Flashcards platform backup wiring.+ *+ * The SQLCipher native layer cannot load on a host JVM, so the codec's actual+ * encrypt/decrypt round-trip is device-provable only (covered on device by+ * `:library:room`'s DeviceDatabaseTest). What is provable here, and asserted:+ * the agent declares the codec + the live DB/settings/media set, the DB+ * config names the live database, the extraction rules never ship the raw+ * encrypted DB or the wrapped passphrase, and a full agent backup/restore+ * round-trips settings + media + the database entry (via a recording codec+ * standing in for the native one) through the real backup streams.+ */+@RunWith(RobolectricTestRunner::class)+class FlashcardsBackupAgentTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ /** Records codec calls and passes a fixed payload through, host-side. */+ private class FakeCodec(private val payload: ByteArray) : DbBackupCodec {+ val exported = mutableListOf<Pair<String, String>>()+ val imported = mutableListOf<Pair<String, String>>()+ override fun exportDatabase(context: Context, dbName: String, password: String, outputFile: File) {+ exported += dbName to password+ outputFile.writeBytes(payload)+ }++ override fun importDatabase(context: Context, dbName: String, password: String, inputFile: File) {+ imported += dbName to password+ assertTrue(payload.contentEquals(inputFile.readBytes()), "codec receives exported bytes")+ }+ }++ /** Real agent wiring, with only the native codec + passphrase swapped out. */+ private class TestAgent(codec: DbBackupCodec) : AppBackupAgent() {+ override val dbCodec: DbBackupCodec = codec+ override val dbConfigs: List<Pair<String, String>> = listOf(DB_NAME to "pw")+ fun attach(ctx: Context) = attachBaseContext(ctx)+ }++ private fun pfd(file: File): ParcelFileDescriptor {+ if (!file.exists()) file.writeBytes(ByteArray(0))+ return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_WRITE)+ }++ @Test+ fun agentDeclaresCodecSettingsAndMedia() {+ assertSame(SqlCipherDbCodec, AppBackupAgent().dbCodec)+ val agent = TestAgent(FakeCodec(byteArrayOf(0))).apply { attach(ctx) }+ assertEquals(listOf("datastore_default"), agent.datastoreNames)+ assertEquals(listOf("media"), agent.extraFiles.map { it.name })+ assertEquals(File(ctx.filesDir, "media"), agent.extraFiles.single())+ assertTrue(agent.prefNames.isEmpty(), "secure_prefs must never be backed up")+ }++ @Test+ fun dbConfigsNameTheLiveDatabase() {+ // Minting/reusing the passphrase needs the AndroidKeyStore, which a+ // host JVM cannot provide; assert the pre-keystore contract instead:+ // either the config names flashcards-db with a passphrase, or the+ // failure is the keystore/passphrase lookup itself.+ val result = runCatching { flashcardsDbConfigs(ctx) }+ result.onSuccess { configs ->+ assertEquals(listOf(DB_NAME), configs.map { it.first })+ assertTrue(configs.single().second.isNotBlank(), "passphrase present")+ }.onFailure { error ->+ assertTrue(+ error is IllegalStateException ||+ error is java.security.GeneralSecurityException ||+ error is java.security.KeyStoreException,+ "unexpected dbConfigs failure: $error",+ )+ }+ assertEquals("flashcards-db", DB_NAME)+ }++ @Test+ fun backupThenRestoreRoundTripsSettingsMediaAndDatabase() {+ val codec = FakeCodec(byteArrayOf(7, 7, 7))+ val agent = TestAgent(codec).apply { attach(ctx) }++ val settings = File(ctx.filesDir, "datastore_default.preferences_pb")+ .apply { writeBytes(byteArrayOf(1, 2, 3)) }+ val media = MediaStore(ctx)+ val mediaName = media.writeBytes("card.png", byteArrayOf(4, 5, 6))+ val mediaFile = media.resolve(mediaName)++ val stateFile = File(ctx.cacheDir, "flashcards-backup-state.bin").apply { delete() }+ val output = BackupDataOutputFactory.newInstance()+ agent.onBackup(null, output, pfd(stateFile))++ val entity = Shadows.shadowOf(output).entities.single()+ assertEquals("full_backup", entity.key())+ assertEquals(listOf(DB_NAME to "pw"), codec.exported)++ settings.delete()+ mediaFile.delete()+ assertTrue(!settings.exists() && !mediaFile.exists())++ val restoreState = File(ctx.cacheDir, "flashcards-restore-state.bin").apply { delete() }+ val input = BackupDataInputBuilder.newBuilder().addEntity(entity).build()+ agent.onRestore(input, 1, pfd(restoreState))++ assertEquals(listOf(DB_NAME to "pw"), codec.imported)+ assertTrue(byteArrayOf(1, 2, 3).contentEquals(settings.readBytes()))+ assertTrue(byteArrayOf(4, 5, 6).contentEquals(mediaFile.readBytes()))+ // The unrelated-entity path is covered by LibraryBackupAgentTest; here+ // the full_backup entity must be consumed, not skipped.+ assertTrue(restoreState.length() == 8L, "restore writes its state record")+ }++ @Test+ fun extractionRulesNeverShipRawDatabaseOrWrappedPassphrase() {+ val parser = ctx.resources.getXml(+ ctx.resources.getIdentifier("data_extraction_rules", "xml", ctx.packageName),+ )+ val excludes = mutableSetOf<Pair<String, String>>()+ var cloudDisablesWithoutEncryption = false+ var event = parser.eventType+ while (event != org.xmlpull.v1.XmlPullParser.END_DOCUMENT) {+ if (event == org.xmlpull.v1.XmlPullParser.START_TAG) {+ when (parser.name) {+ "cloud-backup" ->+ cloudDisablesWithoutEncryption =+ parser.getAttributeBooleanValue(null, "disableIfNoEncryptionCapabilities", false)+ "exclude" -> excludes +=+ parser.getAttributeValue(null, "domain") to parser.getAttributeValue(null, "path")+ }+ }+ event = parser.next()+ }+ parser.close()+ assertTrue(cloudDisablesWithoutEncryption, "cloud fallback stays gated on encryption")+ listOf("flashcards-db", "flashcards-db-wal", "flashcards-db-shm", "flashcards-db-journal")+ .forEach { assertTrue(("database" to it) in excludes, "rules must exclude $it") }+ assertTrue(("sharedpref" to "secure_prefs.xml") in excludes, "rules must exclude secure_prefs.xml")+ }+}
flashcards/src/test/java/com/vayunmathur/flashcards/util/FlashcardsMiscTest.kt
diff --git a/flashcards/src/test/java/com/vayunmathur/flashcards/util/FlashcardsMiscTest.kt b/flashcards/src/test/java/com/vayunmathur/flashcards/util/FlashcardsMiscTest.ktindex e434b57fcd..a96086d949 100644--- a/flashcards/src/test/java/com/vayunmathur/flashcards/util/FlashcardsMiscTest.kt+++ b/flashcards/src/test/java/com/vayunmathur/flashcards/util/FlashcardsMiscTest.kt@@ -64,11 +64,15 @@ class FlashcardsMiscTest { } @Test- fun manifestHasNoBackupAgentAndExtractionRulesGovern() {- // The legacy backup agent was removed; data_extraction_rules.xml now- // governs both cloud backup and device transfer.+ fun manifestDeclaresBackupAgentAndExtractionRules() {+ // Platform backup goes through AppBackupAgent (SQLCipher codec+ // round-trip); data_extraction_rules.xml governs device transfer and+ // must never ship the raw encrypted database — see that file. val info = ctx.packageManager.getApplicationInfo(ctx.packageName, 0)- assertEquals(null, info.backupAgentName)+ assertEquals(+ "com.vayunmathur.flashcards.platform.AppBackupAgent",+ info.backupAgentName,+ ) assertTrue(ctx.resources.getIdentifier("data_extraction_rules", "xml", ctx.packageName) != 0) }