launcher: make platform backup restorable on a new device
- Commit
8af7cd34c7cf7c11d2e324998bac6c46a5d079fc- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-04 21:55 UTC (1 day ago)
- Parents
180c7e7
The extraction rules backed up the raw SQLCipher launcher-db (and secure_prefs) in both cloud backup and device transfer. The DB passphrase is wrapped by the old device's non-exportable AndroidKeyStore key, so a restored copy can never be opened: the Room builder mints a fresh passphrase, skips the encrypted file, and Room throws on first launch. The layout (real user data) was lost and the first launch crashed. Follow the weather pattern. Declare .platform.AppBackupAgent (a BaseBackupAgent with SqlCipherDbCodec): the DB is exported to plaintext inside the backup payload and re-encrypted under the new device's passphrase on restore. launcherDbConfigs resolves that passphrase like the Room builder does, minting a fresh key when none exists yet, which is the fresh-device restore case (weather's bare unwrap would throw there). The same payload carries datastore_default (grid/labels/counts/seeded flag), tvlauncher_config (TV order) and the watch favorites/recents JSON files. data_extraction_rules now excludes launcher-db and its -wal/-shm/-journal sidecars plus secure_prefs.xml from both cloud-backup and device-transfer, keeping everything else. With a backupAgent declared and no fullBackupOnly, cloud backup is the agent payload; the rules govern device transfer and remain correct if the agent is removed. Host verification: AppBackupAgentTest (5 tests) proves manifest and agent wiring (real codec, db name, datastores, watch files), parses the extraction rules for the excludes in both sections, round-trips the full payload (plaintext DB stand-in + datastores + watch JSON) through BackupHelper as BaseBackupAgent drives it, and proves a failed codec import leaves the live DB untouched. The codec's native transform and the KeyStore unwrap cannot run on a host JVM; that remainder is the codec's build-verify-swap re-encryption, covered on device by :library:room's DeviceDatabaseTest. Verified: ./gradlew :launcher:lint :launcher:lintVitalRelease :launcher:testDevUnitTest --max-workers=128 (424 tests, 0 failures; baseline at 30be4a93a green, lintVitalRelease SKIPPED by AGP in both). :launcher:ktlintCheck fails pre-existing across the module (untouched files included) and is not part of the gate.
Diff
launcher/AGENTS.md
diff --git a/launcher/AGENTS.md b/launcher/AGENTS.mdindex cdc905545b..708db5560f 100644--- a/launcher/AGENTS.md+++ b/launcher/AGENTS.md@@ -108,6 +108,7 @@ neither runs on the wrong form factor. - com/vayunmathur/launcher/platform/IconCache.kt - com/vayunmathur/launcher/platform/ActivityBridge.kt - com/vayunmathur/launcher/platform/LauncherPrivilege.kt+- com/vayunmathur/launcher/platform/AppBackupAgent.kt — platform backup: SQLCipher DB via `SqlCipherDbCodec` plaintext round-trip (raw DB + `secure_prefs` excluded in `res/xml/data_extraction_rules.xml`); payload also carries `datastore_default`, `tvlauncher_config` and the watch JSON files - com/vayunmathur/launcher/platform/FormFactor.kt — watch detection (`FEATURE_WATCH`) - com/vayunmathur/launcher/platform/InstalledApps.kt — watch installed-app enumeration + settings targets ### Watch experience (ui/ + data/ + domain/ + platform/ + sync/)
launcher/src/main/AndroidManifest.xml
diff --git a/launcher/src/main/AndroidManifest.xml b/launcher/src/main/AndroidManifest.xmlindex bf0e5ef8db..5c127774b0 100644--- a/launcher/src/main/AndroidManifest.xml+++ b/launcher/src/main/AndroidManifest.xml@@ -78,6 +78,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"
launcher/src/main/java/com/vayunmathur/launcher/data/LauncherDatabase.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherDatabase.kt b/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherDatabase.ktindex 553396a6d0..86725bd6ab 100644--- a/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherDatabase.kt+++ b/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherDatabase.kt@@ -1,5 +1,6 @@ package com.vayunmathur.launcher.data +import android.content.Context import androidx.room3.ColumnTypeConverters import androidx.room3.Dao import androidx.room3.Database@@ -10,10 +11,38 @@ import androidx.room3.Upsert import androidx.room3.migration.Migration import com.vayunmathur.launcher.domain.CONTAINER_DESKTOP import com.vayunmathur.launcher.domain.CONTAINER_HOTSEAT+import com.vayunmathur.library.util.DatabaseHelper import com.vayunmathur.library.util.DatabaseMigrations import com.vayunmathur.library.util.DefaultConverters import kotlinx.coroutines.flow.Flow +/** On-disk name of the SQLCipher workspace database (see [LauncherRepository]). */+const val LAUNCHER_DB_NAME = "launcher-db"++/**+ * Backup config shared by [com.vayunmathur.launcher.platform.AppBackupAgent]:+ * the database name plus the passphrase for *this* device.+ *+ * The passphrase is resolved exactly the way the Room builder resolves it:+ * unwrapped with this device's AndroidKeyStore key when one exists, and+ * minted (new key + new wrapped passphrase) when it does not. The minting+ * branch is what makes restore work on a fresh device, where the backup+ * agent runs before the app has ever opened the database: the codec+ * re-encrypts the restored plaintext under the minted passphrase, and the+ * first Room open afterwards unwraps that same passphrase. A bare unwrap+ * would throw there and the layout would be lost.+ */+fun launcherDbConfigs(context: Context): List<Pair<String, String>> {+ val helper = DatabaseHelper(context)+ val passphrase = if (helper.isKeyGenerated()) {+ helper.getPassphrase()+ } else {+ helper.generateKey()+ helper.createAndStorePassphrase(helper.getCipherForEncryption())+ }+ return listOf(LAUNCHER_DB_NAME to passphrase)+}+ /** Contract for launcher item dao. */ @Dao interface LauncherItemDao {
launcher/src/main/java/com/vayunmathur/launcher/data/LauncherRepository.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherRepository.kt b/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherRepository.ktindex f8c5631ac3..c31e7ba3be 100644--- a/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherRepository.kt+++ b/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherRepository.kt@@ -411,7 +411,7 @@ class LauncherRepository private constructor(context: Context) : * Explicit, because [RoomRepository]'s default is `"passwords-db"` — a default that * predates it being shared and that `clock` still inherits by accident. */- private const val DB_NAME = "launcher-db"+ private const val DB_NAME = LAUNCHER_DB_NAME @Volatile private var instance: LauncherRepository? = null
launcher/src/main/java/com/vayunmathur/launcher/platform/AppBackupAgent.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/platform/AppBackupAgent.kt b/launcher/src/main/java/com/vayunmathur/launcher/platform/AppBackupAgent.ktnew file mode 100644index 0000000000..80d3e0c005--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/platform/AppBackupAgent.kt@@ -0,0 +1,52 @@+package com.vayunmathur.launcher.platform++import com.vayunmathur.launcher.data.launcherDbConfigs+import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.BaseBackupAgent+import java.io.File++/**+ * Platform backup for the launcher, following the weather pattern.+ *+ * The workspace database is SQLCipher-encrypted under a passphrase wrapped+ * by this device's non-exportable AndroidKeyStore key, so the raw file can+ * never be copied to another device (it would be unopenable there). Instead+ * this agent exports it to plaintext inside the backup payload via+ * [SqlCipherDbCodec] and re-encrypts it under the new device's passphrase+ * on restore. Everything else worth keeping — the shared preferences+ * DataStore (grid shape, icon scale, labels, drawer layout, launch counts,+ * seeded flag), the TV row order and the watch favorites/recents JSON —+ * travels in the same payload; `data_extraction_rules.xml` carries those+ * same files raw for device-to-device transfer and excludes only the raw+ * database and its passphrase.+ */+class AppBackupAgent : BaseBackupAgent() {+ override val dbCodec = SqlCipherDbCodec++ override val dbConfigs: List<Pair<String, String>>+ get() = launcherDbConfigs(this)++ override val datastoreNames: List<String> =+ listOf(DATASTORE_DEFAULT_NAME, TV_DATASTORE_NAME)++ override val extraFiles: List<File>+ get() = listOf(+ File(filesDir, WEAR_FAVORITES_FILE),+ File(filesDir, WEAR_RECENTS_FILE),+ )++ /** Backup payload constants for [AppBackupAgent]. */+ companion object {+ /** DataStoreUtils' shared store (`filesDir/datastore_default.preferences_pb`). */+ const val DATASTORE_DEFAULT_NAME = "datastore_default"++ /** TvPrefs' store (`filesDir/datastore/tvlauncher_config.preferences_pb`). */+ const val TV_DATASTORE_NAME = "tvlauncher_config"++ /** Watch favorites snapshot (see WearLauncherStore). */+ const val WEAR_FAVORITES_FILE = "wear-launcher-favorites.json"++ /** Watch-local recents (see WearLauncherStore). */+ const val WEAR_RECENTS_FILE = "wear-launcher-recents.json"+ }+}
launcher/src/main/res/xml/data_extraction_rules.xml
diff --git a/launcher/src/main/res/xml/data_extraction_rules.xml b/launcher/src/main/res/xml/data_extraction_rules.xmlindex 9f98c07beb..4c50b4104c 100644--- a/launcher/src/main/res/xml/data_extraction_rules.xml+++ b/launcher/src/main/res/xml/data_extraction_rules.xml@@ -2,31 +2,70 @@ <!-- Launcher. Audited state: - - launcher-db (SQLCipher, databases/) — the home screen layout: one row per icon,- folder, widget and pinned shortcut, holding the container/page/cell/span plus the- target package, class and user serial. No content from the apps themselves.- - preferences, via DataStoreUtils into filesDir/datastore_default.preferences_pb- (LauncherViewModel) — grid size, icon scale, whether labels are shown.+ - launcher-db (SQLCipher, databases/) - the home screen layout: one row+ per icon, folder, widget and pinned shortcut, holding the+ container/page/cell/span plus the target package, class and user+ serial. No content from the apps themselves. Real user data, worth+ restoring onto a new device.+ - datastore_default.preferences_pb (DataStoreUtils, filesDir root) -+ grid size, icon scale, labels, drawer layout, launch counts, seeded+ flag.+ - tvlauncher_config (DataStore, files/datastore/) - TV row order.+ - wear-launcher-favorites.json / wear-launcher-recents.json (filesDir)+ - watch favorites snapshot and watch-local recents.+ - secure_prefs.xml - the SQLCipher passphrase, wrapped by a+ non-exportable AndroidKeyStore key. - No file I/O, nothing on external storage. The layout is worth restoring onto a new- device and reveals nothing beyond which apps are installed, which the package list- already says. Widget ids are the exception: they are allocated by the system- AppWidgetHost and are meaningless in another install, so a restored widget row is- dropped by reconciliation on first launch rather than rendered. Back everything up.+ launcher-db is excluded from both sections: it is SQLCipher-encrypted+ under a passphrase wrapped by the old device's non-exportable+ AndroidKeyStore key. That key never leaves the device, so a restored+ copy of this file cannot be opened - the Room builder mints a fresh key+ and passphrase, skips the already-encrypted file, and Room throws. The+ previous rules included the raw database (and secure_prefs) in both+ cloud backup and device transfer, which traded a clean first launch+ for a crash and lost the layout anyway.++ The layout still migrates: launcher declares its own BackupAgent+ (.platform.AppBackupAgent), which uses SqlCipherDbCodec to export the+ DB to plaintext inside the backup payload and re-encrypt it under the+ new device's passphrase on restore (minted there if none exists yet).+ The same payload carries both DataStores and the watch JSON files.+ Widget ids in restored rows are allocated by the system AppWidgetHost+ and are meaningless in another install, so a restored widget row is+ dropped by reconciliation on first launch rather than rendered.++ SCOPE: launcher 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 payload described above. The+ rules below govern device-transfer, and are the correct control if+ the backupAgent is ever removed: everything except the raw database,+ its sidecars and the wrapped passphrase transfers as raw files. --> <data-extraction-rules>+ <!-- Not consulted while android:backupAgent is declared; see SCOPE above. --> <cloud-backup> <include domain="root" path="." /> <include domain="file" path="." /> <include domain="database" path="." />+ <exclude domain="database" path="launcher-db" />+ <exclude domain="database" path="launcher-db-wal" />+ <exclude domain="database" path="launcher-db-shm" />+ <exclude domain="database" path="launcher-db-journal" /> <include domain="sharedpref" path="." />+ <exclude domain="sharedpref" path="secure_prefs.xml" /> <include domain="external" path="." /> </cloud-backup> <device-transfer> <include domain="root" path="." /> <include domain="file" path="." /> <include domain="database" path="." />+ <exclude domain="database" path="launcher-db" />+ <exclude domain="database" path="launcher-db-wal" />+ <exclude domain="database" path="launcher-db-shm" />+ <exclude domain="database" path="launcher-db-journal" /> <include domain="sharedpref" path="." />+ <exclude domain="sharedpref" path="secure_prefs.xml" /> <include domain="external" path="." /> </device-transfer> </data-extraction-rules>
launcher/src/test/java/com/vayunmathur/launcher/platform/AppBackupAgentTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/platform/AppBackupAgentTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/platform/AppBackupAgentTest.ktnew file mode 100644index 0000000000..6c83c0aa7b--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/platform/AppBackupAgentTest.kt@@ -0,0 +1,193 @@+package com.vayunmathur.launcher.platform++import android.content.Context+import android.content.pm.ApplicationInfo+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.launcher.R+import com.vayunmathur.launcher.data.LAUNCHER_DB_NAME+import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.BackupHelper+import com.vayunmathur.library.util.DbBackupCodec+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.File+import java.util.zip.ZipInputStream+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertSame+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.xmlpull.v1.XmlPullParser++/**+ * Platform-backup wiring for the launcher.+ *+ * Host limit, stated plainly: the SQLCipher codec's transform and the+ * AndroidKeyStore passphrase unwrap cannot run on a host JVM (no native+ * SQLCipher library, no AndroidKeyStore provider), so no host test can+ * execute the encrypted export/import itself. What can be proven here,+ * and is: the manifest names this agent with backup allowed; the agent+ * wires the real codec, the real database name, both DataStores and the+ * watch files; the extraction rules exclude the raw database and its+ * passphrase from both cloud and device transfer; the full payload+ * (plaintext DB stand-in + DataStores + watch JSON) round-trips through+ * BackupHelper exactly as BaseBackupAgent drives it; and a codec import+ * that cannot proceed leaves the live database byte-for-byte untouched.+ * The remaining device-only step is SqlCipherDbCodec's verified+ * build-verify-swap re-encryption under the restored device's passphrase,+ * covered on device by :library:room's DeviceDatabaseTest.+ */+@RunWith(RobolectricTestRunner::class)+class AppBackupAgentTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ private fun agent(): AppBackupAgent =+ Robolectric.buildBackupAgent(AppBackupAgent::class.java).create().get()++ @Test fun manifestDeclaresBackupAgentWithBackupAllowed() {+ val info = ctx.packageManager.getApplicationInfo(ctx.packageName, 0)+ assertTrue(info.flags and ApplicationInfo.FLAG_ALLOW_BACKUP != 0, "allowBackup")+ assertEquals(AppBackupAgent::class.java.name, info.backupAgentName)+ }++ @Test fun agentWiresCodecDatabaseDatastoresAndWatchFiles() {+ val agent = agent()+ assertSame(SqlCipherDbCodec, agent.dbCodec)+ assertEquals("launcher-db", LAUNCHER_DB_NAME)+ assertEquals(+ listOf(AppBackupAgent.DATASTORE_DEFAULT_NAME, AppBackupAgent.TV_DATASTORE_NAME),+ agent.datastoreNames,+ )+ assertEquals(+ listOf(AppBackupAgent.WEAR_FAVORITES_FILE, AppBackupAgent.WEAR_RECENTS_FILE),+ agent.extraFiles.map { it.name },+ )+ assertTrue(agent.extraFiles.all { it.parentFile == ctx.filesDir })+ assertNotNull(agent.dbCodec)+ }++ @Test fun extractionRulesExcludeRawDatabaseAndPassphraseEverywhere() {+ val excludes = mutableSetOf<String>()+ val includes = mutableSetOf<String>()+ val parser = ctx.resources.getXml(R.xml.data_extraction_rules)+ var event = parser.eventType+ var section = ""+ while (event != XmlPullParser.END_DOCUMENT) {+ if (event == XmlPullParser.START_TAG) {+ when (parser.name) {+ "cloud-backup", "device-transfer" -> section = parser.name+ "exclude" -> excludes += "$section/${parser.getAttributeValue(null, "domain")}" ++ "/${parser.getAttributeValue(null, "path")}"+ "include" -> includes += "$section/${parser.getAttributeValue(null, "domain")}"+ }+ }+ event = parser.next()+ }+ for (s in listOf("cloud-backup", "device-transfer")) {+ for (path in listOf("launcher-db", "launcher-db-wal", "launcher-db-shm", "launcher-db-journal")) {+ assertTrue("$s/database/$path" in excludes, "missing exclude $s $path")+ }+ assertTrue("$s/sharedpref/secure_prefs.xml" in excludes, "missing secure_prefs exclude $s")+ assertTrue("$s/file" in includes, "files must still transfer $s")+ assertTrue("$s/database" in includes, "database domain kept (excludes carve out the DB) $s")+ }+ }++ /** Stands in for SqlCipherDbCodec's plaintext export/import (native, host-unavailable). */+ private class FakeCodec : DbBackupCodec {+ var exportedDbName: String? = null+ var importedBytes: ByteArray? = null+ override fun exportDatabase(context: Context, dbName: String, password: String, outputFile: File) {+ exportedDbName = dbName+ outputFile.parentFile?.mkdirs()+ outputFile.writeBytes(PLAIN_DB)+ }+ override fun importDatabase(context: Context, dbName: String, password: String, inputFile: File) {+ importedBytes = inputFile.readBytes()+ }+ companion object { val PLAIN_DB = "plaintext-launcher-db".toByteArray() }+ }++ @Test fun backupPayloadRoundTripsThroughHelper() {+ val agent = agent()+ val defaultPrefs = File(ctx.filesDir, "datastore_default.preferences_pb")+ val tvPrefs = File(ctx.filesDir, "datastore/tvlauncher_config.preferences_pb")+ val favorites = File(ctx.filesDir, AppBackupAgent.WEAR_FAVORITES_FILE)+ val recents = File(ctx.filesDir, AppBackupAgent.WEAR_RECENTS_FILE)+ tvPrefs.parentFile?.mkdirs()+ defaultPrefs.writeText("default-prefs")+ tvPrefs.writeText("tv-prefs")+ favorites.writeText("favorites-json")+ recents.writeText("recents-json")++ val codec = FakeCodec()+ val zipBytes = ByteArrayOutputStream().also { out ->+ BackupHelper.performFullBackup(+ ctx,+ listOf(LAUNCHER_DB_NAME to "host-passphrase"),+ agent.datastoreNames,+ agent.prefNames,+ agent.extraFiles,+ out,+ codec,+ )+ }.toByteArray()+ assertEquals(LAUNCHER_DB_NAME, codec.exportedDbName)++ val entries = ZipInputStream(ByteArrayInputStream(zipBytes)).use { zis ->+ generateSequence { zis.nextEntry?.name }.toSet()+ }+ assertTrue("launcher-db.db" in entries, "plaintext DB in payload: $entries")+ assertTrue("datastore_default.preferences_pb" in entries, "default prefs in payload: $entries")+ assertTrue("tvlauncher_config.preferences_pb" in entries, "tv prefs in payload: $entries")+ assertTrue(AppBackupAgent.WEAR_FAVORITES_FILE in entries, "favorites in payload: $entries")+ assertTrue(AppBackupAgent.WEAR_RECENTS_FILE in entries, "recents in payload: $entries")++ listOf(defaultPrefs, tvPrefs, favorites, recents).forEach { it.delete() }+ BackupHelper.performFullRestore(+ ctx,+ listOf(LAUNCHER_DB_NAME to "host-passphrase"),+ agent.datastoreNames,+ agent.prefNames,+ agent.extraFiles.associateBy { it.name },+ ByteArrayInputStream(zipBytes),+ codec,+ )+ assertEquals("default-prefs", defaultPrefs.readText())+ assertEquals("tv-prefs", tvPrefs.readText())+ assertEquals("favorites-json", favorites.readText())+ assertEquals("recents-json", recents.readText())+ assertTrue(FakeCodec.PLAIN_DB.contentEquals(codec.importedBytes!!), "DB payload round-trips")+ }++ @Test fun failedCodecImportLeavesLiveDatabaseUntouched() {+ val dbFile = ctx.getDatabasePath(LAUNCHER_DB_NAME)+ dbFile.parentFile?.mkdirs()+ val liveBytes = ByteArray(64) { 7 }+ dbFile.writeBytes(liveBytes)+ val input = File(ctx.cacheDir, "launcher-restore-plaintext.db").apply {+ writeBytes(ByteArray(64) { 0x55 })+ }+ try {+ // Host JVM cannot load native SQLCipher, so this cannot proceed;+ // on a device a corrupt input fails verification the same way.+ // Either failure must leave the live database untouched.+ runCatching {+ SqlCipherDbCodec.importDatabase(ctx, LAUNCHER_DB_NAME, "host-passphrase", input)+ }+ assertTrue(dbFile.exists())+ assertTrue(liveBytes.contentEquals(dbFile.readBytes()), "live DB replaced by failed import")+ 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()+ input.delete()+ }+ }+}