todo: back up tasks via SQLCipher codec agent, not raw DB
- Commit
79d1469854e02905edc80ecf375122662b58a442- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-04 22:01 UTC (1 day ago)
- Parents
6dc1a50
Platform backup previously restored the raw todo-db file. That database is SQLCipher-encrypted under a passphrase wrapped by the old device's non-exportable AndroidKeyStore key, so the restored copy could not be opened on a new device. Mirror the proven weather pattern: declare .platform.AppBackupAgent (BaseBackupAgent + SqlCipherDbCodec + existing todoDbConfigs) so the key/value backup payload carries the database exported to plaintext and re-encrypts it under the new device's key on restore; the codec verifies the replacement before swapping it in, so a corrupt payload leaves the live DB untouched. The agent also carries datastore_default, preserving TodoSettings on platform restore as the in-app backup already did. Rewrite data_extraction_rules coherently for cloud and device-transfer: exclude todo-db and its -wal/-shm/-journal sidecars plus secure_prefs.xml (keystore-bound passphrase) on both channels, so no path ever ships the undecryptable raw DB. With backupAgent declared and no fullBackupOnly, cloud uses the agent's key/value payload and the cloud-backup section is not consulted; the rules govern device-transfer and remain the safe control if the agent is ever removed. Host verification: TodoBackupAgentTest (Robolectric) pins the agent wiring (real SqlCipherDbCodec, datastore_default, DB_NAME), the manifest backupAgentName, the parsed extraction-rule exclusions, and a BackupHelper round-trip through the codec seam with a fake codec plus the settings file. The real encrypted-to-plaintext-to-re-encrypted round trip needs the SQLCipher native library and AndroidKeyStore, so it is device-provable only (covered on device by DeviceDatabaseTest in :library:room). Verified: ./gradlew :todo:lint :todo:lintVitalRelease :todo:testDevUnitTest (baseline at 30be4a93a also green; lintVitalRelease's report task is SKIPPED in both, its analyze task runs). New files are ktlint-clean; module-wide ktlintCheck fails on pre-existing drift in untouched files.
Diff
todo/src/main/AndroidManifest.xml
diff --git a/todo/src/main/AndroidManifest.xml b/todo/src/main/AndroidManifest.xmlindex dd03cb3bdc..c1dc459b41 100644--- a/todo/src/main/AndroidManifest.xml+++ b/todo/src/main/AndroidManifest.xml@@ -62,6 +62,7 @@ <application android:name=".TodoApplication" android:allowBackup="true"+ android:backupAgent=".platform.AppBackupAgent" android:dataExtractionRules="@xml/data_extraction_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name"
todo/src/main/java/com/vayunmathur/todo/platform/AppBackupAgent.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/platform/AppBackupAgent.kt b/todo/src/main/java/com/vayunmathur/todo/platform/AppBackupAgent.ktnew file mode 100644index 0000000000..b756db691b--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/platform/AppBackupAgent.kt@@ -0,0 +1,27 @@+package com.vayunmathur.todo.platform++import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.BaseBackupAgent+import com.vayunmathur.todo.data.todoDbConfigs++/**+ * Key/value backup agent for the platform backup transport.+ *+ * The raw `todo-db` file must never travel as a file copy: it is+ * SQLCipher-encrypted under a passphrase wrapped by a non-exportable+ * AndroidKeyStore key, so a copy restored on another device cannot be+ * opened. This agent instead exports the database to plaintext inside+ * the backup payload via [SqlCipherDbCodec] and re-encrypts it under+ * the new device's key on restore (the codec builds and verifies the+ * replacement before swapping it in, so a corrupt payload leaves the+ * live database untouched). The shared `datastore_default` file that+ * holds TodoSettings travels alongside it.+ */+class AppBackupAgent : BaseBackupAgent() {+ override val dbCodec = SqlCipherDbCodec++ override val dbConfigs: List<Pair<String, String>>+ get() = todoDbConfigs(this)++ override val datastoreNames: List<String> get() = listOf("datastore_default")+}
todo/src/main/res/xml/data_extraction_rules.xml
diff --git a/todo/src/main/res/xml/data_extraction_rules.xml b/todo/src/main/res/xml/data_extraction_rules.xmlindex d0fcba934d..926ab96c79 100644--- a/todo/src/main/res/xml/data_extraction_rules.xml+++ b/todo/src/main/res/xml/data_extraction_rules.xml@@ -1,20 +1,68 @@ <?xml version="1.0" encoding="utf-8"?>-<!-- Storage audited:- database/todo-db TodoDatabase (Todo): the user's task list.- file/datastore_default.preferences_pb app settings.- sharedpref/secure_prefs keystore-wrapped SQLCipher passphrase.+<!--+ Todo. Audited state:+ * databases/todo-db — Room DB holding the user's tasks, lists and+ sync snapshots (genuinely worth restoring).+ * files/datastore_default.preferences_pb — TodoSettings (default+ view/sort, digest, calendar mirror) via the shared DataStoreUtils.+ * shared_prefs/secure_prefs.xml — SQLCipher passphrase wrapped by a+ non-exportable AndroidKeyStore key.+ * shared_prefs/todo_reminders.xml — scheduled-alarm bookkeeping;+ ReminderScheduler.reconcile rebuilds it from the tasks, so it is+ regenerable either way.+ * files/wear-todo-*.json — the watch-side catalog/page/pending-op+ cache. The phone is the source of truth and republishes it, so it+ needs no protection of its own here. - Tasks are user-authored content worth restoring on a new device, so both- channels carry the todo database. Caches and the keystore-bound passphrase- are left out by the allowlist. -->+ todo-db is excluded from both sections: it is SQLCipher-encrypted+ under a passphrase wrapped by a non-exportable AndroidKeystore key.+ That key never leaves the device, so a restored raw copy of this file+ cannot be opened — the repository mints a fresh key and passphrase,+ and Room would fail on the already-encrypted file. Shipping it would+ trade a clean first launch for an undecryptable database.++ The tasks still migrate: todo declares its own BackupAgent, which+ uses SqlCipherDbCodec to export the DB to plaintext inside the backup+ payload and re-encrypt it under the new device's key on restore. That+ path is the one that works; the raw file copy would only get in its+ way. secure_prefs.xml is excluded for the same reason — it is only+ meaningful with the old device's keystore key, and the new device+ mints its own passphrase on first launch.++ SCOPE: todo 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: todo-db exported+ to plaintext by SqlCipherDbCodec plus datastore_default. The rules+ below govern <device-transfer>, and are the correct control if the+ backupAgent is ever removed (in that case the settings and other+ plaintext files still migrate, and the database is recreated empty+ rather than restored undecryptable).+--> <data-extraction-rules>- <cloud-backup disableIfNoEncryptionCapabilities="true">- <!-- Whole-domain include so the -wal/-shm sidecars travel with the database. -->+ <!-- Not consulted while android:backupAgent is declared; see SCOPE above. -->+ <cloud-backup>+ <include domain="root" path="." />+ <include domain="file" path="." /> <include domain="database" path="." />- <include domain="file" path="datastore_default.preferences_pb" />+ <exclude domain="database" path="todo-db" />+ <exclude domain="database" path="todo-db-wal" />+ <exclude domain="database" path="todo-db-shm" />+ <exclude domain="database" path="todo-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="todo-db" />+ <exclude domain="database" path="todo-db-wal" />+ <exclude domain="database" path="todo-db-shm" />+ <exclude domain="database" path="todo-db-journal" />+ <include domain="sharedpref" path="." />+ <exclude domain="sharedpref" path="secure_prefs.xml" />+ <include domain="external" path="." /> </device-transfer> </data-extraction-rules>
todo/src/test/java/com/vayunmathur/todo/platform/TodoBackupAgentTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/platform/TodoBackupAgentTest.kt b/todo/src/test/java/com/vayunmathur/todo/platform/TodoBackupAgentTest.ktnew file mode 100644index 0000000000..2686f666e2--- /dev/null+++ b/todo/src/test/java/com/vayunmathur/todo/platform/TodoBackupAgentTest.kt@@ -0,0 +1,196 @@+package com.vayunmathur.todo.platform++import android.content.Context+import android.content.pm.PackageManager+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.BackupHelper+import com.vayunmathur.library.util.BaseBackupAgent+import com.vayunmathur.library.util.DbBackupCodec+import com.vayunmathur.todo.R+import com.vayunmathur.todo.data.DB_NAME+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.xmlpull.v1.XmlPullParser+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertSame+import kotlin.test.assertTrue++/**+ * Host-side wiring proof for the platform-backup fix.+ *+ * The real [SqlCipherDbCodec] needs the SQLCipher native library and an+ * AndroidKeyStore-wrapped passphrase, neither of which a host JVM can+ * provide, so the actual encrypted-to-plaintext-to-re-encrypted round+ * trip is device-provable only (see DeviceDatabaseTest in+ * :library:room). What is proven here, at host strength:+ * - the declared agent wires the real codec, the todo DB config name+ * and the settings datastore into [BaseBackupAgent];+ * - the manifest actually declares that agent;+ * - the extraction rules never ship the raw encrypted DB or the+ * keystore-bound passphrase on either channel;+ * - [BackupHelper] (the exact code the agent runs) round-trips a DB+ * payload through its codec seam plus the settings file, which is+ * the contract [SqlCipherDbCodec] fulfils on device.+ */+@RunWith(RobolectricTestRunner::class)+class TodoBackupAgentTest {+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @Test fun agentWiresCodecDbAndSettingsDatastore() {+ val agent = AppBackupAgent()+ assertTrue(BaseBackupAgent::class.java.isAssignableFrom(AppBackupAgent::class.java))+ assertSame(SqlCipherDbCodec, agent.dbCodec)+ assertEquals(listOf("datastore_default"), agent.datastoreNames)+ assertEquals("todo-db", DB_NAME)+ }++ @Test fun manifestDeclaresBackupAgent() {+ val info = ctx.packageManager.getApplicationInfo(ctx.packageName, PackageManager.GET_META_DATA)+ assertEquals(+ "com.vayunmathur.todo.platform.AppBackupAgent",+ info.backupAgentName,+ )+ assertTrue(info.flags and android.content.pm.ApplicationInfo.FLAG_ALLOW_BACKUP != 0)+ }++ @Test fun extractionRulesNeverShipRawDbOrPassphrase() {+ val rules = parseExtractionRules()+ assertEquals(setOf("cloud-backup", "device-transfer"), rules.keys)+ for ((section, entries) in rules) {+ fun has(+ action: String,+ domain: String,+ path: String,+ ) = entries.contains(Rule(section, action, domain, path))+ for (suffix in listOf("", "-wal", "-shm", "-journal")) {+ assertTrue(+ has("exclude", "database", "todo-db$suffix"),+ "$section must exclude raw todo-db$suffix",+ )+ }+ assertTrue(+ has("exclude", "sharedpref", "secure_prefs.xml"),+ "$section must exclude the keystore-bound passphrase",+ )+ // No specific include may resurrect the raw files.+ assertTrue(+ entries.none { it.action == "include" && it.domain == "database" && it.path.startsWith("todo-db") },+ )+ assertTrue(entries.none { it.action == "include" && it.path == "secure_prefs.xml" })+ // Settings (files/datastore_default.preferences_pb) ride the file domain.+ assertTrue(has("include", "file", "."), "$section must carry the settings file domain")+ }+ }++ /** Stands in for SqlCipherDbCodec's contract without its native library. */+ private class FakeCodec : DbBackupCodec {+ override fun exportDatabase(+ context: Context,+ dbName: String,+ password: String,+ outputFile: File,+ ) {+ val live = context.getDatabasePath(dbName)+ outputFile.parentFile?.mkdirs()+ outputFile.writeBytes(HEADER + live.readBytes())+ assertEquals("pw", password)+ }++ override fun importDatabase(+ context: Context,+ dbName: String,+ password: String,+ inputFile: File,+ ) {+ val bytes = inputFile.readBytes()+ assertTrue(+ bytes.size >= HEADER.size && HEADER.indices.all { bytes[it] == HEADER[it] },+ "import only accepts codec-exported plaintext",+ )+ val live = context.getDatabasePath(dbName)+ live.parentFile?.mkdirs()+ live.writeBytes(bytes.drop(HEADER.size).toByteArray())+ }++ companion object {+ val HEADER = "PLAIN:".toByteArray()+ }+ }++ @Test fun backupHelperRoundTripsDbThroughCodecAndSettingsFile() {+ val dbFile =+ ctx.getDatabasePath(DB_NAME).apply {+ parentFile?.mkdirs()+ writeText("encrypted-task-rows")+ }+ val settings =+ File(ctx.filesDir, "datastore_default.preferences_pb").apply {+ writeText("settings-bytes")+ }+ val out = ByteArrayOutputStream()+ BackupHelper.performFullBackup(+ ctx,+ dbConfigs = listOf(DB_NAME to "pw"),+ datastoreNames = listOf("datastore_default"),+ extraFiles = emptyList(),+ outputStream = out,+ dbCodec = FakeCodec(),+ )+ assertTrue(out.size() > 0, "backup payload written")++ dbFile.delete()+ settings.delete()++ BackupHelper.performFullRestore(+ ctx,+ dbConfigs = listOf(DB_NAME to "pw"),+ datastoreNames = listOf("datastore_default"),+ extraFilesMapping = emptyMap(),+ inputStream = ByteArrayInputStream(out.toByteArray()),+ dbCodec = FakeCodec(),+ )+ assertEquals("encrypted-task-rows", dbFile.readText())+ assertEquals("settings-bytes", settings.readText())+ }++ private data class Rule(+ val section: String,+ val action: String,+ val domain: String,+ val path: String,+ )++ private fun parseExtractionRules(): Map<String, List<Rule>> {+ val parser = ctx.resources.getXml(R.xml.data_extraction_rules)+ val result = mutableMapOf<String, MutableList<Rule>>()+ var section: String? = null+ var event = parser.eventType+ while (event != XmlPullParser.END_DOCUMENT) {+ when (event) {+ XmlPullParser.START_TAG ->+ when (parser.name) {+ "cloud-backup", "device-transfer" -> section = parser.name+ "include", "exclude" ->+ section?.let { s ->+ result.getOrPut(s) { mutableListOf() }.add(+ Rule(+ s,+ parser.name,+ parser.getAttributeValue(null, "domain"),+ parser.getAttributeValue(null, "path"),+ ),+ )+ }+ }+ XmlPullParser.END_TAG -> if (parser.name == section) section = null+ }+ event = parser.next()+ }+ return result+ }+}