Modern Apps git

← Modern-Apps.git

appstore: make platform backup safe on stock OS

Commit
3cb27c79dabd50732733054e0d42d85443378846
Author
Vayun Mathur <[email protected]>
When
2026-12-04 22:39 UTC (1 day ago)
Parents
f5d9ca4
The device-to-device rules carried the raw SQLCipher appstore-db,
whose passphrase is wrapped by the old device's non-exportable
AndroidKeyStore key (secure_prefs), so a restored copy could not be
opened and the first Room open would crash. Cloud backup denied
everything for the same shared-file reason, losing the user's
repos and settings on every move.

Split by re-derivability, with signature/trust verification
semantics unchanged:

- Survives via codec: AppBackupAgent (key/value, the WEATHER
  pattern over BaseBackupAgent + SqlCipherDbCodec) carries the DB
  as plaintext inside the payload, re-encrypted under the new
  device's passphrase on restore. AppStoreDbBackupCodec strips
  CachedAppEntity from the plaintext copy on export and import
  (DELETE + VACUUM), so RepoEntity (configured repos with their
  index fingerprints), PinnedStampEntity (TOFU source-stamp pins)
  and AccrescentTrustEntity (the ed25519-verified allowlist) move,
  while the multi-megabyte catalogue is re-derived from the signed
  repo indexes on the next sync.
- Survives as DataStore: appstore-settings (auto-install opt-in,
  disabled sources) and accrescent_repodata (the signed-repodata
  anti-rollback timestamp floor guarding the restored allowlist).
- Never carried: play_auth (live anonymous-Play credential bound
  to the old gsfId/profile, re-dispensed), secure_prefs (the
  KeyStore-wrapped passphrase itself), the update-check installed-
  app inventory, restricted/TV-incompatible learned packages
  (device-specific facts, re-learned), wear catalogue/phases/APKs
  (re-synced over the conduit), and cache scratch.

Both rule channels now exclude the raw DB and sidecars, the
wrapped passphrase, the Play credential and the learned
suppressions; external is never included. Cloud content while
the agent is declared is exactly the agent payload; the rules
are the D2D control and the correct fallback if it is removed.

Verified: :appstore:lint :appstore:lintVitalRelease green.
:appstore:testDevUnitTest: 533 tests, only TvMainActivityTest
(ComposeTimeoutException, the known flake) fails; the same test
fails identically on pristine 30be4a93a in a throwaway worktree,
so it is pre-existing. New AppStoreBackupAgentTest (6 tests)
proves the agent wiring, a real onBackup->onRestore round-trip
of both declared DataStores, the catalogue strip preserving
repo/pin/allowlist rows on a real plaintext SQLite file, and
the manifest/rules exclusions. Remainder: the encrypted DB
round-trip needs native SQLCipher, unavailable on host; it is
delegated unchanged to SqlCipherDbCodec's temp-verify-swap.

Diff

