Modern Apps git

← Modern-Apps.git

notes: make platform backup restorable on a new device

Commit
8f0a4f9b2bd1c4e1544d8a2ec406f36ba60ab887
Author
Vayun Mathur <[email protected]>
When
2026-12-04 21:57 UTC (1 day ago)
Parents
519538c
Notes declared allowBackup with dataExtractionRules that included the whole database domain on both cloud backup and device transfer, and excluded only the keystore-wrapped passphrase by omission. The notes database is SQLCipher ciphertext under a passphrase wrapped by the old device's non-exportable AndroidKeyStore key (db_no_auth_key), so a platform restore delivered a database file the new device can never open: Room fails on first launch instead of starting cleanly, and the user's notes are lost either way.

Fix, following the proven weather pattern in this repo: declare a key/value backup agent (platform/AppBackupAgent, a BaseBackupAgent subclass) that exports notes-db to plaintext inside the backup payload via SqlCipherDbCodec and re-encrypts it under the new device's passphrase on restore. The agent mints that passphrase on a restore target that has no key yet, exactly as the database builder does on first open, and it also carries datastore_default (app settings) and the note_images directory that restored notes reference. Rewrite data_extraction_rules.xml so both channels exclude the raw notes-db and legacy passwords-db files (with -wal/-shm/-journal sidecars) and secure_prefs.xml, while file-copy still carries note_images, settings and the watch store on device transfer; the cloud section documents that it is not consulted while the backup agent is declared and stays safe if the agent is ever removed. No database version or migration changes: the codec deliberately does not run migrations, and Room applies the existing 1->4 chain on first open as before.

Update notes/AGENTS.md for the new agent and the MainActivityTest manifest assertion that pinned the old no-agent shape.

