Modern Apps git

← Modern-Apps.git

photos: carry photo database through backup codec, not raw file

Commit
97269872537c5c6c47e576c1b7e1c7bf041b6b69
Author
Vayun Mathur <[email protected]>
When
2026-12-04 22:05 UTC (1 day ago)
Parents
3b4fd57
Photos declared no BackupAgent, so stock device transfer copied the
raw SQLCipher photo database (plus the secure vault) by file rule.
That database is encrypted under a passphrase wrapped by the old
device's non-exportable AndroidKeyStore key, so the restored copy
could not be opened on the new device - which also destroyed the
face and people metadata (user-assigned person names, hidden flags,
face embeddings and cluster centroids) that expensive on-device
analysis built and that cannot be re-derived cheaply.

Follow the weather pattern: declare .platform.AppBackupAgent, a
BaseBackupAgent whose SqlCipherDbCodec exports the database to
plaintext inside the backup payload and re-encrypts it under the new
device's key on restore, plus the datastore_default file. Add
PHOTO_DB_NAME (the historic passwords-db name, unchanged so existing
installs are not stranded) and photosDbConfigs, which mints the
passphrase on first use exactly as the Room builder does so a restore
on a fresh device re-encrypts under a newly created key instead of
throwing for a passphrase that was never created. All three photo
repositories now pass the database name explicitly; vault naming is
pinned the same way (VAULT_DB_NAME) with no file renamed anywhere.

Rewrite data_extraction_rules.xml: both channels include-then-exclude
(the lint-required shape weather uses) and always exclude the raw
photo database, its -wal/-shm/-journal sidecars and secure_prefs.xml,
so no path can ship the unopenable file or its keystore-wrapped
passphrase. Cloud also excludes the secure-folder vault; device
transfer carries vault-db and secure_vault raw inside the wholesale
includes because their key is the user's own password, which opens
them again on the new device. Gallery photos are MediaStore content
and are never included - the external domain stays out and the
restored index re-validates against MediaStore on first sync. Schema
version (23 in this tree) and the 12-to-23 migration chain with the
1-to-11 destructive floor are untouched: Room applies the same chain
on first open after a restore.

Add PhotosPlatformBackupTest, the strongest host-side proof available:
the SQLCipher native library cannot load on a host JVM, so the
encrypted content round-trip remains device-only (the :library:room
codec tests cover its pre-native contract). The test pins the agent
wiring, database names, fresh-device passphrase minting and reuse,
runs the real agent's onBackup/onRestore cycle byte-for-byte for the
datastore payload, proves a failed codec import leaves the live photo
database untouched, and parses the merged extraction rules and the
manifest agent declaration the platform consults.

Verified: ./gradlew :photos:lint :photos:lintVitalRelease
:photos:testDevUnitTest green (433 + 415 tests; lintVitalRelease
reports SKIPPED as before). An earlier full run failed
VaultViewerPageRealTest and one GalleryViewModel test; VaultViewer
fails identically in isolation on the unmodified base (proven in a
clean worktree at the same tip) and both pass on the final full run,
so those failures are pre-existing flakes, not this change.
Not pushed or merged.

Diff