appstore/AGENTS.md
diff --git a/appstore/AGENTS.md b/appstore/AGENTS.mdindex 2b8ef75db3..a1a134fad2 100644--- a/appstore/AGENTS.md+++ b/appstore/AGENTS.md@@ -66,6 +66,8 @@ form factor. - com/vayunmathur/appstore/data/AppModels.kt - com/vayunmathur/appstore/data/AppDatabase.kt - com/vayunmathur/appstore/data/AppStoreDatabaseRepository.kt+- com/vayunmathur/appstore/data/AppStoreDbBackupCodec.kt — backup codec: SQLCipher plaintext round-trip with the re-derivable CachedAppEntity catalogue stripped (repos, stamp pins and Accrescent allowlist survive)+- com/vayunmathur/appstore/platform/AppBackupAgent.kt — key/value BackupAgent (DB via the codec + appstore-settings/accrescent_repodata DataStores; play_auth, all SharedPreferences and wear files excluded); raw DB excluded in res/xml/data_extraction_rules.xml on both channels - com/vayunmathur/appstore/data/InstalledAppsRepository.kt - com/vayunmathur/appstore/data/SettingsRepository.kt - com/vayunmathur/appstore/data/UpdateCheckWorker.kt
appstore/src/main/AndroidManifest.xml
diff --git a/appstore/src/main/AndroidManifest.xml b/appstore/src/main/AndroidManifest.xmlindex a1d546716e..4281e0ec13 100644--- a/appstore/src/main/AndroidManifest.xml+++ b/appstore/src/main/AndroidManifest.xml@@ -62,6 +62,7 @@      <application         android:allowBackup="true"+        android:backupAgent=".platform.AppBackupAgent"         android:banner="@drawable/tv_banner"         android:dataExtractionRules="@xml/data_extraction_rules"         android:icon="@mipmap/ic_launcher"
appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.ktindex 41f5d343dc..b678474aec 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt@@ -11,10 +11,25 @@ import androidx.room3.Upsert import androidx.room3.migration.Migration import androidx.sqlite.SQLiteConnection import androidx.sqlite.execSQL+import android.content.Context+import com.vayunmathur.library.util.DatabaseHelper import kotlinx.coroutines.flow.Flow  const val DB_NAME = "appstore-db" +/**+ * Backup config shared by [com.vayunmathur.appstore.platform.AppBackupAgent].+ * Empty while no database file exists yet (nothing to carry, and no+ * passphrase has been minted), mirroring the SQLCipher codec's missing-DB+ * no-op; once the DB exists its passphrase exists with it.+ */+fun appStoreDbConfigs(context: Context): List<Pair<String, String>> =+    if (context.getDatabasePath(DB_NAME).exists()) {+        listOf(DB_NAME to DatabaseHelper(context).getPassphrase())+    } else {+        emptyList()+    }+ @Entity /** A configured app repository stored by its URL. */ data class RepoEntity(
appstore/src/main/java/com/vayunmathur/appstore/data/AppStoreDbBackupCodec.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/AppStoreDbBackupCodec.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/AppStoreDbBackupCodec.ktnew file mode 100644index 0000000000..4a25dc3a95--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppStoreDbBackupCodec.kt@@ -0,0 +1,65 @@+package com.vayunmathur.appstore.data++import android.content.Context+import android.database.sqlite.SQLiteDatabase+import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.DbBackupCodec+import java.io.File++/**+ * Backup codec for [DB_NAME] that keeps the catalog out of the backup.+ *+ * The one Room file mixes two kinds of rows:+ *  - user/trust state that must survive a move: [RepoEntity] (the repos the+ *    user configured, with their index-signing fingerprints),+ *    [PinnedStampEntity] (trust-on-first-use source-stamp pins) and+ *    [AccrescentTrustEntity] (the ed25519-verified Accrescent allowlist+ *    cache; restoring it together with the `accrescent_repodata` DataStore+ *    timestamp keeps the anti-rollback floor and the allowlist it guards+ *    consistent). Verification semantics are untouched: restored pins and+ *    allowlist entries are consulted by exactly the same checks as before.+ *  - [CachedAppEntity]: the multi-megabyte catalogue index of every app in+ *    every enabled repo. It is re-derived from the (signed) repo indexes on+ *    the next sync, so carrying it would bloat the backup payload with+ *    regenerable data and buy nothing.+ *+ * The split is applied to the plaintext file the SQLCipher codec produces /+ * consumes, never to the live database: export delegates to+ * [SqlCipherDbCodec] (decrypt to plaintext) and then deletes the catalogue+ * rows from the plaintext copy; import deletes them from the incoming+ * plaintext before delegating (re-encrypt under the new device's+ * passphrase), so a payload can never resurrect the catalogue either. The+ * live DB on the old device keeps its catalogue; the restored DB opens+ * with an empty catalogue that the next sync repopulates.+ */+object AppStoreDbBackupCodec : DbBackupCodec {++    override fun exportDatabase(context: Context, dbName: String, password: String, outputFile: File) {+        SqlCipherDbCodec.exportDatabase(context, dbName, password, outputFile)+        if (outputFile.exists() && outputFile.length() > 0L) stripCatalog(outputFile)+    }++    override fun importDatabase(context: Context, dbName: String, password: String, inputFile: File) {+        if (inputFile.exists() && inputFile.length() > 0L) stripCatalog(inputFile)+        SqlCipherDbCodec.importDatabase(context, dbName, password, inputFile)+    }++    /**+     * Deletes every catalogue row from the plaintext SQLite file [plainDbFile]+     * and VACUUMs so the freed pages actually leave the backup payload.+     * User/trust tables are not touched. No-op when the file is missing or+     * carries no catalogue table (a backup made before the table existed).+     */+    internal fun stripCatalog(plainDbFile: File) {+        if (!plainDbFile.exists() || plainDbFile.length() == 0L) return+        SQLiteDatabase.openDatabase(plainDbFile.path, null, SQLiteDatabase.OPEN_READWRITE).use { db ->+            val hasCatalog = db.rawQuery(+                "SELECT name FROM sqlite_master WHERE type='table' AND name='CachedAppEntity'",+                null,+            ).use { it.moveToFirst() }+            if (!hasCatalog) return+            db.execSQL("DELETE FROM CachedAppEntity")+            db.execSQL("VACUUM")+        }+    }+}
appstore/src/main/java/com/vayunmathur/appstore/platform/AppBackupAgent.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/platform/AppBackupAgent.kt b/appstore/src/main/java/com/vayunmathur/appstore/platform/AppBackupAgent.ktnew file mode 100644index 0000000000..d768b54cff--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/platform/AppBackupAgent.kt@@ -0,0 +1,47 @@+package com.vayunmathur.appstore.platform++import com.vayunmathur.appstore.data.AppStoreDbBackupCodec+import com.vayunmathur.appstore.data.appStoreDbConfigs+import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.BaseBackupAgent++/**+ * Key/value backup for the store (manifest `android:backupAgent`, no+ * `fullBackupOnly`): cloud backup is exactly this agent's payload.+ *+ * Carries, in portable form:+ *  - the Room DB via [AppStoreDbBackupCodec] (plaintext inside the payload,+ *    re-encrypted under the new device's key on restore by+ *    [SqlCipherDbCodec]) with the re-derivable catalogue stripped — repos,+ *    source-stamp pins and the Accrescent allowlist survive;+ *  - the `appstore-settings` DataStore (auto-install choice, disabled+ *    sources);+ *  - the `accrescent_repodata` DataStore (the signed-repodata anti-rollback+ *    timestamp floor guarding the restored allowlist).+ *+ * Deliberately absent:+ *  - `play_auth`: a live anonymous-Play session credential bound to the old+ *    device's gsfId/profile; re-dispensed on the new device.+ *  - every SharedPreferences file: `secure_prefs` wraps the SQLCipher+ *    passphrase under a non-exportable AndroidKeyStore key (useless and+ *    misleading off-device — the codec path above replaces it), and+ *    `appstore-update-check` / `appstore-restricted-packages` /+ *    `appstore-tv-incompatible-packages` are regenerable inventories or+ *    device-specific learned facts that must not suppress updates on a+ *    different device.+ *  - the Wear watch files (`wear-catalog.json`, `wear-phases.json`,+ *    `wear-apks/`): re-synced from the phone over the conduit, and staged+ *    APKs are re-offered.+ *+ * Device-to-device transfer is governed separately by+ * `res/xml/data_extraction_rules.xml`, which excludes the raw encrypted DB+ * so this agent's re-encrypted restore is the only DB path on both channels.+ */+class AppBackupAgent : BaseBackupAgent() {+    override val dbCodec = AppStoreDbBackupCodec++    override val dbConfigs: List<Pair<String, String>>+        get() = appStoreDbConfigs(this)++    override val datastoreNames: List<String> = listOf("appstore-settings", "accrescent_repodata")+}
appstore/src/main/res/xml/data_extraction_rules.xml
diff --git a/appstore/src/main/res/xml/data_extraction_rules.xml b/appstore/src/main/res/xml/data_extraction_rules.xmlindex 9deadedfe9..c9cc64fc34 100644--- a/appstore/src/main/res/xml/data_extraction_rules.xml+++ b/appstore/src/main/res/xml/data_extraction_rules.xml@@ -1,37 +1,97 @@ <?xml version="1.0" encoding="utf-8"?>-<!-- App store client. Overrides the permissive default in the shared :library module, and-     replaces an earlier rule set that cloud-backed the whole database and all preferences.+<!--+  App store client. Stock-OS backup audit: -     Storage audit:-       database  appstore-db    Room. RepoEntity (the user's configured F-Droid repos),-                                CachedAppEntity (the full index of every app in every enabled-                                repo — multi-megabyte and refetched on demand) and-                                PinnedStampEntity (trust-on-first-use signer pins).-       file      datastore/play_auth.preferences_pb   A serialized Play AuthData: the-                                dispensed anonymous account with its auth token, gsfId and-                                device profile, plus the dispense timestamp. A live session-                                credential with a max age, re-dispensed whenever it is absent.-       sharedpref appstore-update-check.xml   The comma-joined package list from the last-                                update notification, used only to suppress repeats. It is a-                                list of the user's installed apps.-       cache     <pkg>.apk, PlayDownloads/, fdroid-index/, fdroid-verified.json   Download and-                                verification scratch under getCacheDir(), never backed up.+    database  appstore-db (+ -wal/-shm/-journal)+              Room, SQLCipher-encrypted. RepoEntity (user-configured repos+              with index-signing fingerprints), PinnedStampEntity (TOFU+              source-stamp pins) and AccrescentTrustEntity (verified+              allowlist cache) are user/trust state; CachedAppEntity (the+              full catalogue index of every enabled repo, multi-megabyte)+              is re-derived from the signed repo indexes on the next sync.+              The raw file must never be copied: its passphrase is wrapped+              by a non-exportable AndroidKeyStore key (secure_prefs.xml)+              that never leaves the old device, so a restored copy cannot+              be opened and the first Room open would crash. Instead+              AppBackupAgent exports the DB to plaintext via+              AppStoreDbBackupCodec (catalogue stripped), and re-encrypts+              under the new device's passphrase on restore.+    file      datastore/appstore-settings.preferences_pb+              User settings (auto-install opt-in, disabled sources).+              Portable protobuf; carried by the agent and allowed here.+    file      datastore/accrescent_repodata.preferences_pb+              Anti-rollback timestamp floor for Accrescent's signed+              repodata. Portable; guards the restored allowlist.+    file      datastore/play_auth.preferences_pb+              Live anonymous-Play session credential bound to the old+              device's gsfId/device profile. Never carried; re-dispensed.+    file      wear-catalog.json, wear-phases.json, wear-apks/+              Watch-side catalogue/phases and staged verified APKs.+              Re-synced / re-offered over the conduit; never carried.+    sharedpref secure_prefs.xml+              SQLCipher passphrase wrapped by the old device's KeyStore+              key. Useless off-device and superseded by the agent restore.+    sharedpref appstore-update-check.xml+              Comma-joined packages from the last update notification+              (inventory of the old device's installed apps, only used to+              suppress repeats). Regenerable; never carried.+    sharedpref appstore-restricted-packages.xml+              appstore-tv-incompatible-packages.xml+              Packages learned as install-restricted / TV-incompatible on+              THIS device. Device-specific facts (the TV store documents+              them as never synced or shared); re-learned on the new+              device at the cost of one refused install.+    cache     Download/verification scratch under getCacheDir(); the+              platform never backs up cache. -     Cloud backup is denied. The repo list is the only non-regenerable state and it shares one-     Room file with the bulk index cache and the TOFU signer pins; the update-check preference-     is a regenerable inventory of installed apps; the Play auth blob is a session credential.-     The Play credential is excluded from device transfer as well — it is bound to a gsfId and-     device profile that do not survive the move, and a stale one just costs a round-trip. -->+  SCOPE: appstore 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: the catalogue-+  stripped DB (plaintext in-payload, re-encrypted on restore) plus the+  appstore-settings and accrescent_repodata DataStores. The rules below+  govern <device-transfer>, and are the correct fallback control for+  both channels if the backupAgent is ever removed: on neither channel+  may the raw encrypted DB, its KeyStore-wrapped passphrase, the Play+  credential, or device-specific learned suppressions move. The external+  domain is simply never included, so nothing on external storage moves.+--> <data-extraction-rules>+    <!-- Not consulted while android:backupAgent is declared; see SCOPE above. -->     <cloud-backup>-        <exclude domain="root" path="." />-        <exclude domain="file" path="." />-        <exclude domain="database" path="." />-        <exclude domain="sharedpref" path="." />-        <exclude domain="external" path="." />+        <include domain="root" path="." />+        <include domain="file" path="." />+        <exclude domain="file" path="datastore/play_auth.preferences_pb" />+        <exclude domain="file" path="wear-catalog.json" />+        <exclude domain="file" path="wear-phases.json" />+        <exclude domain="file" path="wear-apks" />+        <include domain="database" path="." />+        <exclude domain="database" path="appstore-db" />+        <exclude domain="database" path="appstore-db-wal" />+        <exclude domain="database" path="appstore-db-shm" />+        <exclude domain="database" path="appstore-db-journal" />+        <include domain="sharedpref" path="." />+        <exclude domain="sharedpref" path="secure_prefs.xml" />+        <exclude domain="sharedpref" path="appstore-update-check.xml" />+        <exclude domain="sharedpref" path="appstore-restricted-packages.xml" />+        <exclude domain="sharedpref" path="appstore-tv-incompatible-packages.xml" />     </cloud-backup>     <device-transfer>+        <include domain="root" path="." />+        <include domain="file" path="." />         <exclude domain="file" path="datastore/play_auth.preferences_pb" />-        <exclude domain="external" path="." />+        <exclude domain="file" path="wear-catalog.json" />+        <exclude domain="file" path="wear-phases.json" />+        <exclude domain="file" path="wear-apks" />+        <include domain="database" path="." />+        <exclude domain="database" path="appstore-db" />+        <exclude domain="database" path="appstore-db-wal" />+        <exclude domain="database" path="appstore-db-shm" />+        <exclude domain="database" path="appstore-db-journal" />+        <include domain="sharedpref" path="." />+        <exclude domain="sharedpref" path="secure_prefs.xml" />+        <exclude domain="sharedpref" path="appstore-update-check.xml" />+        <exclude domain="sharedpref" path="appstore-restricted-packages.xml" />+        <exclude domain="sharedpref" path="appstore-tv-incompatible-packages.xml" />     </device-transfer> </data-extraction-rules>
appstore/src/test/java/com/vayunmathur/appstore/platform/AppStoreBackupAgentTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/platform/AppStoreBackupAgentTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/platform/AppStoreBackupAgentTest.ktnew file mode 100644index 0000000000..71f72d2a11--- /dev/null+++ b/appstore/src/test/java/com/vayunmathur/appstore/platform/AppStoreBackupAgentTest.kt@@ -0,0 +1,210 @@+package com.vayunmathur.appstore.platform++import android.content.Context+import android.content.pm.ApplicationInfo+import android.content.res.XmlResourceParser+import android.database.sqlite.SQLiteDatabase+import android.os.ParcelFileDescriptor+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.appstore.data.AppStoreDbBackupCodec+import com.vayunmathur.appstore.data.DB_NAME+import java.io.File+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++/**+ * Stock-OS platform backup for the store's REAL manifest agent.+ *+ * Host-strongest evidence available: the SQLCipher codec needs the native+ * library a host JVM cannot load, so the encrypted-DB round-trip itself+ * cannot run here (that remainder is covered on-device by the codec's+ * temp-verify-swap contract). What runs here, end to end:+ *  1. the agent's declared wiring (codec, DataStores, no prefs/extras, and+ *     no DB config while no DB file exists — the missing-DB no-op);+ *  2. a real onBackup -> onRestore round-trip of the two declared+ *     DataStore files through Robolectric's backup-data streams;+ *  3. the catalogue strip on a real plaintext SQLite file: catalogue rows+ *     deleted (and vacuumed), repo/pin/allowlist rows byte-preserved;+ *  4. the manifest + merged extraction rules the platform consults: agent+ *     selected for cloud, raw DB and wrapped passphrase excluded on both+ *     channels.+ */+@RunWith(RobolectricTestRunner::class)+class AppStoreBackupAgentTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    private fun attachedAgent(): AppBackupAgent {+        val agent = AppBackupAgent()+        val attach = android.content.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 agentWiringCarriesSettingsAndTrustTimestampButNoPrefsOrExtras() {+        val agent = attachedAgent()+        assertEquals(AppStoreDbBackupCodec, agent.dbCodec)+        assertEquals(listOf("appstore-settings", "accrescent_repodata"), agent.datastoreNames)+        assertTrue(agent.prefNames.isEmpty(), "no SharedPreferences file may ride the agent")+        assertTrue(agent.extraFiles.isEmpty(), "wear files are re-synced, never backed up")+        // No DB file has been created in this host context: the codec's+        // missing-DB no-op, so the backup of the DataStores cannot throw+        // trying to unwrap a passphrase that was never minted.+        assertFalse(ctx.getDatabasePath(DB_NAME).exists())+        assertTrue(agent.dbConfigs.isEmpty())+    }++    @Test+    fun realAgentBackupThenRestoreRoundTripsDeclaredDatastores() {+        val agent = attachedAgent()+        val dsDir = File(ctx.filesDir, "datastore").apply { mkdirs() }+        val settings = File(dsDir, "appstore-settings.preferences_pb")+            .apply { writeBytes(byteArrayOf(1, 3, 5, 7)) }+        val repodata = File(dsDir, "accrescent_repodata.preferences_pb")+            .apply { writeBytes(byteArrayOf(2, 4, 6, 8, 10)) }+        // The Play credential must NOT be in the payload.+        val playAuth = File(dsDir, "play_auth.preferences_pb")+            .apply { writeBytes(byteArrayOf(99)) }++        val stateFile = File(ctx.cacheDir, "appstore-backup-state.bin").apply { delete() }+        val output = org.robolectric.shadows.BackupDataOutputFactory.newInstance()+        agent.onBackup(null, output, pfd(stateFile))+        val entities = Shadows.shadowOf(output).entities+        assertEquals(1, entities.size)+        assertEquals("full_backup", entities.single().key())++        settings.delete(); repodata.delete()+        assertFalse(settings.exists()); assertFalse(repodata.exists())++        val restoreState = File(ctx.cacheDir, "appstore-restore-state.bin").apply { delete() }+        val input = BackupDataInputBuilder.newBuilder().addEntity(entities.single()).build()+        agent.onRestore(input, 1, pfd(restoreState))++        assertEquals(listOf<Byte>(1, 3, 5, 7), settings.readBytes().toList())+        assertEquals(listOf<Byte>(2, 4, 6, 8, 10), repodata.readBytes().toList())+        // play_auth was untouched by the restore (it was never backed up;+        // the live file simply remains whatever the new device dispenses).+        assertEquals(listOf<Byte>(99), playAuth.readBytes().toList())+        assertEquals(8, restoreState.length())+    }++    @Test+    fun stripCatalogDeletesOnlyCatalogueRowsFromPlaintextDb() {+        val plain = File(ctx.cacheDir, "strip-plaintext.db").apply { delete() }+        SQLiteDatabase.openOrCreateDatabase(plain, null).use { db ->+            db.execSQL("CREATE TABLE CachedAppEntity (packageName TEXT PRIMARY KEY, name TEXT)")+            db.execSQL("CREATE TABLE RepoEntity (url TEXT PRIMARY KEY, name TEXT)")+            db.execSQL("CREATE TABLE PinnedStampEntity (packageName TEXT PRIMARY KEY, stampSha256 TEXT)")+            db.execSQL(+                "CREATE TABLE AccrescentTrustEntity (appId TEXT PRIMARY KEY, signingCertHash TEXT)",+            )+            db.execSQL("INSERT INTO CachedAppEntity VALUES ('com.example.a','A')")+            db.execSQL("INSERT INTO CachedAppEntity VALUES ('com.example.b','B')")+            db.execSQL("INSERT INTO RepoEntity VALUES ('https://example.test/repo','Example')")+            db.execSQL("INSERT INTO PinnedStampEntity VALUES ('com.example.a','stamp-sha')")+            db.execSQL("INSERT INTO AccrescentTrustEntity VALUES ('com.example.a','cert-hash')")+        }+        AppStoreDbBackupCodec.stripCatalog(plain)+        SQLiteDatabase.openDatabase(plain.path, null, SQLiteDatabase.OPEN_READONLY).use { db ->+            fun count(table: String): Long =+                db.rawQuery("SELECT COUNT(*) FROM $table", null).use {+                    it.moveToFirst(); it.getLong(0)+                }+            assertEquals(0L, count("CachedAppEntity"), "catalogue is re-derivable: stripped")+            assertEquals(1L, count("RepoEntity"), "user repos survive")+            assertEquals(1L, count("PinnedStampEntity"), "TOFU pins survive")+            assertEquals(1L, count("AccrescentTrustEntity"), "verified allowlist survives")+        }+        plain.delete()+    }++    @Test+    fun stripCatalogIsNoOpWithoutCatalogueTableOrFile() {+        val plain = File(ctx.cacheDir, "strip-notables.db").apply { delete() }+        SQLiteDatabase.openOrCreateDatabase(plain, null).use { db ->+            db.execSQL("CREATE TABLE RepoEntity (url TEXT PRIMARY KEY)")+            db.execSQL("INSERT INTO RepoEntity VALUES ('https://example.test/repo')")+        }+        AppStoreDbBackupCodec.stripCatalog(plain)+        AppStoreDbBackupCodec.stripCatalog(File(ctx.cacheDir, "strip-missing.db"))+        SQLiteDatabase.openDatabase(plain.path, null, SQLiteDatabase.OPEN_READONLY).use { db ->+            db.rawQuery("SELECT COUNT(*) FROM RepoEntity", null).use {+                it.moveToFirst(); assertEquals(1L, it.getLong(0))+            }+        }+        plain.delete()+    }++    @Test+    fun manifestSelectsTheAgentAndRulesExcludeRawDbOnBothChannels() {+        val info = ctx.packageManager.getApplicationInfo(ctx.packageName, 0)+        assertTrue(info.flags and ApplicationInfo.FLAG_ALLOW_BACKUP != 0)+        assertEquals(+            "com.vayunmathur.appstore.platform.AppBackupAgent",+            info.backupAgentName,+        )++        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()+            // The restore trap: the raw SQLCipher file and its wrapped+            // passphrase must never be copied on either channel.+            assertTrue("exclude:database:appstore-db" in rules, "$channel: $rules")+            assertTrue("exclude:database:appstore-db-wal" in rules, "$channel: $rules")+            assertTrue("exclude:sharedpref:secure_prefs.xml" in rules, "$channel: $rules")+            // Credentials and device-specific learned facts stay behind too.+            assertTrue("exclude:file:datastore/play_auth.preferences_pb" in rules, "$channel: $rules")+            assertTrue(+                "exclude:sharedpref:appstore-tv-incompatible-packages.xml" in rules,+                "$channel: $rules",+            )+        }+    }++    @Test+    fun codecExportOfMissingDatabaseWritesNothing() {+        // Remainder statement: the encrypted round-trip needs the native+        // SQLCipher library, unavailable on this host. The pre-native+        // contract still runs: a missing source produces no export file.+        val output = File(ctx.cacheDir, "codec-missing-export.db").apply { delete() }+        AppStoreDbBackupCodec.exportDatabase(ctx, "no-such-db-backup-test", "pw", output)+        assertFalse(output.exists())+    }+}