Verified: ./gradlew :notes:lint :notes:lintVitalRelease :notes:testDevUnitTest green (263 tests, including 4 new AppBackupAgentTest tests). The new Robolectric suite runs the real agent onBackup -> onRestore through Robolectric's backup-data streams and round-trips settings and note images byte-for-byte, asserts the codec/dbConfigs/datastore/extraFiles wiring, asserts restore drops no notes-db file (the clean-start guarantee), and parses the manifest plus merged extraction rules to prove both channels exclude the raw databases and secure_prefs. SQLCipher's native library cannot load on a host JVM, so the native plaintext export/import itself remains device-provable (covered on device by :library:room's codec tests); the agent test documents that limit. ktlintCheck failures in notes are pre-existing in files this change does not touch (e.g. data/Note.kt, data/NoteBlock.kt, the androidTest source set).

Diff

notes/AGENTS.md
diff --git a/notes/AGENTS.md b/notes/AGENTS.mdindex 6af2637966..1062db2baa 100644--- a/notes/AGENTS.md+++ b/notes/AGENTS.md@@ -15,7 +15,7 @@ _Install: ./install notes (dev by default)._ **Key features:** - Block-based editor (`Note`/`NoteBlock`) with stylus ink (`:library:ink`) and images (`:library:image`, content-addressed `sha256.jpg`) - `.md` import/export — opens files shared from other apps, desktop file-drop, shares notes back out-- OpenAssistant read/add via `intents/`; local backup/restore via the in-app backup buttons (`BackupButtons`, no backup agent)+- OpenAssistant read/add via `intents/`; local backup/restore via the in-app backup buttons (`BackupButtons`); platform backup via `platform/AppBackupAgent` (key/value `BaseBackupAgent` + `SqlCipherDbCodec`: the DB is exported to plaintext in the backup payload and re-encrypted under the new device's passphrase on restore; `data_extraction_rules.xml` excludes the raw `notes-db`/`passwords-db` files and `secure_prefs` from file copy on both channels, and carries `note_images`/settings/watch store by device transfer) **Architecture / data-flow:** `ui/` Compose list/detail → `platform/NotesViewModel` (+ `NotesUiContract`) → `data/NotesRepository` singleton over Room (`Note`/`NoteBlock`/`NoteDatabase`). `MainActivity.onCreateBeforeContent`: repo init → one-time legacy-notes clear + image `img_<uuid>.jpg → sha256.jpg` migration with block-reference rewrite → `ready` gate before `Navigation`. **Entry points + reading order:** `Route` (`NotesList` / `Note(id)` / `ExternalNote(uri)`) → `MainActivity.kt` → `Navigation.kt` → `platform/NotesViewModel.kt` → `data/NotesRepository.kt`. @@ -67,6 +67,7 @@ routing, so every entry point is inert on the wrong form factor. - com/vayunmathur/notes/domain/NoteTags.kt — tag normalisation, rename/merge, counts, suggestions - com/vayunmathur/notes/domain/NoteOrder.kt — strict reorder positions (respaces tied positions so a drag persists) ### platform/ — ViewModel, contract, stores, export+- com/vayunmathur/notes/platform/AppBackupAgent.kt — platform backup agent (DB via `SqlCipherDbCodec`, `datastore_default`, `note_images`) - com/vayunmathur/notes/platform/NotesViewModel.kt - com/vayunmathur/notes/platform/NotesUiContract.kt - com/vayunmathur/notes/platform/NoteImageStore.kt — content-addressed image copy + migration
notes/src/main/AndroidManifest.xml
diff --git a/notes/src/main/AndroidManifest.xml b/notes/src/main/AndroidManifest.xmlindex 39bce04945..cb3a323ada 100644--- a/notes/src/main/AndroidManifest.xml+++ b/notes/src/main/AndroidManifest.xml@@ -42,6 +42,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"
notes/src/main/java/com/vayunmathur/notes/platform/AppBackupAgent.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/platform/AppBackupAgent.kt b/notes/src/main/java/com/vayunmathur/notes/platform/AppBackupAgent.ktnew file mode 100644index 0000000000..bc80706ef0--- /dev/null+++ b/notes/src/main/java/com/vayunmathur/notes/platform/AppBackupAgent.kt@@ -0,0 +1,46 @@+package com.vayunmathur.notes.platform++import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.BaseBackupAgent+import com.vayunmathur.library.util.DatabaseHelper+import com.vayunmathur.notes.data.DB_NAME+import java.io.File++/**+ * Platform backup agent for Notes.+ *+ * The notes database is SQLCipher-encrypted under a passphrase wrapped by a+ * non-exportable AndroidKeyStore key, so the raw database file must never+ * travel by file copy (see res/xml/data_extraction_rules.xml). This agent is+ * the path that carries it instead: [SqlCipherDbCodec] exports the database+ * to plaintext inside the key/value backup payload on the old device and+ * re-encrypts it under the new device's passphrase on restore.+ */+class AppBackupAgent : BaseBackupAgent() {+    override val dbCodec = SqlCipherDbCodec++    override val dbConfigs: List<Pair<String, String>>+        get() {+            // On a restore target no key exists yet: mint the passphrase the+            // same way the database builder does on first open, so the codec+            // can re-encrypt under it and the first real open decrypts with+            // that same passphrase. On the backup source the existing+            // passphrase is returned unchanged.+            val helper = DatabaseHelper(this)+            val passphrase =+                if (helper.isKeyGenerated()) {+                    helper.getPassphrase()+                } else {+                    helper.generateKey()+                    helper.createAndStorePassphrase(helper.getCipherForEncryption())+                }+            return listOf(DB_NAME to passphrase)+        }++    // The shared DataStore file holding app settings.+    override val datastoreNames: List<String> get() = listOf("datastore_default")++    // Images referenced by note blocks; without them a restored database+    // renders every embedded image blank.+    override val extraFiles: List<File> get() = NoteImageStore.backupFiles(this)+}
notes/src/main/res/xml/data_extraction_rules.xml
diff --git a/notes/src/main/res/xml/data_extraction_rules.xml b/notes/src/main/res/xml/data_extraction_rules.xmlindex cd33c503d5..69f3e897c2 100644--- a/notes/src/main/res/xml/data_extraction_rules.xml+++ b/notes/src/main/res/xml/data_extraction_rules.xml@@ -1,28 +1,69 @@ <?xml version="1.0" encoding="utf-8"?>-<!-- Overrides the permissive default in the shared :library module.+<!--+  Notes. Audited state:+    * databases/notes-db — Room DB holding the user's notes. SQLCipher-encrypted+      under a passphrase wrapped by a non-exportable AndroidKeyStore key+      (secure_prefs / db_no_auth_key), so a file copy of it can never be opened+      on another device. databases/passwords-db is the same story: it is the+      legacy name the app reads once and deletes in MainActivity.+    * files/note_images/ — content-addressed images embedded in notes.+    * files/datastore_default.preferences_pb — app settings.+    * files/wear-notes-snapshot.json + wear-notes-pending.json — the watch+      experience's local store (derived snapshot + unreflected watch ops).+    * shared_prefs/secure_prefs.xml — the keystore-wrapped DB passphrase. -     Storage audited:-       database/notes-db      NoteDatabase (Note): the user's note content. Also the-                              legacy passwords-db, deleted after migration in MainActivity.-       file/note_images       images embedded in notes (NoteImageStore). User content.-       file/datastore_default.preferences_pb  app settings.-       cache/shared_notes     markdown export scratch; Android never backs up cacheDir.-       sharedpref/secure_prefs  keystore-wrapped SQLCipher passphrase.+  Both databases and secure_prefs are excluded from both sections: the+  wrapping key never leaves the old device, so a restored copy is ciphertext+  the new device cannot open and Room fails on first launch instead of+  starting cleanly. -     Notes are user-authored content worth restoring on a new device, so both channels-     carry the notes database and its images. Cloud backup is gated on device encryption-     because note text can contain anything. Caches and the keystore-bound passphrase are-     left out by the allowlist. -->+  The notes still migrate: notes declares its own BackupAgent+  (platform/AppBackupAgent), which uses SqlCipherDbCodec to export the DB to+  plaintext inside the key/value backup payload and re-encrypt it under the+  new device's passphrase on restore. That path also carries+  datastore_default and note_images. The rules below govern device transfer+  (where note_images, settings and the watch store travel by file copy and+  the databases deliberately do not), and are the correct control if the+  backupAgent is ever removed.++  SCOPE: notes declares android:backupAgent=".platform.AppBackupAgent" and+  does NOT set android:fullBackupOnly, so Android uses key/value backup here+  and the <cloud-backup> section below is NOT consulted. Cloud content is+  exactly AppBackupAgent's payload: notes-db exported to plaintext by+  SqlCipherDbCodec, datastore_default, and note_images.+--> <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="note_images" />-        <include domain="file" path="datastore_default.preferences_pb" />+        <exclude domain="database" path="notes-db" />+        <exclude domain="database" path="notes-db-wal" />+        <exclude domain="database" path="notes-db-shm" />+        <exclude domain="database" path="notes-db-journal" />+        <exclude domain="database" path="passwords-db" />+        <exclude domain="database" path="passwords-db-wal" />+        <exclude domain="database" path="passwords-db-shm" />+        <exclude domain="database" path="passwords-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="note_images" />-        <include domain="file" path="datastore_default.preferences_pb" />+        <exclude domain="database" path="notes-db" />+        <exclude domain="database" path="notes-db-wal" />+        <exclude domain="database" path="notes-db-shm" />+        <exclude domain="database" path="notes-db-journal" />+        <exclude domain="database" path="passwords-db" />+        <exclude domain="database" path="passwords-db-wal" />+        <exclude domain="database" path="passwords-db-shm" />+        <exclude domain="database" path="passwords-db-journal" />+        <include domain="sharedpref" path="." />+        <exclude domain="sharedpref" path="secure_prefs.xml" />+        <include domain="external" path="." />     </device-transfer> </data-extraction-rules>
notes/src/test/java/com/vayunmathur/notes/MainActivityTest.kt
diff --git a/notes/src/test/java/com/vayunmathur/notes/MainActivityTest.kt b/notes/src/test/java/com/vayunmathur/notes/MainActivityTest.ktindex c8fa64450b..8e36da3833 100644--- a/notes/src/test/java/com/vayunmathur/notes/MainActivityTest.kt+++ b/notes/src/test/java/com/vayunmathur/notes/MainActivityTest.kt@@ -39,11 +39,12 @@ class MainActivityTest {         controller.pause().stop().destroy()     } -    @Test fun manifestHasNoBackupAgentAndExtractionRulesGovern() {-        // The legacy backup agent was removed; data_extraction_rules.xml now-        // governs both cloud backup and device transfer.+    @Test fun manifestDeclaresBackupAgentAndExtractionRules() {+        // Platform backup goes through the codec backup agent (key/value);+        // data_extraction_rules.xml governs device transfer and excludes the+        // raw encrypted databases from file copy.         val info = app.packageManager.getApplicationInfo(app.packageName, 0)-        assertEquals(null, info.backupAgentName)+        assertEquals("com.vayunmathur.notes.platform.AppBackupAgent", info.backupAgentName)         assertTrue(app.resources.getIdentifier("data_extraction_rules", "xml", app.packageName) != 0)     } 
notes/src/test/java/com/vayunmathur/notes/platform/AppBackupAgentTest.kt
diff --git a/notes/src/test/java/com/vayunmathur/notes/platform/AppBackupAgentTest.kt b/notes/src/test/java/com/vayunmathur/notes/platform/AppBackupAgentTest.ktnew file mode 100644index 0000000000..ebe2f372ef--- /dev/null+++ b/notes/src/test/java/com/vayunmathur/notes/platform/AppBackupAgentTest.kt@@ -0,0 +1,193 @@+package com.vayunmathur.notes.platform++import android.content.Context+import android.content.ContextWrapper+import android.content.pm.ApplicationInfo+import android.content.res.XmlResourceParser+import android.os.ParcelFileDescriptor+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.DatabaseHelper+import com.vayunmathur.notes.data.DB_NAME+import com.vayunmathur.testsupport.FakeAndroidKeyStore+import java.io.ByteArrayInputStream+import java.io.File+import java.util.zip.ZipInputStream+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+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++/**+ * Platform backup for Notes' real manifest agent ([AppBackupAgent]).+ *+ * Host limit: SQLCipher's native library cannot load on a JVM, so with no+ * live notes-db file present the codec exports nothing and this suite proves+ * the round-trip for everything around it (settings + note images through+ * the real agent's onBackup -> onRestore, DB codec/config wiring, manifest+ * and extraction-rules shape, and the clean-start guarantee that restore+ * drops no undecryptable database file). The native export/import itself is+ * device-provable (see :library:room's on-device codec tests).+ */+@RunWith(RobolectricTestRunner::class)+class AppBackupAgentTest {+    companion object {+        @org.junit.BeforeClass+        @JvmStatic+        fun installKeyStore() = FakeAndroidKeyStore.install()+    }++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    private fun attachedAgent(): AppBackupAgent {+        val agent = AppBackupAgent()+        val attach = ContextWrapper::class.java+            .getDeclaredMethod("attachBaseContext", Context::class.java)+        attach.isAccessible = true+        attach.invoke(agent, ctx)+        return agent+    }++    private fun pfd(file: File): ParcelFileDescriptor {+        if (!file.exists()) file.writeBytes(ByteArray(0))+        return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_WRITE)+    }++    @Test+    fun agentDeclaresSqlCipherCodecForNotesDb() {+        DatabaseHelper(ctx).storePassphrase("notes-backup-test-passphrase")+        val agent = attachedAgent()+        assertEquals(SqlCipherDbCodec, agent.dbCodec)+        assertEquals(listOf(DB_NAME to "notes-backup-test-passphrase"), agent.dbConfigs)+        assertEquals(listOf("datastore_default"), agent.datastoreNames)+        assertEquals(listOf("note_images"), agent.extraFiles.map { it.name })+    }++    @Test+    fun agentMintsPassphraseWhenNoneExistsYet() {+        // The restore-target case: no AndroidKeyStore key has ever been+        // generated on this device, so the agent must mint the passphrase the+        // codec re-encrypts under (and the first real open later decrypts).+        DatabaseHelper(ctx).deleteKey()+        val agent = attachedAgent()+        val configs = agent.dbConfigs+        assertEquals(1, configs.size)+        assertEquals(DB_NAME, configs.single().first)+        assertTrue(configs.single().second.isNotBlank())+        assertEquals(configs.single().second, DatabaseHelper(ctx).getPassphrase())+    }++    @Test+    fun realAgentBackupThenRestoreRoundTripsSettingsAndImages() {+        val agent = attachedAgent()+        val dbFile = ctx.getDatabasePath(DB_NAME)+        dbFile.delete()++        val settingsFile =+            File(ctx.filesDir, "datastore_default.preferences_pb")+                .apply {+                    parentFile?.mkdirs()+                    writeBytes(byteArrayOf(11, 22, 33, 44))+                }+        val imageFile =+            File(ctx.filesDir, "note_images/fixed-image.jpg")+                .apply {+                    parentFile?.mkdirs()+                    writeBytes(byteArrayOf(55, 66, 77))+                }++        val stateFile = File(ctx.cacheDir, "notes-backup-state.bin").apply { delete() }+        val output = BackupDataOutputFactory.newInstance()+        agent.onBackup(null, output, pfd(stateFile))+        val entities = Shadows.shadowOf(output).entities+        assertEquals(1, entities.size)+        val entity = entities.single()+        assertEquals("full_backup", entity.key())++        // The zip the agent would ship carries settings + images, and no+        // database entry while no live DB exists on this host.+        val entryNames = mutableListOf<String>()+        ZipInputStream(ByteArrayInputStream(entity.data())).use { zip ->+            var entry = zip.nextEntry+            while (entry != null) {+                entryNames += entry.name+                entry = zip.nextEntry+            }+        }+        assertTrue("datastore_default.preferences_pb" in entryNames, "$entryNames")+        assertTrue(entryNames.any { it.startsWith("note_images") }, "$entryNames")+        assertTrue(entryNames.none { it.contains(DB_NAME) }, "$entryNames")++        settingsFile.delete()+        imageFile.parentFile?.deleteRecursively()+        assertTrue(!settingsFile.exists() && !imageFile.exists())++        val restoreState = File(ctx.cacheDir, "notes-restore-state.bin").apply { delete() }+        val input = BackupDataInputBuilder.newBuilder().addEntity(entity).build()+        agent.onRestore(input, 1, pfd(restoreState))++        assertEquals(listOf<Byte>(11, 22, 33, 44), settingsFile.readBytes().toList())+        assertEquals(listOf<Byte>(55, 66, 77), imageFile.readBytes().toList())+        // Clean-start guarantee: restore dropped no notes-db file at all, so+        // the first open creates a fresh database instead of failing on+        // ciphertext keyed to the old device.+        assertFalse(dbFile.exists(), "restore must not drop an undecryptable notes-db")+        assertEquals(8, restoreState.length())+    }++    @Test+    fun manifestDeclaresAgentAndExtractionRulesExcludeRawDatabases() {+        val info = ctx.packageManager.getApplicationInfo(ctx.packageName, 0)+        assertEquals(+            "com.vayunmathur.notes.platform.AppBackupAgent",+            info.backupAgentName,+        )+        assertTrue(info.flags and ApplicationInfo.FLAG_ALLOW_BACKUP != 0)++        val resId = ctx.resources.getIdentifier("data_extraction_rules", "xml", ctx.packageName)+        assertTrue(resId != 0, "manifest dataExtractionRules resource resolves")+        val parser: XmlResourceParser = ctx.resources.getXml(resId)+        val sections = mutableMapOf<String, MutableSet<String>>()+        var section: String? = null+        var event = parser.eventType+        while (event != XmlResourceParser.END_DOCUMENT) {+            if (event == XmlResourceParser.START_TAG) {+                when (parser.name) {+                    "cloud-backup", "device-transfer" -> {+                        section = parser.name+                        sections[section] = mutableSetOf()+                    }+                    "exclude", "include" -> section?.let {+                        sections.getValue(it).add(+                            "${parser.name}:${parser.getAttributeValue(null, "domain")}:" ++                                parser.getAttributeValue(null, "path"),+                        )+                    }+                }+            }+            if (event == XmlResourceParser.END_TAG && parser.name in sections) section = null+            event = parser.next()+        }+        for (channel in listOf("cloud-backup", "device-transfer")) {+            val rules = sections[channel].orEmpty()+            assertTrue("include:file:." in rules, "$channel carries files by copy: $rules")+            for (db in listOf(DB_NAME, "passwords-db")) {+                for (suffix in listOf("", "-wal", "-shm", "-journal")) {+                    assertTrue(+                        "exclude:database:$db$suffix" in rules,+                        "$channel must exclude raw $db$suffix: $rules",+                    )+                }+            }+            assertTrue(+                "exclude:sharedpref:secure_prefs.xml" in rules,+                "$channel must exclude the wrapped passphrase: $rules",+            )+        }+    }+}