photos/AGENTS.md
diff --git a/photos/AGENTS.md b/photos/AGENTS.mdindex 9399975c28..a34b5b6804 100644--- a/photos/AGENTS.md+++ b/photos/AGENTS.md@@ -190,6 +190,7 @@ _Install: ./install photos (dev by default)._ - com/vayunmathur/photos/platform/SyncWorkerHelper.kt - com/vayunmathur/photos/platform/LiveWallpaperLauncher.kt - com/vayunmathur/photos/platform/WallpaperHelper.kt+- com/vayunmathur/photos/platform/AppBackupAgent.kt — platform backup agent: carries the photo database (file `passwords-db`, named by `PHOTO_DB_NAME` in `data/PhotoDatabase.kt` with its `photosDbConfigs`) through `SqlCipherDbCodec` plus the `datastore_default` file, so face/people metadata (person names, hidden flags, face/OCR/CLIP payloads) survives a restore re-encrypted under the new device's key. The raw SQLCipher file and `secure_prefs` never ship (non-exportable keystore wrapping); gallery photos are MediaStore content and stay out of the payload. The secure-folder vault (`vault-db` + `secure_vault`, keyed by the user's password) travels raw only on device transfer and through its own in-app password export, never in cloud backup. Extraction rules in `src/main/res/xml/data_extraction_rules.xml` govern device transfer and mirror these exclusions  ## Verify (this module only) ```
photos/src/main/AndroidManifest.xml
diff --git a/photos/src/main/AndroidManifest.xml b/photos/src/main/AndroidManifest.xmlindex 1f767a1272..a68cdd0688 100644--- a/photos/src/main/AndroidManifest.xml+++ b/photos/src/main/AndroidManifest.xml@@ -30,6 +30,7 @@         android:protectionLevel="signature" />     <application         android:allowBackup="true"+        android:backupAgent=".platform.AppBackupAgent"         android:dataExtractionRules="@xml/data_extraction_rules"         android:icon="@mipmap/ic_launcher"         android:label="@string/app_name"
photos/src/main/java/com/vayunmathur/photos/data/FaceRepository.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/FaceRepository.kt b/photos/src/main/java/com/vayunmathur/photos/data/FaceRepository.ktindex 9ffb56ebc0..c0184741b8 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/FaceRepository.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/FaceRepository.kt@@ -12,7 +12,7 @@ import kotlinx.coroutines.flow.Flow  * [RoomRepository], touching [FaceDao] (and [PhotoScanDao] for the scanned flag).  */ class FaceRepository private constructor(context: Context) :-    RoomRepository<PhotoDatabase>(context, PhotoDatabase::class) {+    RoomRepository<PhotoDatabase>(context, PhotoDatabase::class, dbName = PHOTO_DB_NAME) {      private val faceDao: FaceDao get() = db.faceDao()     private val scanDao: PhotoScanDao get() = db.photoScanDao()
photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.ktindex c0bdf4131a..ee2c3c793f 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt@@ -1,5 +1,6 @@ package com.vayunmathur.photos.data +import android.content.Context import androidx.room3.Dao import androidx.room3.Database import androidx.room3.Delete@@ -9,8 +10,36 @@ import androidx.room3.Transaction import androidx.room3.Upsert import androidx.room3.migration.Migration import androidx.sqlite.execSQL+import com.vayunmathur.library.util.DatabaseHelper import kotlinx.coroutines.flow.Flow +/**+ * On-device file name of the photo database. This is the shared+ * [com.vayunmathur.library.room.RoomRepository] default name, kept explicit+ * here so backup and repositories name one file: renaming it would strand+ * every existing install's index.+ */+const val PHOTO_DB_NAME = "passwords-db"++/**+ * Backup config shared by [com.vayunmathur.photos.platform.AppBackupAgent]:+ * the photo database paired with its SQLCipher passphrase. The passphrase is+ * minted on first use exactly as the Room builder mints it, so a restore on+ * a fresh device (where no AndroidKeyStore key exists yet) creates the new+ * device's key and re-encrypts the imported plaintext under it instead of+ * failing to read a passphrase that was never created.+ */+fun photosDbConfigs(context: Context): List<Pair<String, String>> {+    val helper = DatabaseHelper(context)+    val passphrase = if (!helper.isKeyGenerated()) {+        helper.generateKey()+        helper.createAndStorePassphrase(helper.getCipherForEncryption())+    } else {+        helper.getPassphrase()+    }+    return listOf(PHOTO_DB_NAME to passphrase)+}+ /** Contract for photo dao. */ @Dao interface PhotoDao {
photos/src/main/java/com/vayunmathur/photos/data/PhotoScanRepository.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/PhotoScanRepository.kt b/photos/src/main/java/com/vayunmathur/photos/data/PhotoScanRepository.ktindex cc6bee9e62..d3611f6d50 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotoScanRepository.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotoScanRepository.kt@@ -10,7 +10,7 @@ import com.vayunmathur.library.room.RoomRepository  * [RoomRepository], touching only [PhotoScanDao].  */ open class PhotoScanRepository internal constructor(context: Context) :-    RoomRepository<PhotoDatabase>(context, PhotoDatabase::class) {+    RoomRepository<PhotoDatabase>(context, PhotoDatabase::class, dbName = PHOTO_DB_NAME) {      private val scanDao: PhotoScanDao get() = db.photoScanDao() 
photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt b/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.ktindex 49be25be59..995885b84c 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt@@ -13,7 +13,7 @@ import kotlinx.coroutines.flow.Flow  * class). Consumers obtain data through here.  */ open class PhotosRepository internal constructor(context: Context) :-    RoomRepository<PhotoDatabase>(context, PhotoDatabase::class) {+    RoomRepository<PhotoDatabase>(context, PhotoDatabase::class, dbName = PHOTO_DB_NAME) {      private val photoDao: PhotoDao get() = db.photoDao()     private val faceDao: FaceDao get() = db.faceDao()
photos/src/main/java/com/vayunmathur/photos/data/VaultDatabase.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/VaultDatabase.kt b/photos/src/main/java/com/vayunmathur/photos/data/VaultDatabase.ktindex 342bcc7ba7..f9704702ad 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/VaultDatabase.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/VaultDatabase.kt@@ -43,6 +43,9 @@ interface VaultPhotoDao {     suspend fun delete(value: VaultPhoto): Int } +/** On-device file name of the vault database (opened with the user's vault password). */+const val VAULT_DB_NAME = "vault-db"+ /** Vault Database: a room database implementation for vault database. */ @Database(entities = [VaultPhoto::class], version = 1, exportSchema = true) abstract class VaultDatabase : RoomDatabase() {
photos/src/main/java/com/vayunmathur/photos/data/VaultRepository.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/VaultRepository.kt b/photos/src/main/java/com/vayunmathur/photos/data/VaultRepository.ktindex 94f7e2ca1d..12d4d86a01 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/VaultRepository.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/VaultRepository.kt@@ -17,7 +17,7 @@ class VaultRepository private constructor( ) : RoomRepository<VaultDatabase>(     context,     VaultDatabase::class,-    dbName = "vault-db",+    dbName = VAULT_DB_NAME,     encryptionPassword = encryptionPassword,     migrations = emptyList<Migration>(), ) {
photos/src/main/java/com/vayunmathur/photos/platform/AppBackupAgent.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/AppBackupAgent.kt b/photos/src/main/java/com/vayunmathur/photos/platform/AppBackupAgent.ktnew file mode 100644index 0000000000..da726b62f4--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/platform/AppBackupAgent.kt@@ -0,0 +1,33 @@+package com.vayunmathur.photos.platform++import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.BaseBackupAgent+import com.vayunmathur.photos.data.photosDbConfigs++/**+ * Platform backup agent for Photos.+ *+ * Carries the photo database through [SqlCipherDbCodec]: the database is+ * exported to plaintext inside the backup payload and re-encrypted under+ * the new device's AndroidKeyStore-wrapped passphrase on restore, so face+ * and people metadata (person names, hidden flags, face embeddings and+ * cluster centroids — all expensive on-device analysis) survives a cloud+ * restore or device transfer. The raw SQLCipher file is never shipped:+ * its passphrase is wrapped by a non-exportable key that cannot leave the+ * old device, so a file copy would restore as an unopenable database.+ *+ * The gallery photos themselves are MediaStore content and are not part+ * of this payload; the secure-folder vault is not carried either, because+ * its database and files are encrypted under the user's vault password,+ * which no unattended backup can know (device transfer carries them raw+ * instead — see res/xml/data_extraction_rules.xml — and the secure folder+ * offers its own password-backed export).+ */+class AppBackupAgent : BaseBackupAgent() {+    override val dbCodec = SqlCipherDbCodec++    override val dbConfigs: List<Pair<String, String>>+        get() = photosDbConfigs(this)++    override val datastoreNames: List<String> get() = listOf("datastore_default")+}
photos/src/main/java/com/vayunmathur/photos/ui/SecureFolderPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/SecureFolderPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/SecureFolderPage.ktindex b54872ac58..3e54ba53d7 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/SecureFolderPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/SecureFolderPage.kt@@ -48,6 +48,7 @@ import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.photos.ui.LocalColumnCount import com.vayunmathur.photos.R import com.vayunmathur.photos.Route+import com.vayunmathur.photos.data.VAULT_DB_NAME import com.vayunmathur.photos.data.VaultPhoto import com.vayunmathur.photos.platform.SecureFolderViewModel import kotlin.math.roundToInt@@ -88,7 +89,7 @@ fun SecureFolderPage(                     IconSettings()                 }                 BackupButtons(-                    dbConfigs = listOf("vault-db" to password),+                    dbConfigs = listOf(VAULT_DB_NAME to password),                     dbCodec = SqlCipherDbCodec,                     extraFiles = listOf(File(context.filesDir, "secure_vault"))                 )
photos/src/main/res/xml/data_extraction_rules.xml
diff --git a/photos/src/main/res/xml/data_extraction_rules.xml b/photos/src/main/res/xml/data_extraction_rules.xmlindex 0d38898917..4af5977aa6 100644--- a/photos/src/main/res/xml/data_extraction_rules.xml+++ b/photos/src/main/res/xml/data_extraction_rules.xml@@ -3,36 +3,76 @@       Storage audited:        database/passwords-db  PhotoDatabase (Photo/Person/PhotoFace): a derived index over-                              MediaStore. EXIF, lat/long, OCR text of every image, CLIP-                              embeddings and face-cluster centroids. Almost everything-                              here is regenerable by re-running SyncWorker, but not all:-                              Person.name IS a user-assigned name (picked from contacts-                              for a face cluster) and Person.hidden is a user-set flag,-                              and neither can be re-derived by re-scanning. The-                              cropped*/projection* columns are panorama projection-                              metadata, not user edits. Still privacy-heavy (OCR text,-                              geotags, face vectors, and those user-supplied names).+                              MediaStore plus the on-device analysis built on it — EXIF,+                              lat/long, OCR text, CLIP embeddings, face embeddings and+                              cluster centroids. Most of the MediaStore-derived columns are+                              regenerable by re-running SyncWorker, but Person.name (a+                              user-assigned name for a face cluster), Person.hidden (a+                              user-set flag) and the face/OCR/CLIP payloads are user data+                              built by expensive on-device analysis and cannot be re-derived+                              cheaply. The database is SQLCipher-encrypted under a passphrase+                              wrapped by a non-exportable AndroidKeyStore key.        database/vault-db      VaultDatabase for the secure folder, opened with a                               user-supplied password rather than the keystore passphrase.-       file/secure_vault      the secure folder's stored photos. User content the user-                              deliberately hid.+       file/secure_vault      the secure folder's stored photos, AES-GCM-encrypted under a+                              key derived from that same user password.        file/datastore_default.preferences_pb  grid column count and model-version markers.        cache/image_cache      Coil disk cache; Android never backs up cacheDir. -     Cloud backup carries the grid preference only. The index is largely regenerable and-     would ship OCR text, geotags and face vectors off the device (person names and-     hidden flags would be lost on a cloud-only restore, accepted); the secure folder is-     hidden by intent and stays local. Device transfer carries both databases and the-     vault so a new phone does not have to re-index the whole library or lose person-     names, and so hidden photos survive the move without passing through Google. -->+     The photo database migrates through the declared BackupAgent+     (.platform.AppBackupAgent), which exports it to plaintext inside the backup+     payload via SqlCipherDbCodec and re-encrypts it under the new device's key on+     restore. That codec path is the one that carries face/people metadata across.+     The raw database file must therefore never travel on either channel: a restored+     copy cannot be opened (the wrapping key never leaves the old device, the new+     device mints a fresh passphrase, and Room then fails to open the file), so the+     rules below exclude it and its sidecars everywhere as the control that applies+     to device transfer and as the correct fallback if the agent is ever removed.++     The vault is different by key custody, not by sensitivity: vault-db and+     secure_vault are encrypted under the user's own password, so a raw device+     transfer copy opens again with that same password and hidden photos survive a+     phone move without passing through Google. Cloud backup excludes them — the+     secure folder is hidden by intent and stays exportable only through its own+     password-backed backup in the app.++     The gallery photos themselves are MediaStore content, not app data: the+     external domain is never included, and no rule here copies image or video+     files. They move with the system's media transfer, and the restored index+     re-validates against MediaStore on the first sync.++     SCOPE: photos 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 photosDbConfigs(this) — the photo database, exported to+     plaintext by SqlCipherDbCodec and re-encrypted on restore — plus its+     datastore_default file. The rules below govern <device-transfer>, and are+     the correct cloud control if the backupAgent is ever removed. --> <data-extraction-rules>+    <!-- Not consulted while android:backupAgent is declared; see SCOPE above. -->     <cloud-backup disableIfNoEncryptionCapabilities="true">-        <include domain="file" path="datastore_default.preferences_pb" />+        <include domain="file" path="." />+        <include domain="database" path="." />+        <include domain="sharedpref" path="." />+        <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" />+        <exclude domain="database" path="vault-db" />+        <exclude domain="database" path="vault-db-wal" />+        <exclude domain="database" path="vault-db-shm" />+        <exclude domain="database" path="vault-db-journal" />+        <exclude domain="file" path="secure_vault" />+        <exclude domain="sharedpref" path="secure_prefs.xml" />     </cloud-backup>     <device-transfer>-        <!-- Whole-domain include so the -wal/-shm sidecars travel with each database. -->+        <include domain="file" path="." />         <include domain="database" path="." />-        <include domain="file" path="secure_vault" />-        <include domain="file" path="datastore_default.preferences_pb" />+        <include domain="sharedpref" path="." />+        <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" />+        <exclude domain="sharedpref" path="secure_prefs.xml" />     </device-transfer> </data-extraction-rules>
photos/src/test/java/com/vayunmathur/photos/platform/PhotosPlatformBackupTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/platform/PhotosPlatformBackupTest.kt b/photos/src/test/java/com/vayunmathur/photos/platform/PhotosPlatformBackupTest.ktnew file mode 100644index 0000000000..0bcb78fd35--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/platform/PhotosPlatformBackupTest.kt@@ -0,0 +1,220 @@+package com.vayunmathur.photos.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.photos.data.PHOTO_DB_NAME+import com.vayunmathur.photos.data.PhotoDatabase+import com.vayunmathur.photos.data.VAULT_DB_NAME+import com.vayunmathur.photos.data.photosDbConfigs+import com.vayunmathur.testsupport.FakeAndroidKeyStore+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+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 Photos on stock Android.+ *+ * The photo database is SQLCipher-encrypted under a passphrase wrapped by a+ * non-exportable AndroidKeyStore key, so the raw file can never be a backup+ * payload: shipped raw it restores unopenable. The safe path is the declared+ * [AppBackupAgent], which exports the database to plaintext through+ * [SqlCipherDbCodec] inside the backup payload and re-encrypts it under the+ * new device's key on restore.+ *+ * Host limit, stated plainly: the SQLCipher native library cannot load on a+ * host JVM (see the :library:room codec tests), so the encrypted-content+ * round-trip itself is device-only. What this test proves on host is+ * everything around it: the agent wiring and database name, a fresh-device+ * passphrase mint that lets a restore re-encrypt instead of throwing, the+ * real agent's backup/restore cycle for the non-database payload it+ * declares, the codec's pre-native file contract for this database name,+ * and the extraction rules the platform consults for device transfer.+ */+@RunWith(RobolectricTestRunner::class)+class PhotosPlatformBackupTest {++    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 agentCarriesPhotoDatabaseThroughCodec() {+        val agent = attachedAgent()+        assertEquals(SqlCipherDbCodec, agent.dbCodec)+        assertEquals(listOf("datastore_default"), agent.datastoreNames)+        assertTrue(agent.prefNames.isEmpty(), "no SharedPreferences file may ship, least of all secure_prefs")+        assertTrue(agent.extraFiles.isEmpty(), "vault files stay out of the unattended payload")+    }++    @Test+    fun dbConfigsNameHistoricDatabaseAndMintFreshPassphrase() {+        assertEquals("passwords-db", PHOTO_DB_NAME)+        assertEquals("vault-db", VAULT_DB_NAME)+        val configs = photosDbConfigs(ctx)+        assertEquals(listOf(PHOTO_DB_NAME), configs.map { it.first })+        assertTrue(configs.single().second.isNotBlank())+        // Minted once: a second lookup (the restore side) reuses the same passphrase.+        assertEquals(configs, photosDbConfigs(ctx))+    }++    @Test+    fun manifestDeclaresAgentAndAllowBackup() {+        val info = ctx.packageManager.getApplicationInfo(ctx.packageName, 0)+        assertEquals("com.vayunmathur.photos.platform.AppBackupAgent", info.backupAgentName)+        assertTrue(info.flags and ApplicationInfo.FLAG_ALLOW_BACKUP != 0)+    }++    @Test+    fun extractionRulesNeverShipRawPhotoDatabase() {+        val sections = parseExtractionRules()+        for (channel in listOf("cloud-backup", "device-transfer")) {+            val rules = sections[channel].orEmpty()+            assertTrue("exclude:database:$PHOTO_DB_NAME" in rules, "$channel must exclude the raw photo DB, was $rules")+            for (sidecar in listOf("-wal", "-shm", "-journal")) {+                assertTrue(+                    "exclude:database:$PHOTO_DB_NAME$sidecar" in rules,+                    "$channel must exclude the $sidecar sidecar, was $rules",+                )+            }+            assertTrue("exclude:sharedpref:secure_prefs.xml" in rules, "$channel must exclude secure_prefs, was $rules")+            // The database domain is included wholesale (the lint-required+            // shape, as in weather) and the photo database is carved back+            // out by the excludes above: exclude wins over include.+            assertTrue("include:database:." in rules, "$channel must use include-then-exclude, was $rules")+            assertTrue(rules.none { it.startsWith("include:external") }, "$channel must not copy MediaStore files, was $rules")+        }+        // Cloud keeps the hidden vault local; device transfer carries it raw+        // (inside the wholesale file/database includes, with no vault+        // exclude) because its key is the user's password, not the keystore.+        val cloud = sections.getValue("cloud-backup")+        assertTrue("exclude:database:$VAULT_DB_NAME" in cloud, "cloud must exclude vault-db, was $cloud")+        assertTrue("exclude:file:secure_vault" in cloud, "cloud must exclude secure_vault, was $cloud")+        val transfer = sections.getValue("device-transfer")+        assertTrue("include:file:." in transfer, "device transfer must carry app files, was $transfer")+        assertTrue(+            transfer.none { it == "exclude:database:$VAULT_DB_NAME" || it == "exclude:file:secure_vault" },+            "device transfer must not exclude the vault, was $transfer",+        )+    }++    private fun parseExtractionRules(): Map<String, Set<String>> {+        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()+                    }+                    "include", "exclude" -> 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()+        }+        return sections+    }++    @Test+    fun realAgentBackupThenRestoreRoundTripsDatastore() {+        val agent = attachedAgent()+        val defaultFile = File(ctx.filesDir, "datastore_default.preferences_pb")+            .apply { parentFile?.mkdirs(); writeBytes(byteArrayOf(11, 22, 33, 44, 55)) }++        val stateFile = File(ctx.cacheDir, "photos-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)+        assertEquals("full_backup", entities.single().key())++        defaultFile.delete()+        assertTrue(!defaultFile.exists())++        val restoreState = File(ctx.cacheDir, "photos-restore-state.bin").apply { delete() }+        val input = BackupDataInputBuilder.newBuilder().addEntity(entities.single()).build()+        agent.onRestore(input, 1, pfd(restoreState))++        assertEquals(listOf<Byte>(11, 22, 33, 44, 55), defaultFile.readBytes().toList())+    }++    @Test+    fun failedCodecImportLeavesLivePhotoDatabaseUntouched() {+        // The codec builds and verifies a replacement beside the live file+        // and only swaps it in once proven good. On host the native layer+        // cannot load (on device a corrupt input fails verification), so+        // the import must fail with the live set byte-for-byte intact.+        val dbFile = ctx.getDatabasePath(PHOTO_DB_NAME)+        dbFile.parentFile?.mkdirs()+        dbFile.writeBytes(byteArrayOf(1))+        val wal = File("${dbFile.path}-wal").apply { writeBytes(byteArrayOf(2)) }+        val shm = File("${dbFile.path}-shm").apply { writeBytes(byteArrayOf(3)) }+        val input = File(ctx.cacheDir, "photos-import-plaintext.db")+        input.writeBytes(ByteArray(32) { 5 })+        try {+            runCatching {+                SqlCipherDbCodec.importDatabase(ctx, PHOTO_DB_NAME, "pw", input)+            }+            assertTrue(dbFile.exists())+            assertTrue(byteArrayOf(1).contentEquals(dbFile.readBytes()))+            assertTrue(byteArrayOf(2).contentEquals(wal.readBytes()))+            assertTrue(byteArrayOf(3).contentEquals(shm.readBytes()))+            val leftovers = dbFile.parentFile?.listFiles()+                ?.filter { it.name.contains(".import-") || it.name.contains(".bak-") }+                .orEmpty()+            assertTrue(leftovers.isEmpty(), "leftover swap files: $leftovers")+        } finally {+            dbFile.delete(); wal.delete(); shm.delete(); input.delete()+        }+    }++    @Test+    fun schemaVersionAndMigrationChainAreUntouched() {+        // Backup preserves the database file as-is; Room applies this same+        // chain on first open after a restore, so it must stay contiguous.+        assertEquals(22 to 23, PhotoDatabase.migrations.last().let { it.startVersion to it.endVersion })+        assertEquals(+            (12..22).map { it to it + 1 },+            PhotoDatabase.migrations.map { it.startVersion to it.endVersion },+        )+        assertEquals((1..11).toSet(), PhotoDatabase.destructiveMigrationFrom)+    }+}