youpipe: make backup/restore safe and data-preserving
- Commit
c345a93400a5bd66b377f4bac2fc24cebb579102- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-04 22:02 UTC (1 day ago)
- Parents
79d1469
The device-transfer rules carried the raw SQLCipher database (passwords-db) plus the passphrase wrapped by the old device's non-exportable AndroidKeyStore key, so a restored database could not be opened on the new device. Cloud backup only carried the settings DataStore, losing subscriptions and history entirely. Follow the weather precedent (BaseBackupAgent + SqlCipherDbCodec), adapted to YouPipe's mixed database: - Declare .platform.AppBackupAgent in the manifest (no fullBackupOnly, so cloud backup is key/value): its zip carries the settings DataStore and the database as a plaintext codec export, re-encrypted under the new device's key on restore. - YouPipeDbBackupCodec wraps SqlCipherDbCodec and strips the cache tables (SubscriptionVideo feed cache, CachedRelatedVideo, RecommendationImpression, DownloadedVideo rows pointing at excluded external files) from the plaintext payload in both directions; subscriptions, categories, history, playlists and tuned recommendation preferences are preserved. - youpipeDbConfigs names the DB explicitly (DB_NAME passed to RoomRepository, same file as before) and mints a passphrase on a fresh restore target, where no wrapped passphrase exists yet. - data_extraction_rules: both sections now exclude the raw database and sidecars, secure_prefs and the SABR token/diagnostic prefs, so device transfer stays coherent with the agent and a raw file copy can never shadow the re-keyed restore. Downloads and the fetched SABR policy files remain excluded. Verified: ./gradlew :youpipe:lint :youpipe:lintVitalRelease :youpipe:testDevUnitTest passes (baseline at 30be4a93a also passed, so no pre-existing failures are masked). The new YouPipeBackupAgentTest (9 tests) proves the manifest/agent wiring, the preserved/excluded partition against the committed Room schema, the rules, a BackupHelper backup/restore zip round-trip of the settings file through the agent's exact configs+codec, and that failed/corrupt imports leave the live DB untouched. The SQLCipher native transform cannot run on a host JVM; exporting a real encrypted DB, stripping rows on device and Room opening the re-encrypted restore remain device-only (shared codec path with weather).
Diff
youpipe/AGENTS.md
diff --git a/youpipe/AGENTS.md b/youpipe/AGENTS.mdindex dc28c3e6bc..e2228a0788 100644--- a/youpipe/AGENTS.md+++ b/youpipe/AGENTS.md@@ -31,7 +31,7 @@ _Install: ./install youpipe (dev by default)._ - com/vayunmathur/youpipe/Navigation.kt - com/vayunmathur/youpipe/YouPipeApplication.kt ### data/ — subscriptions, playlists, recommendations (Room)-- com/vayunmathur/youpipe/data/SubscriptionDatabase.kt+- com/vayunmathur/youpipe/data/SubscriptionDatabase.kt — also `DB_NAME`, the preserved/excluded backup table lists and `youpipeDbConfigs` (mints the SQLCipher passphrase on a fresh restore target) - com/vayunmathur/youpipe/data/SubscriptionRepository.kt - com/vayunmathur/youpipe/data/Subscription.kt - com/vayunmathur/youpipe/data/SubscriptionVideo.kt@@ -99,6 +99,8 @@ _Install: ./install youpipe (dev by default)._ - com/vayunmathur/youpipe/ui/ManageInterestsPage.kt - com/vayunmathur/youpipe/ui/DataSettingsPage.kt ### platform/ — ViewModel, playback, downloads, sync+- com/vayunmathur/youpipe/platform/AppBackupAgent.kt — key/value backup agent (manifest `backupAgent`, no `fullBackupOnly`): settings DataStore + codec-exported database zip+- com/vayunmathur/youpipe/platform/YouPipeDbBackupCodec.kt — `SqlCipherDbCodec` round-trip (plaintext export, re-encrypt under the new device's key) with the cache tables in `YOUPIPE_EXCLUDED_TABLES` stripped in both directions; never back up the raw `passwords-db` file or `secure_prefs` (see `res/xml/data_extraction_rules.xml`) - com/vayunmathur/youpipe/platform/YouPipeViewModel.kt - com/vayunmathur/youpipe/platform/YouPipeUiContract.kt - com/vayunmathur/youpipe/platform/YouPipeVideoLoading.kt
youpipe/src/main/AndroidManifest.xml
diff --git a/youpipe/src/main/AndroidManifest.xml b/youpipe/src/main/AndroidManifest.xmlindex c2a78a5f40..074a1521eb 100644--- a/youpipe/src/main/AndroidManifest.xml+++ b/youpipe/src/main/AndroidManifest.xml@@ -38,6 +38,7 @@ <application android:name=".YouPipeApplication" android:allowBackup="true"+ android:backupAgent=".platform.AppBackupAgent" android:banner="@drawable/tv_banner" android:dataExtractionRules="@xml/data_extraction_rules" android:icon="@mipmap/ic_launcher"
youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionDatabase.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionDatabase.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionDatabase.ktindex d9a9c24dc1..e9fa192956 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionDatabase.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionDatabase.kt@@ -1,5 +1,6 @@ package com.vayunmathur.youpipe.data +import android.content.Context import androidx.room3.ColumnTypeConverters import androidx.room3.Dao import androidx.room3.Database@@ -9,9 +10,60 @@ import androidx.room3.RoomDatabase import androidx.room3.Upsert import androidx.room3.migration.Migration import androidx.sqlite.execSQL+import com.vayunmathur.library.util.DatabaseHelper import com.vayunmathur.library.util.DefaultConverters import kotlinx.coroutines.flow.Flow +/** On-device file name of the [SubscriptionDatabase] (the RoomRepository default). */+const val DB_NAME = "passwords-db"++/**+ * Tables holding user data worth carrying to a new device: subscriptions and+ * their categories, watch history (incl. resume positions), playlists, and the+ * user-tuned recommendation/channel/keyword preferences.+ */+val YOUPIPE_PRESERVED_TABLES: Set<String> = setOf(+ "Subscription",+ "SubscriptionCategory",+ "HistoryVideo",+ "Playlist",+ "PlaylistItem",+ "RecommendationPreferences",+ "ChannelPreference",+ "KeywordPreference",+)++/**+ * Tables holding regenerable caches, stripped from the plaintext backup export+ * by [com.vayunmathur.youpipe.platform.YouPipeDbBackupCodec]: the subscription+ * feed cache (refetched by SubscriptionFetchTask), related-video cache,+ * recommendation impression tracking, and download rows whose files live in+ * the excluded external downloads directory (restored rows would dangle).+ */+val YOUPIPE_EXCLUDED_TABLES: Set<String> = setOf(+ "SubscriptionVideo",+ "DownloadedVideo",+ "CachedRelatedVideo",+ "RecommendationImpression",+)++/**+ * Backup config shared by [com.vayunmathur.youpipe.platform.AppBackupAgent].+ * Mints a passphrase on first use (mirroring the database builder): on a fresh+ * restore target no key exists yet, and without one the restored database+ * could not be re-encrypted under the new device's key.+ */+fun youpipeDbConfigs(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(DB_NAME to passphrase)+}+ val MIGRATION_1_2 = Migration(1, 2) { it.execSQL(""" CREATE TABLE IF NOT EXISTS `DownloadedVideo` (
youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionRepository.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionRepository.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionRepository.ktindex e62fd8c168..6defdd93e4 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionRepository.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionRepository.kt@@ -29,7 +29,7 @@ class SubscriptionRepository internal constructor( * the SQLCipher file every app database is — is used exactly as before. */ private val injectedDatabase: SubscriptionDatabase? = null,-) : RoomRepository<SubscriptionDatabase>(context, SubscriptionDatabase::class) {+) : RoomRepository<SubscriptionDatabase>(context, SubscriptionDatabase::class, DB_NAME) { /** The database every DAO below comes from: injected in tests, else [db]. */ private val database: SubscriptionDatabase get() = injectedDatabase ?: db
youpipe/src/main/java/com/vayunmathur/youpipe/platform/AppBackupAgent.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/platform/AppBackupAgent.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/platform/AppBackupAgent.ktnew file mode 100644index 0000000000..60f394a76c--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/platform/AppBackupAgent.kt@@ -0,0 +1,21 @@+package com.vayunmathur.youpipe.platform++import com.vayunmathur.library.util.BaseBackupAgent+import com.vayunmathur.youpipe.data.youpipeDbConfigs++/**+ * Key/value backup agent (declared in the manifest without fullBackupOnly,+ * the weather precedent): cloud backup is this agent's zip — the subscription+ * database exported to plaintext by [YouPipeDbBackupCodec] (cache tables+ * stripped, re-encrypted under the new device's key on restore) plus the+ * settings DataStore. The SABR token/diagnostic prefs and the downloaded+ * files are deliberately absent: they are device-bound or re-downloadable.+ */+class AppBackupAgent : BaseBackupAgent() {+ override val dbCodec = YouPipeDbBackupCodec++ override val dbConfigs: List<Pair<String, String>>+ get() = youpipeDbConfigs(this)++ override val datastoreNames: List<String> = listOf("datastore_default")+}
youpipe/src/main/java/com/vayunmathur/youpipe/platform/YouPipeDbBackupCodec.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/platform/YouPipeDbBackupCodec.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/platform/YouPipeDbBackupCodec.ktnew file mode 100644index 0000000000..76b4d9df97--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/platform/YouPipeDbBackupCodec.kt@@ -0,0 +1,94 @@+package com.vayunmathur.youpipe.platform++import android.content.Context+import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.room.loadSqlCipher+import com.vayunmathur.library.util.DbBackupCodec+import com.vayunmathur.youpipe.data.YOUPIPE_EXCLUDED_TABLES+import net.zetetic.database.sqlcipher.SQLiteDatabase+import java.io.File++/**+ * [DbBackupCodec] for YouPipe: the [SqlCipherDbCodec] plaintext round-trip+ * (export the SQLCipher database to plaintext on the old device, re-encrypt+ * under the new device's key on restore), with the cache tables in+ * [YOUPIPE_EXCLUDED_TABLES] stripped from the plaintext payload in both+ * directions. User data (subscriptions, history, playlists, tuned+ * preferences) crosses devices; regenerable caches never leave the device+ * and never land on the new one — including from a payload written by a+ * version that did not strip them.+ *+ * Stripping happens only on the plaintext temp files the codec owns. A+ * payload that cannot be opened aborts the import before the delegate's+ * verified swap, so the live database stays untouched.+ */+object YouPipeDbBackupCodec : DbBackupCodec {+ override fun exportDatabase(context: Context, dbName: String, password: String, outputFile: File) {+ val parent = outputFile.parentFile+ if (parent == null) {+ SqlCipherDbCodec.exportDatabase(context, dbName, password, outputFile)+ return+ }+ parent.mkdirs()+ val raw = File(parent, "${outputFile.name}.raw")+ try {+ SqlCipherDbCodec.exportDatabase(context, dbName, password, raw)+ if (!raw.exists() || raw.length() == 0L) {+ // No source database (or an empty export): produce no output,+ // matching the delegate, so the backup carries no DB entity.+ outputFile.delete()+ return+ }+ stripExcludedTables(raw)+ if (outputFile.exists()) outputFile.delete()+ if (!raw.renameTo(outputFile)) {+ raw.copyTo(outputFile, overwrite = true)+ raw.delete()+ }+ } finally {+ deleteWithSidecars(raw)+ }+ }++ override fun importDatabase(context: Context, dbName: String, password: String, inputFile: File) {+ // No-op for a missing/empty input: the delegate then fails before+ // touching the live database, exactly as without this codec.+ stripExcludedTables(inputFile)+ SqlCipherDbCodec.importDatabase(context, dbName, password, inputFile)+ }++ /**+ * Deletes every [YOUPIPE_EXCLUDED_TABLES] row present in the plaintext+ * SQLite file [plainDb] and vacuums, so freed cache content does not+ * survive in unused pages. Missing/empty files are left alone.+ */+ internal fun stripExcludedTables(plainDb: File) {+ if (!plainDb.exists() || plainDb.length() == 0L) return+ loadSqlCipher()+ val db = SQLiteDatabase.openDatabase(+ plainDb.canonicalPath,+ "",+ null,+ SQLiteDatabase.OPEN_READWRITE,+ null,+ )+ try {+ val present = mutableSetOf<String>()+ db.rawQuery("SELECT name FROM sqlite_master WHERE type = 'table'", null)?.use { cursor ->+ while (cursor.moveToNext()) present += cursor.getString(0)+ }+ val stripped = YOUPIPE_EXCLUDED_TABLES.intersect(present)+ stripped.forEach { table -> db.rawExecSQL("DELETE FROM \"$table\"") }+ if (stripped.isNotEmpty()) db.rawExecSQL("VACUUM")+ } finally {+ db.close()+ }+ }++ private fun deleteWithSidecars(file: File) {+ file.delete()+ File("${file.path}-wal").delete()+ File("${file.path}-shm").delete()+ File("${file.path}-journal").delete()+ }+}
youpipe/src/main/res/xml/data_extraction_rules.xml
diff --git a/youpipe/src/main/res/xml/data_extraction_rules.xml b/youpipe/src/main/res/xml/data_extraction_rules.xmlindex 5525a3d42f..bf560062f6 100644--- a/youpipe/src/main/res/xml/data_extraction_rules.xml+++ b/youpipe/src/main/res/xml/data_extraction_rules.xml@@ -1,34 +1,77 @@ <?xml version="1.0" encoding="utf-8"?> <!-- YouTube client. Overrides the permissive default in the shared :library module. - Storage audit:- database passwords-db Room. The buildDatabase() default dbName is used because- MainActivity calls buildDatabase<SubscriptionDatabase>() with- no name; the file is per-app so the name is only confusing.- Holds Subscription, SubscriptionVideo, HistoryVideo,- DownloadedVideo, CachedRelatedVideo, RecommendationImpression- and the recommendation/channel/keyword preference tables.- sharedpref sabr_* PoToken caches and playback diagnostics. Session tokens bound- to this device and install; useless and unsafe off-device.+ Storage audited:+ database passwords-db Room (SubscriptionDatabase). User data worth restoring:+ Subscription + categories, HistoryVideo (incl. resume+ positions), Playlist/PlaylistItem and the tuned+ recommendation/channel/keyword preference tables. Cache+ tables in the same file (SubscriptionVideo feed cache,+ CachedRelatedVideo, RecommendationImpression, and+ DownloadedVideo rows pointing at excluded external files)+ are stripped from the backup payload, not the device.+ sharedpref secure_prefs SQLCipher passphrase wrapped by a non-exportable+ AndroidKeyStore key. Never transferable.+ sharedpref sabr_* PoToken caches and playback diagnostics. Session tokens+ bound to this device and install; useless and unsafe+ off-device. file datastore_default.preferences_pb Settings only: sponsorblock_enabled + categories,- dearrow_enabled, youtube_language, default page.+ dearrow_enabled, youtube_language, default page, speeds. file sabr-cloud-policy.bin/.rev Fetched playback policy, refetched on demand. external downloads/ Downloaded video files. Large and re-downloadable. - Cloud backup is an allowlist holding just the settings DataStore. Subscriptions are worth- restoring but sit in the same Room file as watch history and per-video recommendation- impressions, so the whole database is device-transfer only. -->+ The raw database file must never travel as a file: it is SQLCipher-encrypted+ under a passphrase wrapped by the old device's non-exportable AndroidKeyStore+ key, so a restored copy cannot be opened on the new device (a fresh key and+ passphrase are minted there and Room rejects the foreign file). Instead the+ app declares android:backupAgent=".platform.AppBackupAgent" (no+ fullBackupOnly, so cloud backup is key/value): the agent exports the+ database to plaintext inside its backup zip via YouPipeDbBackupCodec+ (cache tables stripped) and re-encrypts it under the new device's key on+ restore, and also carries the settings DataStore.++ SCOPE: while the backupAgent is declared, the <cloud-backup> section below+ is NOT consulted for cloud backup; it is the correct fallback if the agent+ is ever removed. The <device-transfer> section governs device-to-device+ file transfer and must stay coherent with the agent: the same plaintext+ codec round-trip carries the database, the same settings file is included,+ and the raw database, its sidecars, the wrapped passphrase and the SABR+ caches are excluded so a raw file copy can never shadow the re-keyed+ restore. --> <data-extraction-rules> <cloud-backup>- <include domain="file" path="datastore_default.preferences_pb" />- </cloud-backup>- <device-transfer>- <exclude domain="external" path="downloads" />+ <include domain="file" path="." />+ <include domain="database" path="." />+ <include domain="sharedpref" path="." />+ <include domain="external" 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" />+ <exclude domain="sharedpref" path="sabr_local_dom_video_token_cache.xml" />+ <exclude domain="sharedpref" path="sabr_webpo_video_token_cache.xml" />+ <exclude domain="sharedpref" path="sabr_playback_diagnostics.xml" /> <exclude domain="file" path="sabr-cloud-policy.bin" /> <exclude domain="file" path="sabr-cloud-policy.rev" />+ <exclude domain="external" path="downloads" />+ </cloud-backup>+ <device-transfer>+ <include domain="file" path="." />+ <include domain="database" path="." />+ <include domain="sharedpref" path="." />+ <include domain="external" 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" /> <exclude domain="sharedpref" path="sabr_local_dom_video_token_cache.xml" /> <exclude domain="sharedpref" path="sabr_webpo_video_token_cache.xml" /> <exclude domain="sharedpref" path="sabr_playback_diagnostics.xml" />+ <exclude domain="file" path="sabr-cloud-policy.bin" />+ <exclude domain="file" path="sabr-cloud-policy.rev" />+ <exclude domain="external" path="downloads" /> </device-transfer> </data-extraction-rules>
youpipe/src/test/java/com/vayunmathur/youpipe/platform/YouPipeBackupAgentTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/platform/YouPipeBackupAgentTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/platform/YouPipeBackupAgentTest.ktnew file mode 100644index 0000000000..f99f27dcfe--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/platform/YouPipeBackupAgentTest.kt@@ -0,0 +1,229 @@+package com.vayunmathur.youpipe.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.BackupHelper+import com.vayunmathur.library.util.DatabaseHelper+import com.vayunmathur.testsupport.FakeAndroidKeyStore+import com.vayunmathur.youpipe.data.DB_NAME+import com.vayunmathur.youpipe.data.YOUPIPE_EXCLUDED_TABLES+import com.vayunmathur.youpipe.data.YOUPIPE_PRESERVED_TABLES+import com.vayunmathur.youpipe.data.youpipeDbConfigs+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotEquals+import kotlin.test.assertTrue+import kotlin.test.fail++/**+ * Host-strongest backup/restore coverage for YouPipe.+ *+ * The SQLCipher native transform itself cannot run on a host JVM (the+ * .so cannot load), so this test proves everything around it: the manifest+ * declares the agent, the agent wires the sanitising codec + the shared+ * db configs + the settings datastore, the preserved/excluded table lists+ * partition the Room schema, the extraction rules never carry the raw+ * database or the wrapped passphrase, the backup zip round-trips the+ * settings file through the exact BackupHelper + codec the agent uses+ * (with no database file present, the codec export is a no-op), and a+ * failed import leaves the live database byte-for-byte untouched.+ *+ * Remainder that only a device can prove: SqlCipherDbCodec exporting a+ * real encrypted passwords-db to plaintext, stripExcludedTables deleting+ * cache rows from that plaintext, and the re-encrypted restore opening+ * under Room on the target device. That native path is shared with+ * weather (SqlCipherDbCodec) and covered on-device there.+ */+@RunWith(RobolectricTestRunner::class)+class YouPipeBackupAgentTest {+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ companion object {+ @org.junit.BeforeClass @JvmStatic fun installKeyStore() = FakeAndroidKeyStore.install()+ }++ @Test fun manifestDeclaresBackupAgentAndRules() {+ val info = ctx.packageManager.getApplicationInfo(ctx.packageName, 0)+ assertEquals(+ "com.vayunmathur.youpipe.platform.AppBackupAgent",+ info.backupAgentName,+ )+ assertNotEquals(0, ctx.resources.getIdentifier("data_extraction_rules", "xml", ctx.packageName))+ }++ @Test fun agentWiresCodecConfigsAndDatastore() {+ val agent = AppBackupAgent()+ assertEquals(YouPipeDbBackupCodec, agent.dbCodec)+ assertEquals(listOf("datastore_default"), agent.datastoreNames)+ assertTrue(agent.prefNames.isEmpty(), "SABR/device-bound prefs must not be backed up")+ assertTrue(agent.extraFiles.isEmpty(), "downloaded files must not be backed up")+ }++ @Test fun dbConfigsMintAStablePassphraseForFreshRestoreTargets() {+ DatabaseHelper(ctx).deleteKey()+ val first = youpipeDbConfigs(ctx)+ assertEquals(listOf(DB_NAME), first.map { it.first })+ assertTrue(first.single().second.isNotBlank())+ // Minted once: a second call (e.g. restore after backup) reuses it,+ // and it is the passphrase the database builder will unwrap.+ assertEquals(first, youpipeDbConfigs(ctx))+ assertEquals(first.single().second, DatabaseHelper(ctx).getPassphrase())+ }++ @Test fun preservedAndExcludedTablesPartitionTheSchema() {+ // The committed Room schema (current version = newest file) is the+ // authoritative table list: a future entity must land in exactly+ // one of the two backup lists or this test fails.+ val schemaDir = File(+ "schemas/com.vayunmathur.youpipe.data.SubscriptionDatabase",+ )+ val schema = schemaDir.listFiles()+ ?.filter { it.extension == "json" }+ ?.maxByOrNull { it.nameWithoutExtension.toInt() }+ ?: fail("committed Room schema not found in $schemaDir")+ val entityTables = Regex(""""tableName"\s*:\s*"([^"]+)"""")+ .findAll(schema.readText()).map { it.groupValues[1] }.toSet()+ assertTrue(entityTables.isNotEmpty())+ assertEquals(entityTables, YOUPIPE_PRESERVED_TABLES + YOUPIPE_EXCLUDED_TABLES)+ assertTrue(YOUPIPE_PRESERVED_TABLES.intersect(YOUPIPE_EXCLUDED_TABLES).isEmpty())+ // The data kinds the decision turns on, named explicitly.+ assertTrue("Subscription" in YOUPIPE_PRESERVED_TABLES)+ assertTrue("HistoryVideo" in YOUPIPE_PRESERVED_TABLES)+ assertTrue("Playlist" in YOUPIPE_PRESERVED_TABLES)+ assertTrue("CachedRelatedVideo" in YOUPIPE_EXCLUDED_TABLES)+ assertTrue("RecommendationImpression" in YOUPIPE_EXCLUDED_TABLES)+ assertTrue("SubscriptionVideo" in YOUPIPE_EXCLUDED_TABLES)+ assertTrue("DownloadedVideo" in YOUPIPE_EXCLUDED_TABLES)+ }++ @Test fun extractionRulesNeverCarryRawDatabaseOrWrappedPassphrase() {+ val parser = ctx.resources.getXml(+ ctx.resources.getIdentifier("data_extraction_rules", "xml", ctx.packageName),+ )+ val includes = mutableListOf<Pair<String, String>>()+ val excludes = mutableListOf<Pair<String, String>>()+ var event = parser.eventType+ while (event != org.xmlpull.v1.XmlPullParser.END_DOCUMENT) {+ if (event == org.xmlpull.v1.XmlPullParser.START_TAG) {+ val domain = parser.getAttributeValue(null, "domain") ?: ""+ val path = parser.getAttributeValue(null, "path") ?: ""+ when (parser.name) {+ "include" -> includes += domain to path+ "exclude" -> excludes += domain to path+ }+ }+ event = parser.next()+ }+ // Both sections include each domain wholesale and then refuse the+ // sensitive children (the weather shape Android lint requires):+ // the net payload is the settings file only, since the database,+ // the wrapped passphrase, the SABR caches and the downloads are+ // all excluded below and no other files exist in these domains.+ assertEquals(+ setOf("file" to ".", "database" to ".", "sharedpref" to ".", "external" to "."),+ includes.toSet(),+ )+ assertEquals(8, includes.size, "four domain includes per section, two sections")+ // ...and both sections explicitly refuse the raw DB, its sidecars+ // and the keystore-wrapped passphrase even if the allowlist is+ // ever widened (each refusal appears once per section).+ for (refusal in listOf(+ "database" to "passwords-db",+ "database" to "passwords-db-wal",+ "database" to "passwords-db-shm",+ "database" to "passwords-db-journal",+ "sharedpref" to "secure_prefs.xml",+ "external" to "downloads",+ )) {+ assertEquals(2, excludes.count { it == refusal }, "$refusal must be excluded in both sections")+ }+ assertFalse(includes.any { it.second == "passwords-db" }, "raw SQLCipher DB must never be a file payload")+ }++ @Test fun backupZipRoundTripsSettingsThroughAgentWiring() {+ // No passwords-db exists in this sandbox, so the codec export is a+ // no-op (as on a fresh install); the settings datastore must still+ // round-trip through the exact helper + configs + codec the agent+ // is wired with.+ val datastoreFile = File(ctx.filesDir, "datastore_default.preferences_pb")+ datastoreFile.parentFile?.mkdirs()+ datastoreFile.writeBytes("youpipe-settings".encodeToByteArray())+ val zip = ByteArrayOutputStream()+ BackupHelper.performFullBackup(+ ctx,+ youpipeDbConfigs(ctx),+ listOf("datastore_default"),+ emptyList(),+ emptyList(),+ zip,+ YouPipeDbBackupCodec,+ )+ assertTrue(zip.size() > 0, "backup zip written")+ assertTrue(datastoreFile.delete())+ BackupHelper.performFullRestore(+ ctx,+ youpipeDbConfigs(ctx),+ listOf("datastore_default"),+ emptyList(),+ emptyMap(),+ ByteArrayInputStream(zip.toByteArray()),+ YouPipeDbBackupCodec,+ )+ assertEquals("youpipe-settings", datastoreFile.readBytes().decodeToString())+ }++ @Test fun exportingAMissingDatabaseWritesNothing() {+ val output = File(ctx.cacheDir, "youpipe-export-should-not-exist.db")+ output.delete()+ YouPipeDbBackupCodec.exportDatabase(ctx, "no-such-youpipe-db", "pw", output)+ assertFalse(output.exists(), "a missing source must not produce an export file")+ }++ @Test fun failedImportLeavesLiveDatabaseUntouched() {+ val dbFile = ctx.getDatabasePath("youpipe-import-target")+ dbFile.parentFile?.mkdirs()+ val liveBytes = ByteArray(64) { 7 }+ dbFile.writeBytes(liveBytes)+ val missing = File(ctx.cacheDir, "youpipe-missing-plaintext.db")+ missing.delete()+ try {+ YouPipeDbBackupCodec.importDatabase(ctx, "youpipe-import-target", "pw", missing)+ fail("missing input must fail the import")+ } catch (expected: Exception) {+ // IOException from the delegate, before any native or swap step.+ assertTrue(expected is java.io.IOException, "$expected")+ }+ assertTrue(liveBytes.contentEquals(dbFile.readBytes()))+ val leftovers = dbFile.parentFile?.listFiles()+ ?.filter { it.name.contains(".import-") || it.name.contains(".bak-") }+ .orEmpty()+ assertTrue(leftovers.isEmpty(), "leftover swap files: $leftovers")+ dbFile.delete()+ }++ @Test fun corruptImportLeavesLiveDatabaseUntouched() {+ val dbFile = ctx.getDatabasePath("youpipe-corrupt-target")+ dbFile.parentFile?.mkdirs()+ val liveBytes = ByteArray(64) { 3 }+ dbFile.writeBytes(liveBytes)+ val corrupt = File(ctx.cacheDir, "youpipe-corrupt-plaintext.db")+ corrupt.writeBytes(ByteArray(64) { 0x55 }) // not a SQLite file at all+ try {+ YouPipeDbBackupCodec.importDatabase(ctx, "youpipe-corrupt-target", "pw", corrupt)+ fail("corrupt input must fail the import")+ } catch (expected: Throwable) {+ // On host the native open fails; on device strip/verify rejects+ // the payload. Either way the failure precedes any swap.+ assertTrue(expected is Exception || expected is Error)+ }+ assertTrue(liveBytes.contentEquals(dbFile.readBytes()))+ dbFile.delete()+ corrupt.delete()+ }+}