findfamily: make stock-OS backup safe without key material
- Commit
e5c74b771d206ad499f4e52b9384dc330a5a2f17- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-04 21:59 UTC (1 day ago)
- Parents
c6d0dd5
Find Family's device-transfer rules shipped the raw SQLCipher database (passwords-db). Its passphrase is wrapped by a non-exportable AndroidKeyStore key that never transfers, so the restored file cannot be opened on the new device, which mints a fresh wrapping key and passphrase. Following the weather pattern, the app now declares a platform BackupAgent (platform/AppBackupAgent) whose only payload is the database through a new FindFamilyDbBackupCodec: SqlCipherDbCodec exports it to plaintext inside the backup payload and re-encrypts it under the new device's passphrase on restore. The codec then sanitizes the plaintext export, because Find Family's database mixes user content with pairing state. Key-material decision, documented in domain/PlatformBackup.kt: the E2EE identity (userid, ff_pqc identity keypair, tracker and powered-off private keys, all in the default DataStore) is never backed up in any form - the agent declares no DataStore, prefs or extra files, and data_extraction_rules exclude the DataStore file and secure_prefs.xml (the wrapped DB passphrase) on both cloud and device-transfer. Per-row pairing state is stripped from the export: peer bundle cache, legacy encryptionKey and both hidden pair IDs are nulled, TemporaryLink rows (whose seed is the link secret) and tracker rows (whose private bundles live in the excluded store) are deleted, and this device's own row is dropped when its userid is readable. People, waypoints, location history and no-show watches survive; restored people return as AWAITING_REQUEST and re-pair explicitly through the existing Add Person flow, which fingerprint-checks and pins the peer's current bundle and mints a fresh outbound pair ID. No silent re-trust, no identity cloning. data_extraction_rules.xml now excludes passwords-db and its sidecars, secure_prefs.xml, the identity DataStore and the decrypted wear snapshot from both channels identically, so no channel can ship the raw encrypted database. The manual, user-chosen backup keeps its existing DB+DataStore contract and is now the only backup carrying identity material. The stale no-backup-agent host test is updated to the new contract, and findfamily/AGENTS.md documents the new files. Verified in the worktree (baseline at 30be4a93a was green before the change, so no failures are pre-existing): ./gradlew :findfamily:lint :findfamily:lintVitalRelease :findfamily:testDevUnitTest (env as specified, --max-workers=128) passes, including new PlatformBackupTest (pure sanitize contract) and FindFamilyPlatformBackupTest (manifest, agent wiring and merged extraction rules; the codec itself is native/host-limited).
Diff
findfamily/AGENTS.md
diff --git a/findfamily/AGENTS.md b/findfamily/AGENTS.mdindex 3e40a5d9ee..3a04c4a92a 100644--- a/findfamily/AGENTS.md+++ b/findfamily/AGENTS.md@@ -85,7 +85,9 @@ location sharing never starts there. - com/vayunmathur/findfamily/data/Coord.kt - com/vayunmathur/findfamily/data/LocationValue.kt - com/vayunmathur/findfamily/data/DirectBootStore.kt+- com/vayunmathur/findfamily/data/FindFamilyDbBackupCodec.kt — platform-backup codec: `SqlCipherDbCodec` export/import plus plaintext-export sanitization (see `domain/PlatformBackup.kt`) ### domain/ — pairing auth, no-show policy, sender movement policy (pure logic)+- com/vayunmathur/findfamily/domain/PlatformBackup.kt — stock-OS backup contract (`FindFamilyPlatformBackup`): sanitized DB-only agent payload, identity/pairing/link secrets never backed up, restored people re-pair via Add Person - com/vayunmathur/findfamily/domain/PairAuth.kt - com/vayunmathur/findfamily/domain/NoShowPolicy.kt - com/vayunmathur/findfamily/domain/MovementDetector.kt — sender moving/still state machine (acceleration + fix speed + displacement)@@ -105,6 +107,7 @@ location sharing never starts there. - com/vayunmathur/findfamily/ipc/FamilyLocationProtocol.kt - com/vayunmathur/findfamily/ipc/FamilyLocationService.kt ### platform/ — reporters + schedulers+- com/vayunmathur/findfamily/platform/AppBackupAgent.kt — stock-OS backup agent (manifest `backupAgent`): sanitized `passwords-db` only via `data/FindFamilyDbBackupCodec`; no DataStore/prefs/files; raw DB + `secure_prefs` + identity DataStore excluded by `res/xml/data_extraction_rules.xml` on both channels - com/vayunmathur/findfamily/platform/FormFactor.kt — watch detection (`FEATURE_WATCH`) for the single merged APK - com/vayunmathur/findfamily/platform/FinalLocationReporter.kt - com/vayunmathur/findfamily/platform/NoShowCheckScheduler.kt@@ -181,7 +184,6 @@ location sharing never starts there. - com/vayunmathur/findfamily/util/FindFamilyNotificationChannels.kt - com/vayunmathur/findfamily/util/TrackingTileService.kt - com/vayunmathur/findfamily/util/BootReceiver.kt-- com/vayunmathur/findfamily/util/AppBackupAgent.kt ## Verify (this module only) ```
findfamily/src/main/AndroidManifest.xml
diff --git a/findfamily/src/main/AndroidManifest.xml b/findfamily/src/main/AndroidManifest.xmlindex 396066a1da..f356e435b3 100644--- a/findfamily/src/main/AndroidManifest.xml+++ b/findfamily/src/main/AndroidManifest.xml@@ -73,6 +73,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"
findfamily/src/main/java/com/vayunmathur/findfamily/data/FindFamilyDbBackupCodec.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FindFamilyDbBackupCodec.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FindFamilyDbBackupCodec.ktnew file mode 100644index 0000000000..a58866f4ff--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FindFamilyDbBackupCodec.kt@@ -0,0 +1,71 @@+package com.vayunmathur.findfamily.data++import android.content.Context+import android.database.sqlite.SQLiteDatabase+import com.vayunmathur.findfamily.domain.FindFamilyPlatformBackup+import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.library.util.DbBackupCodec+import kotlinx.coroutines.runBlocking+import java.io.File++/**+ * Platform-backup codec for the Find Family database: the weather+ * [SqlCipherDbCodec] pattern (export to plaintext inside the backup payload,+ * re-encrypt under the new device's passphrase on import) plus the Find+ * Family sanitization from [FindFamilyPlatformBackup.sanitizeStatements].+ *+ * Export delegates to [SqlCipherDbCodec] first, then opens the resulting+ * plaintext SQLite file with the framework SQLite API (an exported plaintext+ * file is an ordinary SQLite database) and runs the sanitize statements, so+ * the payload that leaves the device contains no pairing secrets, no link+ * secrets and no tracker rows — see [FindFamilyPlatformBackup] for the full+ * key-material decision. Import is the plain codec import: the payload was+ * already sanitized at export time, and the codec builds and verifies the+ * re-encrypted replacement before swapping it in, so a corrupt payload+ * leaves the live database untouched.+ *+ * This codec is used only by the OS platform agent+ * ([com.vayunmathur.findfamily.platform.AppBackupAgent]). The manual,+ * user-chosen backup in `ui/BackupMenuButton` keeps using the raw+ * [SqlCipherDbCodec] with its existing DataStore-including contract.+ */+object FindFamilyDbBackupCodec : DbBackupCodec {++ override fun exportDatabase(context: Context, dbName: String, password: String, outputFile: File) {+ SqlCipherDbCodec.exportDatabase(context, dbName, password, outputFile)+ if (!outputFile.exists() || outputFile.length() == 0L) return+ scrubPlaintextExport(outputFile, ownUserId(context))+ }++ override fun importDatabase(context: Context, dbName: String, password: String, inputFile: File) {+ SqlCipherDbCodec.importDatabase(context, dbName, password, inputFile)+ }++ /**+ * This device's `userid` from the default DataStore, or null when it+ * cannot be read (locked storage, backup before first unlock, any store+ * failure). Backup runs on a background thread, so awaiting the store+ * here cannot block the UI; a null result only means the own row is+ * sanitized like every other row instead of being dropped.+ */+ private fun ownUserId(context: Context): Long? = runCatching {+ runBlocking { DataStoreUtils.getInstance(context).getLongAwait("userid") }+ }.getOrNull()++ /** Runs the sanitize statements against the plaintext export in place. */+ private fun scrubPlaintextExport(outputFile: File, ownUserId: Long?) {+ val db = SQLiteDatabase.openDatabase(+ outputFile.path,+ null,+ SQLiteDatabase.OPEN_READWRITE,+ )+ try {+ FindFamilyPlatformBackup.sanitizeStatements(ownUserId).forEach { statement ->+ db.execSQL(statement)+ }+ } finally {+ db.close()+ }+ }+}
findfamily/src/main/java/com/vayunmathur/findfamily/domain/FamilyBackup.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/domain/FamilyBackup.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/FamilyBackup.ktindex 0ded9aa60c..26bcc59acc 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/domain/FamilyBackup.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/FamilyBackup.kt@@ -13,9 +13,12 @@ package com.vayunmathur.findfamily.domain * * The manual backup covers the encrypted Room database plus the default * DataStore, which holds the stable device identity and the E2EE key material.- * It is a user-triggered export to a user-chosen file only: OS backup no longer- * carries this payload (no backupAgent is declared, and data_extraction_rules- * deny cloud backup; D2D carries the database file alone, without the keys).+ * It is a user-triggered export to a user-chosen file only, and it is the+ * only backup that carries identity key material. Stock-OS platform backup+ * is a separate path (see [FindFamilyPlatformBackup]): its agent exports+ * the database alone, sanitized of pairing and link secrets, and the+ * data-extraction rules keep the raw database file, the wrapped passphrase+ * and the identity DataStore out of both cloud backup and device transfer. * Pre-removal manual backups contained only the database entry; such legacy * files still restore — the missing DataStore entry is simply skipped by the reader. */
findfamily/src/main/java/com/vayunmathur/findfamily/domain/PlatformBackup.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/domain/PlatformBackup.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/PlatformBackup.ktnew file mode 100644index 0000000000..8426e310a1--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/PlatformBackup.kt@@ -0,0 +1,105 @@+package com.vayunmathur.findfamily.domain++/**+ * Stock-OS platform backup contract for Find Family (cloud backup and+ * device-to-device transfer), as opposed to the user-triggered manual backup+ * in [FamilyBackup].+ *+ * ## The defect this fixes+ * The Room database (`passwords-db`, see [FamilyBackup.DB_NAME]) is+ * SQLCipher-encrypted under a passphrase wrapped by a non-exportable+ * AndroidKeyStore key (`secure_prefs` / `DatabaseHelper`). That key never+ * leaves the device that created it, so a *raw file copy* of the database —+ * which is what the old device-transfer rules shipped — restores as a file+ * the new device cannot open: the new device mints a fresh wrapping key and+ * passphrase, and Room/SQLCipher then fails on the already-encrypted file.+ * Platform backup must therefore never carry the raw database file. The+ * database content instead travels through+ * [com.vayunmathur.library.room.SqlCipherDbCodec] (the weather pattern):+ * exported to a plaintext SQLite file inside the backup payload on the old+ * device and re-encrypted under the new device's own passphrase on restore.+ *+ * ## Key-material decision (explicit)+ * Find Family holds end-to-end-encryption identity and pairing state, and not+ * everything in the database is safe — or even meaningful — to copy:+ *+ * - **Never backed up, in any form:** the device identity. The stable+ * `userid`, the `ff_pqc` ML-KEM/ML-DSA identity keypair, tracker secrets and+ * private bundles, and powered-off recovery keys all live in the default+ * DataStore (`datastore_default`), sealed per device. Copying them raw+ * would either restore undecryptable (they are wrapped by the old device's+ * keystore) or, if copied decryptable, would clone the E2EE identity onto+ * another device and break the E2EE model. The platform agent therefore+ * declares no DataStore, no shared preferences and no extra files, and the+ * data-extraction rules exclude the DataStore file and `secure_prefs.xml`+ * (the wrapped SQLCipher passphrase) on both channels. A restored device+ * mints its own identity and its own database passphrase.+ * - **Stripped from the exported database by [sanitizeStatements]:** every+ * per-pairing secret or trust binding stored on a `User` row+ * (`encryptionKey`, the cached peer bundle `pqcEncryptionKey`, and the+ * hidden sender-auth pair IDs `inboundPairId`/`outboundPairId`), every+ * `TemporaryLink` row (its `pqcSeed`/legacy `pqcKey` is the link's entire+ * private secret — copying it is copying key material, and a row without+ * it could never be re-shared, so links are recreated after restore), and+ * every tracker row (a tracker's private bundle lives in the DataStore+ * above, so a restored tracker could never decrypt its reports and must be+ * re-bound). This device's own `User` row is dropped when its id is known:+ * the restored device generates a new `userid`, so the old row would+ * otherwise linger as a phantom person.+ * - **Preserved:** the non-key user content — people (names, photos, last+ * known place, sharing toggles), saved waypoints, location history and+ * no-show watches. Restored people are reset to+ * `RequestStatus.AWAITING_REQUEST`: they are remembered, but no location+ * flows to or from them until the user re-pairs through the existing+ * Add Person flow, which fingerprint-checks the peer's current bundle,+ * pins the verified key and mints a fresh outbound pair ID for the new+ * identity. That is the clean re-pair path; there is deliberately no+ * silent re-trust of a relay-served bundle for a restored contact.+ *+ * The manual backup ([FamilyBackup]) is a different, user-chosen file and+ * keeps its existing contract; only the OS platform path is sanitized this+ * way.+ */+object FindFamilyPlatformBackup {++ /** Room database name, shared with the manual backup contract. */+ const val DB_NAME = FamilyBackup.DB_NAME++ /** Database configs for the platform agent: name to SQLCipher passphrase. */+ fun dbConfigs(passphrase: String): List<Pair<String, String>> =+ listOf(DB_NAME to passphrase)++ /**+ * SQL statements that strip key material and pairing state from the+ * *plaintext* database export before it enters the backup payload, in+ * execution order. Pure and host-testable: the codec that runs them+ * against a real SQLite file needs a device, but what runs is exactly+ * this list. [ownUserId] is this device's `userid` when it could be+ * read at backup time; when null the own row is left in place (still+ * reset to awaiting-re-pair like every other row) rather than guessed.+ *+ * `Waypoint`, `LocationValue` history for other people and+ * `NoShowAlert` are deliberately untouched: they carry no key material.+ */+ fun sanitizeStatements(ownUserId: Long?): List<String> = buildList {+ // Link secrets are key material; a secret-less link row is dead weight.+ add("DELETE FROM `TemporaryLink`")+ // Tracker private bundles live in the excluded DataStore, so a+ // restored tracker row could never decrypt anything again.+ add("DELETE FROM `User` WHERE `kind` = 'TRACKER'")+ if (ownUserId != null) {+ // The restored device mints a new userid; the old own row would+ // otherwise survive as a phantom contact, history included.+ add("DELETE FROM `User` WHERE `id` = $ownUserId")+ add("DELETE FROM `LocationValue` WHERE `userid` = $ownUserId")+ }+ // People survive as remembered contacts only: no cached peer bundle,+ // no pair-ID secrets, and no location flow until an explicit,+ // fingerprint-checked re-pair through Add Person.+ add(+ "UPDATE `User` SET `encryptionKey` = NULL, `pqcEncryptionKey` = NULL, " ++ "`inboundPairId` = NULL, `outboundPairId` = NULL, " ++ "`requestStatus` = 'AWAITING_REQUEST'"+ )+ }+}
findfamily/src/main/java/com/vayunmathur/findfamily/platform/AppBackupAgent.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/AppBackupAgent.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/AppBackupAgent.ktnew file mode 100644index 0000000000..85d6aa558c--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/AppBackupAgent.kt@@ -0,0 +1,33 @@+package com.vayunmathur.findfamily.platform++import com.vayunmathur.findfamily.data.FindFamilyDbBackupCodec+import com.vayunmathur.findfamily.domain.FindFamilyPlatformBackup+import com.vayunmathur.library.util.BaseBackupAgent+import com.vayunmathur.library.util.DatabaseHelper++/**+ * Stock-OS platform backup agent (cloud key/value backup; the+ * data-extraction rules carry the matching raw-file exclusions for+ * device-to-device transfer).+ *+ * Only the Room database travels, and only through+ * [FindFamilyDbBackupCodec]: plaintext-inside-the-payload on export,+ * re-encrypted under this device's fresh passphrase on restore, with all+ * pairing/key material stripped by+ * [FindFamilyPlatformBackup.sanitizeStatements]. The raw SQLCipher file is+ * never shipped (its passphrase is wrapped by a non-exportable keystore key,+ * so a copied file would be unopenable on the new device).+ *+ * Deliberately declared nowhere here: the default DataStore, which holds+ * the `userid` and the `ff_pqc` E2EE identity keypair plus tracker and+ * powered-off private keys, and `secure_prefs`, which holds the wrapped+ * database passphrase. Identity is per-device and is re-minted on the new+ * device; restored people re-pair explicitly. See+ * [FindFamilyPlatformBackup].+ */+class AppBackupAgent : BaseBackupAgent() {+ override val dbCodec = FindFamilyDbBackupCodec++ override val dbConfigs: List<Pair<String, String>>+ get() = FindFamilyPlatformBackup.dbConfigs(DatabaseHelper(this).getPassphrase())+}
findfamily/src/main/res/xml/data_extraction_rules.xml
diff --git a/findfamily/src/main/res/xml/data_extraction_rules.xml b/findfamily/src/main/res/xml/data_extraction_rules.xmlindex b50aa121b6..6ef69e1497 100644--- a/findfamily/src/main/res/xml/data_extraction_rules.xml+++ b/findfamily/src/main/res/xml/data_extraction_rules.xml@@ -1,30 +1,74 @@ <?xml version="1.0" encoding="utf-8"?>-<!-- Overrides the permissive default in the shared :library module.+<!--+ Find Family. Audited state:+ * databases/passwords-db — FFDatabase (User/Waypoint/LocationValue/+ TemporaryLink/NoShowAlert): people, saved places, precise location+ history, share-link state and no-show watches.+ * files/datastore_default.preferences_pb — the default DataStore:+ userid plus the E2EE identity keypair ("ff_pqc" PqcIdentity), tracker+ secrets/private bundles and powered-off recovery keys. Private key+ material, sealed per device.+ * shared_prefs/secure_prefs.xml — the SQLCipher passphrase for+ passwords-db, wrapped by a non-exportable AndroidKeyStore key.+ * files/wear-findfamily-snapshot.json — the watch snapshot: already-+ decrypted people summaries, regenerated from Room via the conduit.+ Excluded so decrypted location state never rides a raw file copy; the+ phone re-publishes it and the watch re-derives it after restore. - Storage audited:- database/passwords-db FFDatabase (User/Waypoint/LocationValue/TemporaryLink):- precise location history and family link state.- file/datastore_default.preferences_pb userid plus the E2EE identity keypair and- the "ff_pqc" post-quantum keys (Networking.init ->- E2eeIdentity/PqcIdentity.loadOrCreate). Private key material.- sharedpref/secure_prefs keystore-wrapped SQLCipher passphrase.+ The raw database file must never be copied on either channel: its+ passphrase is wrapped by the old device's keystore key, which never+ transfers, so a restored copy cannot be opened (the new device mints a+ fresh key/passphrase and SQLCipher rejects the already-encrypted file).+ The database content instead travels through the declared BackupAgent+ (platform/AppBackupAgent + FindFamilyDbBackupCodec, the weather+ SqlCipherDbCodec pattern): exported to plaintext inside the backup+ payload and re-encrypted under the new device's passphrase on restore,+ with pairing secrets, link secrets and tracker rows stripped first+ (domain/FindFamilyPlatformBackup documents the key-material decision).+ Restored people keep their names/photos/places/history but return as+ awaiting-re-pair; identity and link secrets are re-minted/recreated on+ the new device, never restored. - Nothing leaves for cloud backup: location history is sensitive and the DataStore- holds long-term private keys. Device transfer carries the location history only;- the key material stays on the device that generated it, so a new device- re-establishes its own identity and family links. -->+ SCOPE: findfamily declares android:backupAgent=".platform.AppBackupAgent"+ and does NOT set android:fullBackupOnly, so Android uses key/value backup+ for cloud and the <cloud-backup> section below is NOT consulted. Cloud+ content is exactly the agent's sanitized passwords-db export — no+ DataStore, no preferences, no extra files. The rules below govern+ <device-transfer>, and are the correct control if the backupAgent is+ ever removed. Both sections are identical so the two channels stay+ coherent: no channel ever ships the raw encrypted database, the wrapped+ passphrase, or the identity DataStore.+--> <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="." />+ <include domain="database" 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="file" path="datastore_default.preferences_pb" />+ <exclude domain="file" path="datastore/datastore_default.preferences_pb" />+ <exclude domain="file" path="wear-findfamily-snapshot.json" />+ <include domain="sharedpref" path="." />+ <exclude domain="sharedpref" path="secure_prefs.xml" />+ <include domain="external" path="." /> </cloud-backup> <device-transfer>- <!-- Allowlist: the database domain only, so the DataStore holding the E2EE and- PQC private keys is excluded. Whole-domain include keeps the -wal/-shm- sidecars with the database. -->+ <include domain="root" path="." />+ <include domain="file" path="." /> <include domain="database" 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="file" path="datastore_default.preferences_pb" />+ <exclude domain="file" path="datastore/datastore_default.preferences_pb" />+ <exclude domain="file" path="wear-findfamily-snapshot.json" />+ <include domain="sharedpref" path="." />+ <exclude domain="sharedpref" path="secure_prefs.xml" />+ <include domain="external" path="." /> </device-transfer> </data-extraction-rules>
findfamily/src/test/java/com/vayunmathur/findfamily/domain/PlatformBackupTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/domain/PlatformBackupTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/domain/PlatformBackupTest.ktnew file mode 100644index 0000000000..d24e93df45--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/domain/PlatformBackupTest.kt@@ -0,0 +1,91 @@+package com.vayunmathur.findfamily.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Pure-JVM tests for the stock-OS platform backup contract+ * ([FindFamilyPlatformBackup]).+ *+ * The SQLCipher codec itself needs a device, so these tests pin the part+ * that decides what the backup payload may contain: the sanitize statement+ * list the codec executes verbatim against the plaintext export. If a+ * future edit lets a secret column, a link secret or the identity store+ * back into the platform payload, it fails here first.+ */+class PlatformBackupTest {++ @Test+ fun dbConfigsCarryHistoricDbName() {+ assertEquals("passwords-db", FindFamilyPlatformBackup.DB_NAME)+ assertEquals(+ listOf("passwords-db" to "pw"),+ FindFamilyPlatformBackup.dbConfigs("pw"),+ )+ }++ @Test+ fun sanitizeNullsEveryPairingSecretAndResetsPeopleToAwaitingRepair() {+ val statements = FindFamilyPlatformBackup.sanitizeStatements(ownUserId = null)+ val update = statements.single { it.startsWith("UPDATE `User`") }+ // Every per-pairing secret/trust column on the User row is cleared:+ // the legacy key, the cached peer bundle and both hidden pair IDs.+ for (column in listOf("encryptionKey", "pqcEncryptionKey", "inboundPairId", "outboundPairId")) {+ assertTrue("`$column` = NULL" in update, "expected $column nulled in: $update")+ }+ // Restored people are remembered contacts, not live pairings: no+ // location flows until the fingerprint-checked Add Person re-pair.+ assertTrue("`requestStatus` = 'AWAITING_REQUEST'" in update, update)+ }++ @Test+ fun sanitizeDeletesLinkSecretsAndTrackerRows() {+ val statements = FindFamilyPlatformBackup.sanitizeStatements(ownUserId = null)+ // A TemporaryLink's pqcSeed/pqcKey is its entire private secret:+ // copying the row copies key material, and a row without the secret+ // can never be re-shared, so links are recreated after restore.+ assertTrue("DELETE FROM `TemporaryLink`" in statements, "$statements")+ // Tracker private bundles live in the excluded identity DataStore,+ // so a restored tracker row could never decrypt its reports.+ assertTrue("DELETE FROM `User` WHERE `kind` = 'TRACKER'" in statements, "$statements")+ }++ @Test+ fun sanitizePreservesNonKeyUserContent() {+ val joined = FindFamilyPlatformBackup.sanitizeStatements(ownUserId = null)+ .joinToString("\n")+ // Waypoints, other people's location history and no-show watches+ // carry no key material and must survive untouched.+ assertFalse("Waypoint" in joined, joined)+ assertFalse("NoShowAlert" in joined, joined)+ assertFalse("DELETE FROM `LocationValue`" in joined, joined)+ // No destructive shortcut (dropping/truncating the people table+ // would throw the preserved content away with the secrets).+ assertFalse("DROP " in joined, joined)+ assertFalse("DELETE FROM `User`" in joined.replace("DELETE FROM `User` WHERE", ""), joined)+ }++ @Test+ fun sanitizeDropsOwnRowAndItsHistoryWhenOwnIdIsKnown() {+ val statements = FindFamilyPlatformBackup.sanitizeStatements(ownUserId = 4242L)+ // The restored device mints a new userid, so the old own row would+ // otherwise linger as a phantom contact.+ assertTrue("DELETE FROM `User` WHERE `id` = 4242" in statements, "$statements")+ assertTrue("DELETE FROM `LocationValue` WHERE `userid` = 4242" in statements, "$statements")+ }++ @Test+ fun sanitizeWithoutOwnIdDeletesNoPersonRow() {+ val statements = FindFamilyPlatformBackup.sanitizeStatements(ownUserId = null)+ assertFalse(+ statements.any { it.startsWith("DELETE FROM `User` WHERE `id`") },+ "$statements",+ )+ assertFalse(+ statements.any { it.startsWith("DELETE FROM `LocationValue`") },+ "$statements",+ )+ }+}
findfamily/src/test/java/com/vayunmathur/findfamily/platform/FindFamilyPlatformBackupTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/platform/FindFamilyPlatformBackupTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/platform/FindFamilyPlatformBackupTest.ktnew file mode 100644index 0000000000..270a6e5376--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/platform/FindFamilyPlatformBackupTest.kt@@ -0,0 +1,114 @@+package com.vayunmathur.findfamily.platform++import android.content.Context+import android.content.pm.ApplicationInfo+import android.content.res.XmlResourceParser+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.FindFamilyDbBackupCodec+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertSame+import kotlin.test.assertTrue++/**+ * Host-side wiring proof for stock-OS platform backup. SQLCipher is native,+ * so the codec round-trip itself cannot run here; what can be proven on the+ * host is exactly what the platform would consult: the manifest's agent,+ * the agent's codec/config surface (database only — no DataStore, prefs or+ * files that could carry identity key material), and the merged+ * data-extraction rules that govern device transfer (and cloud, if the+ * agent were ever removed).+ */+@RunWith(AndroidJUnit4::class)+class FindFamilyPlatformBackupTest {++ private val app: Context get() = ApplicationProvider.getApplicationContext()++ @Test+ fun manifestDeclaresBackupAgentWithAllowBackup() {+ val info = app.packageManager.getApplicationInfo(app.packageName, 0)+ assertEquals(+ "com.vayunmathur.findfamily.platform.AppBackupAgent",+ info.backupAgentName,+ )+ assertTrue(info.flags and ApplicationInfo.FLAG_ALLOW_BACKUP != 0)+ }++ @Test+ fun agentCarriesOnlyTheSanitizedDatabase() {+ val agent = AppBackupAgent()+ // The codec is the sanitizing wrapper, not the raw SQLCipher codec:+ // the plaintext export is scrubbed before it enters the payload.+ assertSame(FindFamilyDbBackupCodec, agent.dbCodec)+ // No identity-bearing stores ride along: the default DataStore holds+ // the userid and the ff_pqc identity keypair, secure_prefs holds the+ // wrapped DB passphrase. Neither may be copied in any form.+ assertTrue(agent.datastoreNames.isEmpty(), "no DataStore in platform backup")+ assertTrue(agent.prefNames.isEmpty(), "no shared prefs in platform backup")+ assertTrue(agent.extraFiles.isEmpty(), "no extra files in platform backup")+ }++ /** Parses the merged rules into section -> (kind, domain, path) triples. */+ private fun extractionRules(): Map<String, List<Triple<String, String, String>>> {+ val resId = app.resources.getIdentifier("data_extraction_rules", "xml", app.packageName)+ assertTrue(resId != 0, "manifest dataExtractionRules resource resolves")+ val parser: XmlResourceParser = app.resources.getXml(resId)+ val sections = mutableMapOf<String, MutableList<Triple<String, String, 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] = mutableListOf()+ }+ "exclude", "include" -> section?.let {+ sections.getValue(it).add(+ Triple(+ 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 extractionRulesExcludeRawDatabaseAndKeyStoresOnBothChannels() {+ val sections = extractionRules()+ for (channel in listOf("cloud-backup", "device-transfer")) {+ val rules = sections[channel].orEmpty()+ fun excluded(domain: String, path: String) =+ Triple("exclude", domain, path) in rules+ // The raw SQLCipher file (passphrase wrapped by a non-exportable+ // keystore key) would restore unopenable; sidecars included.+ for (path in listOf("passwords-db", "passwords-db-wal", "passwords-db-shm", "passwords-db-journal")) {+ assertTrue(excluded("database", path), "$channel must exclude raw $path, was $rules")+ }+ // The wrapped passphrase and the identity DataStore never copy.+ assertTrue(excluded("sharedpref", "secure_prefs.xml"), "$channel, was $rules")+ assertTrue(+ excluded("file", "datastore_default.preferences_pb"),+ "$channel must exclude the identity DataStore, was $rules",+ )+ // The decrypted watch snapshot is regenerated from Room, never+ // carried as a raw file.+ assertTrue(+ excluded("file", "wear-findfamily-snapshot.json"),+ "$channel, was $rules",+ )+ }+ // Coherent channels: cloud and device-transfer apply the same rules,+ // so neither can ship what the other forbids.+ assertEquals(sections["cloud-backup"], sections["device-transfer"])+ }+}
findfamily/src/test/java/com/vayunmathur/findfamily/service/TilesBootAndChannelsTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/service/TilesBootAndChannelsTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/service/TilesBootAndChannelsTest.ktindex 28c4c952ec..b8d211b0b1 100644--- a/findfamily/src/test/java/com/vayunmathur/findfamily/service/TilesBootAndChannelsTest.kt+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/service/TilesBootAndChannelsTest.kt@@ -25,8 +25,8 @@ import kotlin.test.assertNotNull import kotlin.test.assertTrue /**- * Quick Settings tiles, boot receiver, notification channels and the no-agent- * backup contract in the sandbox: tile clicks flip the persisted switches, the boot receiver+ * Quick Settings tiles, boot receiver, notification channels and the platform+ * backup-agent contract in the sandbox: tile clicks flip the persisted switches, the boot receiver * ignores unrelated broadcasts and unpermitted boots, and channels are created * per person with the documented ids. */@@ -139,11 +139,16 @@ class TilesBootAndChannelsTest { ) } - @Test fun manifestHasNoBackupAgentAndExtractionRulesGovern() {- // The legacy backup agent was removed (it bypassed the deny-all cloud- // rules); data_extraction_rules.xml now governs both channels.+ @Test fun manifestDeclaresSanitizingBackupAgentAndExtractionRules() {+ // The platform agent carries the database only, through the+ // sanitizing codec; data_extraction_rules.xml keeps the raw+ // encrypted database and the identity DataStore out of D2D (and+ // would govern cloud too if the agent were ever removed). val info = app.packageManager.getApplicationInfo(app.packageName, 0)- assertEquals(null, info.backupAgentName)+ assertEquals(+ "com.vayunmathur.findfamily.platform.AppBackupAgent",+ info.backupAgentName,+ ) assertTrue(app.resources.getIdentifier("data_extraction_rules", "xml", app.packageName) != 0) assertNotNull(DataStoreUtils.getInstance(ctx)) }