health: back up records via re-keying BackupAgent, not raw DB file
- Commit
5cc276a9a6cdbc4ef2e4fb85931656bf061c5071- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-04 21:50 UTC (1 day ago)
- Parents
444d24b
Health's device-transfer rules carried the raw SQLCipher database (passwords-db) while excluding the keystore-wrapped passphrase, and the wrapping AndroidKeyStore key is non-exportable by design. A device-to-device restore therefore landed an encrypted database the new device could never open: the repository minted a fresh key and passphrase and Room threw on first open, losing irreplaceable health records. Cloud backup excluded everything, so records were lost on that channel too. Follow the weather pattern. Health now declares .platform.AppBackupAgent (BaseBackupAgent + SqlCipherDbCodec): the codec exports the database to plaintext inside the backup payload and re-encrypts it under the new device's key on restore, and the agent carries files/medical_attachments (vaccination-card scans) as extra files. The regenerable food index and the Health Connect sync bookkeeping are deliberately not backed up; restoring stale sync state on a new device could skip re-importing records. data_extraction_rules.xml now excludes the raw passwords-db file and its -wal/-shm/-journal sidecars plus secure_prefs.xml on both channels, so the file-copy path can never resurrect the trap. With the agent declared and no fullBackupOnly, cloud backup is key/value through the agent and the cloud-backup section is not consulted; it remains the correct fallback control if the agent is ever removed. Record.kt gains DB_NAME and healthDbConfigs (shared by the agent), and HealthRepository passes DB_NAME explicitly instead of relying on the RoomRepository default. Host verification is the strongest available off-device: SQLCipher is native and cannot load on a host JVM, so the codec round trip itself stays covered by :library:room instrumented tests. The new HealthBackupAgentTest proves the manifest names the agent, the agent wires SqlCipherDbCodec to passwords-db with the DatabaseHelper passphrase, the parsed extraction rules never ship the raw DB or wrapped passphrase on either channel, and a real onBackup -> onRestore cycle through Robolectric's backup streams round-trips a medical attachment byte-for-byte. Verified: ./gradlew :health:lint :health:lintVitalRelease :health:testDevUnitTest green (677 tests). The pre-change run failed only the then-new agent test (unattached agent in the test harness); every pre-existing test passed there and passes now.
Diff
health/AGENTS.md
diff --git a/health/AGENTS.md b/health/AGENTS.mdindex 861571ace5..ebd2e7cd0f 100644--- a/health/AGENTS.md+++ b/health/AGENTS.md@@ -31,6 +31,7 @@ _Install: ./install health (dev by default)._ - com/vayunmathur/health/Navigation.kt ### data/ — Room entities + repository - com/vayunmathur/health/data/HealthRepository.kt+- com/vayunmathur/health/data/Record.kt — also owns `DB_NAME` (`passwords-db`) and `healthDbConfigs` shared by the backup agent - com/vayunmathur/health/data/HealthConverters.kt — Room type converters (`Converters`) - com/vayunmathur/health/data/Record.kt - com/vayunmathur/health/data/NutritionScaling.kt@@ -61,6 +62,7 @@ _Install: ./install health (dev by default)._ - com/vayunmathur/health/platform/DoseActionReceiver.kt - com/vayunmathur/health/platform/DoseReminderActivity.kt - com/vayunmathur/health/platform/HealthBootReceiver.kt+- com/vayunmathur/health/platform/AppBackupAgent.kt — platform backup: `SqlCipherDbCodec` re-keys `passwords-db` into the backup payload (raw encrypted file is excluded by `res/xml/data_extraction_rules.xml` on both channels) and carries `files/medical_attachments/` as extra files; food index and sync bookkeeping are not backed up ### intents/ — assistant IPC - com/vayunmathur/health/intents/GetMetricSummaryIntent.kt — OpenAssistant `health_get_metric_summary`: validated metric/range over a recent local-calendar window, SQL aggregates only (latest/average/min/max/total/count via `HealthRepository` aggregate queries); no raw records cross in the `library.intents.health` DTO ### notifications/ + service/ — channels and dose sound
health/src/main/AndroidManifest.xml
diff --git a/health/src/main/AndroidManifest.xml b/health/src/main/AndroidManifest.xmlindex 47623b59c1..b4ccf2c663 100644--- a/health/src/main/AndroidManifest.xml+++ b/health/src/main/AndroidManifest.xml@@ -106,6 +106,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"
health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt b/health/src/main/java/com/vayunmathur/health/data/HealthRepository.ktindex baf41ede80..b906522ed7 100644--- a/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt+++ b/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt@@ -18,7 +18,7 @@ import kotlinx.coroutines.flow.Flow // touch a DAO directly. Splitting it would only move the same method count elsewhere. @Suppress("TooManyFunctions") class HealthRepository private constructor(context: Context) :- RoomRepository<HealthDatabase>(context, HealthDatabase::class) {+ RoomRepository<HealthDatabase>(context, HealthDatabase::class, DB_NAME) { private val dao get() = db.healthDao() private val medicalDao get() = db.medicalDao()
health/src/main/java/com/vayunmathur/health/data/Record.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/Record.kt b/health/src/main/java/com/vayunmathur/health/data/Record.ktindex bbf9ae7d37..834b9e8d1c 100644--- a/health/src/main/java/com/vayunmathur/health/data/Record.kt+++ b/health/src/main/java/com/vayunmathur/health/data/Record.kt@@ -15,6 +15,8 @@ import androidx.room3.Update import androidx.room3.Delete import androidx.room3.migration.Migration import androidx.sqlite.execSQL+import android.content.Context+import com.vayunmathur.library.util.DatabaseHelper import kotlinx.serialization.Serializable import kotlinx.coroutines.flow.Flow import java.time.Instant@@ -395,6 +397,13 @@ interface HealthDao { suspend fun getIngredientsForRecipe(recipeId: String): List<RecipeIngredient> } +/** On-disk name of the [HealthDatabase] file (the [com.vayunmathur.library.room.RoomRepository] default). */+const val DB_NAME = "passwords-db"++/** Backup config shared by [com.vayunmathur.health.platform.AppBackupAgent]. */+fun healthDbConfigs(context: Context): List<Pair<String, String>> =+ listOf(DB_NAME to DatabaseHelper(context).getPassphrase())+ @Database( entities = [ Record::class, Ingredient::class, Recipe::class, ServingUnit::class, RecipeIngredient::class,
health/src/main/java/com/vayunmathur/health/platform/AppBackupAgent.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/AppBackupAgent.kt b/health/src/main/java/com/vayunmathur/health/platform/AppBackupAgent.ktnew file mode 100644index 0000000000..cb06c5bbc8--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/platform/AppBackupAgent.kt@@ -0,0 +1,25 @@+package com.vayunmathur.health.platform++import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.BaseBackupAgent+import com.vayunmathur.health.data.healthDbConfigs+import java.io.File++/**+ * Carries the health database and medical attachment files through platform+ * backup. The database is SQLCipher-encrypted under a passphrase wrapped by a+ * non-exportable AndroidKeyStore key, so a raw file copy can never be opened+ * on a new device: [SqlCipherDbCodec] exports it to plaintext inside the+ * backup payload and re-encrypts it under the new device's key on restore.+ * The regenerable food index and the Health Connect sync bookkeeping are+ * deliberately left out — both are rebuilt on the new device.+ */+class AppBackupAgent : BaseBackupAgent() {+ override val dbCodec = SqlCipherDbCodec++ override val dbConfigs: List<Pair<String, String>>+ get() = healthDbConfigs(this)++ override val extraFiles: List<File>+ get() = listOf(File(filesDir, "medical_attachments"))+}
health/src/main/res/xml/data_extraction_rules.xml
diff --git a/health/src/main/res/xml/data_extraction_rules.xml b/health/src/main/res/xml/data_extraction_rules.xmlindex 47b49d0352..c74a4a2196 100644--- a/health/src/main/res/xml/data_extraction_rules.xml+++ b/health/src/main/res/xml/data_extraction_rules.xml@@ -1,31 +1,76 @@ <?xml version="1.0" encoding="utf-8"?>-<!-- Overrides the permissive default in the shared :library module.+<!--+ Health. Audited state:+ * databases/passwords-db — HealthDatabase (health, nutrition, sleep,+ exercise and FHIR medical records). Irreplaceable user data.+ * files/medical_attachments/ — vaccination-card scans referenced by+ MedicalAttachment rows. Irreplaceable user data.+ * files/food.db, food.db.part, food.bin.part, food.bin.meta.json —+ Open Food Facts index unpacked from a bundled asset. Fully regenerable.+ * files/datastore_default.preferences_pb — Health Connect sync+ bookkeeping. Regenerable; restoring it on a new device would skip+ re-importing records Health Connect there does not have yet.+ * shared_prefs/secure_prefs.xml — SQLCipher passphrase wrapped by a+ non-exportable AndroidKeyStore key.+ * shared_prefs/sync.xml — declared in HealthAPI but never read or written. - Storage audited:- database/passwords-db HealthDatabase (Record/Ingredient/Recipe/ServingUnit/- RecipeIngredient): health, nutrition, sleep and exercise- records. Highly sensitive.- file/food.db, food.db.part, food.bin.part, food.bin.meta.json- Open Food Facts index unpacked from a bundled asset.- Large and fully regenerable.- file/datastore_default.preferences_pb sync bookkeeping.- sharedpref/sync declared in HealthAPI but never read or written.- sharedpref/secure_prefs keystore-wrapped SQLCipher passphrase.+ passwords-db is excluded from both sections: it is SQLCipher-encrypted+ under a passphrase wrapped by a key that never leaves the old device, so a+ restored raw copy cannot be opened — the repository mints a fresh key and+ passphrase, and Room throws on the already-encrypted file. Shipping it+ would trade a clean first launch for a crash and lose the records anyway. - Health records must not reach Google's servers, so cloud backup is off entirely.- Device-to-device transfer never leaves the two devices, so records move with the- user; the regenerable food index and the keystore-bound passphrase do not. -->+ The records still migrate: health 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 key on restore, and carries medical_attachments as extra files.+ That path is the one that works; the raw file copy would only get in its+ way. The food index and sync bookkeeping stay behind on purpose.++ SCOPE: health declares android:backupAgent=".platform.AppBackupAgent" and+ does NOT set android:fullBackupOnly, so Android uses key/value backup here+ and the <cloud-backup> section below is NOT consulted. Cloud content is+ exactly AppBackupAgent's payload — passwords-db exported to plaintext by+ SqlCipherDbCodec (re-encrypted on restore) plus medical_attachments. The+ rules below govern <device-transfer>, and are the correct control if the+ backupAgent is ever removed: without the agent the raw DB must still never+ travel, so a rule-only restore keeps the attachments and starts the+ database empty rather than crashing on an unopenable file.+--> <data-extraction-rules>+ <!-- Not consulted while android:backupAgent is declared; see SCOPE above. --> <cloud-backup>- <exclude domain="root" path="." />- <exclude domain="file" path="." />- <exclude domain="database" path="." />- <exclude domain="sharedpref" path="." />- <exclude domain="external" path="." />+ <include domain="root" path="." />+ <include domain="file" path="." />+ <exclude domain="file" path="food.db" />+ <exclude domain="file" path="food.db.part" />+ <exclude domain="file" path="food.bin.part" />+ <exclude domain="file" path="food.bin.meta.json" />+ <exclude domain="file" path="datastore_default.preferences_pb" />+ <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" />+ <include domain="sharedpref" path="." />+ <exclude domain="sharedpref" path="secure_prefs.xml" />+ <include domain="external" path="." /> </cloud-backup> <device-transfer>- <!-- Whole-domain include so the -wal/-shm sidecars travel with the database. -->+ <include domain="root" path="." />+ <include domain="file" path="." />+ <exclude domain="file" path="food.db" />+ <exclude domain="file" path="food.db.part" />+ <exclude domain="file" path="food.bin.part" />+ <exclude domain="file" path="food.bin.meta.json" />+ <exclude domain="file" path="datastore_default.preferences_pb" /> <include domain="database" path="." />- <include domain="file" path="datastore_default.preferences_pb" />+ <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" />+ <include domain="sharedpref" path="." />+ <exclude domain="sharedpref" path="secure_prefs.xml" />+ <include domain="external" path="." /> </device-transfer> </data-extraction-rules>
health/src/test/java/com/vayunmathur/health/platform/HealthBackupAgentTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/platform/HealthBackupAgentTest.kt b/health/src/test/java/com/vayunmathur/health/platform/HealthBackupAgentTest.ktnew file mode 100644index 0000000000..18b4d793cb--- /dev/null+++ b/health/src/test/java/com/vayunmathur/health/platform/HealthBackupAgentTest.kt@@ -0,0 +1,165 @@+package com.vayunmathur.health.platform++import android.content.Context+import android.content.pm.ApplicationInfo+import android.content.res.XmlResourceParser+import android.os.ParcelFileDescriptor+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.health.data.DB_NAME+import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.DatabaseHelper+import com.vayunmathur.testsupport.FakeAndroidKeyStore+import java.io.File+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertSame+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 wiring for Health's REAL manifest BackupAgent+ * ([AppBackupAgent], android:backupAgent=".platform.AppBackupAgent" without+ * fullBackupOnly, so cloud backup is key/value through this agent and+ * device transfer is governed by the extraction rules instead).+ *+ * Host limit: SQLCipher is a native library a host JVM cannot load, so the+ * codec's export/import of the encrypted database itself cannot run here —+ * that round trip is covered on device by :library:room's instrumented+ * tests. What this test proves on host is everything around it: the agent+ * is the one the manifest names, it wires the SQLCipher codec to the+ * database the repository actually opens with the passphrase the keystore+ * helper owns, the extraction rules never let the raw encrypted database+ * or its wrapped passphrase travel on either channel, and the agent's+ * backup -> restore cycle carries the medical attachments byte-for-byte+ * (with no database file present the codec export is a no-op, so the zip+ * holds exactly the extra files).+ */+@RunWith(RobolectricTestRunner::class)+class HealthBackupAgentTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @BeforeTest+ fun installKeyStore() {+ FakeAndroidKeyStore.install()+ }++ private fun attachedAgent(): AppBackupAgent {+ val agent = AppBackupAgent()+ val attach = android.content.ContextWrapper::class.java+ .getDeclaredMethod("attachBaseContext", Context::class.java)+ attach.isAccessible = true+ attach.invoke(agent, ctx)+ return agent+ }++ private fun pfd(file: File): ParcelFileDescriptor {+ if (!file.exists()) file.writeBytes(ByteArray(0))+ return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_WRITE)+ }++ @Test+ fun manifestNamesTheAgentAndBackupStaysEnabled() {+ val info = ctx.packageManager.getApplicationInfo(ctx.packageName, 0)+ assertEquals(+ "com.vayunmathur.health.platform.AppBackupAgent",+ info.backupAgentName,+ )+ assertTrue(info.flags and ApplicationInfo.FLAG_ALLOW_BACKUP != 0)+ }++ @Test+ fun agentWiresSqlCipherCodecToTheHealthDatabase() {+ DatabaseHelper(ctx).storePassphrase("health-backup-test-passphrase")+ val agent = attachedAgent()+ assertSame(SqlCipherDbCodec, agent.dbCodec)+ assertEquals(+ listOf(DB_NAME to "health-backup-test-passphrase"),+ agent.dbConfigs,+ )+ assertEquals("passwords-db", DB_NAME)+ assertEquals(+ listOf("medical_attachments"),+ agent.extraFiles.map { it.name },+ )+ }++ @Test+ fun extractionRulesNeverShipTheRawEncryptedDatabase() {+ val resId = ctx.resources.getIdentifier("data_extraction_rules", "xml", ctx.packageName)+ assertTrue(resId != 0, "manifest dataExtractionRules resource resolves")+ val parser: XmlResourceParser = ctx.resources.getXml(resId)+ val sections = mutableMapOf<String, MutableSet<String>>()+ var section: String? = null+ var event = parser.eventType+ while (event != XmlResourceParser.END_DOCUMENT) {+ if (event == XmlResourceParser.START_TAG) {+ when (parser.name) {+ "cloud-backup", "device-transfer" -> {+ section = parser.name+ sections[section] = mutableSetOf()+ }+ "exclude" -> section?.let {+ sections.getValue(it).add(+ "exclude:" + parser.getAttributeValue(null, "domain") ++ ":" + parser.getAttributeValue(null, "path"),+ )+ }+ "include" -> section?.let {+ sections.getValue(it).add(+ "include:" + parser.getAttributeValue(null, "domain") ++ ":" + parser.getAttributeValue(null, "path"),+ )+ }+ }+ }+ if (event == XmlResourceParser.END_TAG && parser.name in sections) section = null+ event = parser.next()+ }+ for (channel in listOf("cloud-backup", "device-transfer")) {+ val rules = sections[channel].orEmpty()+ assertTrue("exclude:database:passwords-db" in rules, "$channel must exclude the raw DB: $rules")+ assertTrue("exclude:database:passwords-db-wal" in rules, "$channel must exclude the DB WAL: $rules")+ assertTrue("exclude:database:passwords-db-shm" in rules, "$channel must exclude the DB SHM: $rules")+ assertTrue("exclude:sharedpref:secure_prefs.xml" in rules, "$channel must exclude the wrapped passphrase: $rules")+ assertTrue("exclude:file:food.db" in rules, "$channel must exclude the regenerable food index: $rules")+ }+ }++ @Test+ fun realAgentBackupThenRestoreRoundTripsAttachments() {+ DatabaseHelper(ctx).storePassphrase("health-backup-test-passphrase")+ val agent = attachedAgent()++ // Seed the exact extra file the agent declares, through the store+ // the app itself writes attachments with.+ val seeded = AttachmentStore.fileFor(ctx, "card-front.png")+ seeded.writeBytes(byteArrayOf(11, 22, 33, 44, 55))++ val stateFile = File(ctx.cacheDir, "health-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())++ // Wipe what the backup is supposed to carry.+ seeded.delete()+ assertTrue(!seeded.exists())++ val restoreState = File(ctx.cacheDir, "health-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),+ seeded.readBytes().toList(),+ )+ assertEquals(8, restoreState.length())+ }+}