openassistant: make platform backup safe and data-preserving
- Commit
142aa57bdda399761cb5d08f41d69630cd139381- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-04 22:00 UTC (1 day ago)
- Parents
e5c74b7
Device-to-device transfer previously carried the raw SQLCipher database (passwords-db) while its passphrase stays wrapped by the old device's non-exportable AndroidKeyStore key, so a restored database could not be opened and Room would fail on first launch. Cloud backup denied everything, so conversations were lost there too. Conversations, messages and memories are real user data and must survive both channels. Follow the weather pattern: declare platform/AppBackupAgent, a BaseBackupAgent whose SqlCipherDbCodec exports the database to plaintext inside the backup payload and re-encrypts it under the new device's key on restore, plus the datastore_default file that holds the user's editable system prompt. Add DB_NAME and openAssistantDbConfigs in data/Database.kt (the name is unchanged, so existing installs keep their database) and pass it explicitly in OpenAssistantRepository. Rewrite data_extraction_rules.xml so both cloud-backup and device-transfer exclude passwords-db and its -wal/-shm/-journal sidecars, the keystore-wrapped secure_prefs, and the gemma4 model downloads (gigabytes, re-downloadable). While the backupAgent is declared the cloud section is not consulted and cloud content is exactly the agent payload; the rules govern device transfer and remain the correct control if the agent is ever removed. Update CopyUriAndRouteTest, which pinned the previous no-agent state, and add OpenAssistantPlatformBackupTest: it proves the agent declares exactly the codec, the conversation database and the system-prompt datastore, that the manifest names the agent, that the rules never carry the raw database, passphrase or models, and that the real agent round-trips the datastore through Robolectric backup-data streams. The SQLCipher codec needs its native library, which a host JVM cannot load, so the encrypted database round-trip itself remains device-only; the codec's host-side contract is covered in :library:room. Verified: ./gradlew :openassistant:lint :openassistant:lintVitalRelease :openassistant:testDevUnitTest passes.
Diff
openassistant/AGENTS.md
diff --git a/openassistant/AGENTS.md b/openassistant/AGENTS.mdindex a95a736f7e..b8d0c12e2c 100644--- a/openassistant/AGENTS.md+++ b/openassistant/AGENTS.md@@ -44,7 +44,7 @@ _Install: ./install openassistant (dev by default)._ ### network/ — web tools - com/vayunmathur/openassistant/network/AssistantWebTools.kt — the app's networking entry point for web tools: `web_search` calls the server's `GET /api/search` (type=text/news) through `NetworkClient` (FIRST_PARTY bundle inited in MainActivity) and reshapes results on device into {title,url,snippet} hits (n<=10); `web_read`/`web_read_result` fetch the page on device (per-request system trust, since page hosts are arbitrary) and extract readable text locally via `domain/WebPageExtractor` — http/https only, localhost/.local/private IP literals refused, 10s timeouts, 2M-char body cap, 6000-char pages paged by character offset. Extracts are cached process-wide (LRU, 4 pages × 24k chars, raw HTML never retained) so paging or re-reading a page fetches once. Tool failures are typed `Error: ...` strings, never silent empties ### data/ — chats + repository-- com/vayunmathur/openassistant/data/Database.kt+- com/vayunmathur/openassistant/data/Database.kt — `DB_NAME` (`passwords-db`) + `openAssistantDbConfigs` for the backup agent - com/vayunmathur/openassistant/data/OpenAssistantRepository.kt ### ui/ — chat + settings - com/vayunmathur/openassistant/ui/LiteRTChatUi.kt@@ -68,6 +68,7 @@ _Install: ./install openassistant (dev by default)._ - com/vayunmathur/openassistant/domain/ReplyStream.kt — bounded chunk buffer between cumulative model callbacks and the DB writer (<=64 pending chunks, 32k live snapshot cap) - com/vayunmathur/openassistant/domain/TurnGate.kt — bounded concurrent turns (max 3 active, per-conversation serialisation) ### platform/ — ViewModel, engine + tool registry+- com/vayunmathur/openassistant/platform/AppBackupAgent.kt — platform backup agent: codec-exported `passwords-db` (via `SqlCipherDbCodec`) plus `datastore_default`; raw DB, `secure_prefs` and external model files are excluded in `res/xml/data_extraction_rules.xml` - com/vayunmathur/openassistant/platform/AssistantViewModel.kt - com/vayunmathur/openassistant/platform/MamlChatEngine.kt - com/vayunmathur/openassistant/platform/AssistantDeviceTools.kt
openassistant/src/main/AndroidManifest.xml
diff --git a/openassistant/src/main/AndroidManifest.xml b/openassistant/src/main/AndroidManifest.xmlindex 5d9138c3ba..b10b36d0c4 100644--- a/openassistant/src/main/AndroidManifest.xml+++ b/openassistant/src/main/AndroidManifest.xml@@ -74,6 +74,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"
openassistant/src/main/java/com/vayunmathur/openassistant/data/Database.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/data/Database.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/data/Database.ktindex 1686ed34cd..68a0c9f58a 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/data/Database.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/data/Database.kt@@ -12,8 +12,21 @@ import androidx.room3.RoomDatabase import androidx.room3.Upsert import com.vayunmathur.library.util.DefaultConverters import androidx.room3.migration.Migration+import android.content.Context+import com.vayunmathur.library.util.DatabaseHelper import kotlinx.coroutines.flow.Flow +/**+ * On-disk name of the [AppDatabase] file. This is the shared RoomRepository+ * default, kept explicit (and unchanged) so existing installs keep opening+ * the database they already have.+ */+const val DB_NAME = "passwords-db"++/** Backup config shared by [com.vayunmathur.openassistant.platform.AppBackupAgent]. */+fun openAssistantDbConfigs(context: Context): List<Pair<String, String>> =+ listOf(DB_NAME to DatabaseHelper(context).getPassphrase())+ /** Immutable value describing conversation. */ @Entity data class Conversation(
openassistant/src/main/java/com/vayunmathur/openassistant/data/OpenAssistantRepository.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/data/OpenAssistantRepository.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/data/OpenAssistantRepository.ktindex 7c23b388b1..c0e9a83623 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/data/OpenAssistantRepository.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/data/OpenAssistantRepository.kt@@ -8,7 +8,7 @@ import kotlinx.coroutines.flow.Flow * Single owner of [AppDatabase] for the openassistant module. */ class OpenAssistantRepository private constructor(context: Context) :- RoomRepository<AppDatabase>(context, AppDatabase::class) {+ RoomRepository<AppDatabase>(context, AppDatabase::class, DB_NAME) { private val conversationDao get() = db.conversationDao() private val messageDao get() = db.messageDao()
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AppBackupAgent.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AppBackupAgent.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AppBackupAgent.ktnew file mode 100644index 0000000000..c442209d37--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AppBackupAgent.kt@@ -0,0 +1,28 @@+package com.vayunmathur.openassistant.platform++import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.BaseBackupAgent+import com.vayunmathur.openassistant.data.openAssistantDbConfigs++/**+ * Platform backup agent for OpenAssistant.+ *+ * The conversation database is SQLCipher-encrypted under a passphrase wrapped+ * by a non-exportable AndroidKeyStore key, so the raw database file must+ * never travel in a backup: a restored copy cannot be opened on a new+ * device. [SqlCipherDbCodec] instead exports the database to plaintext+ * inside the backup payload on the old device and re-encrypts it under the+ * new device's key on restore (the weather pattern). The DataStore file+ * rides along because it holds the user's editable system prompt; it also+ * holds model-download markers, which are harmless without the models.+ * Model files live in external storage, are gigabytes, and are+ * re-downloadable, so they are deliberately not part of this payload.+ */+class AppBackupAgent : BaseBackupAgent() {+ override val dbCodec = SqlCipherDbCodec++ override val dbConfigs: List<Pair<String, String>>+ get() = openAssistantDbConfigs(this)++ override val datastoreNames: List<String> get() = listOf("datastore_default")+}
openassistant/src/main/res/xml/data_extraction_rules.xml
diff --git a/openassistant/src/main/res/xml/data_extraction_rules.xml b/openassistant/src/main/res/xml/data_extraction_rules.xmlindex 13906e26ab..a68a572d86 100644--- a/openassistant/src/main/res/xml/data_extraction_rules.xml+++ b/openassistant/src/main/res/xml/data_extraction_rules.xml@@ -2,37 +2,74 @@ <!-- Overrides the permissive default in the shared :library module. Storage audited:- database/passwords-db AppDatabase (Conversation/Message/Memory): the full- conversation history plus remembered facts. Free-form user- text, so it can contain anything.- external/ on-demand model downloads in getExternalFilesDir(null):- the gemma4/ maml model files. Gigabytes, and re-downloadable.- file/datastore_default.preferences_pb model download progress and version markers- (progress_*, dlid_*). Meaningless once- the models are gone.- cache/ recordings and attachment scratch files; Android never backs- up cacheDir.+ database/passwords-db AppDatabase (Conversation/Message/Memory,+ PendingToolCall, AuditRecord): the full+ conversation history plus remembered facts.+ Free-form user text, so it can contain+ anything. SQLCipher-encrypted.+ file/datastore_default.preferences_pb the user's editable system+ prompt, plus model download progress and+ version markers (progress_*, dlid_*). The+ markers are meaningless without the models;+ the prompt is real user data.+ external/ on-demand model downloads in+ getExternalFilesDir(null): the gemma4/ model+ files. Gigabytes, and re-downloadable.+ cache/ recordings and attachment scratch files;+ Android never backs up cacheDir. Message+ imagePaths point into cacheDir, so restored+ messages can reference already-gone scratch+ images; the conversation text is unaffected. sharedpref/secure_prefs keystore-wrapped SQLCipher passphrase. - No API keys or remote credentials were found - inference runs on-device - so the only- secret-grade material is the keystore passphrase.+ passwords-db is excluded from both sections for the same reason as+ weather-db: it is SQLCipher ciphertext under a passphrase wrapped by a+ non-exportable AndroidKeyStore key. That key never leaves the device,+ so a restored copy of this file cannot be opened on a new device and+ would crash Room on first launch. The conversations still migrate:+ the declared BackupAgent (platform/AppBackupAgent) uses+ SqlCipherDbCodec to export the database to plaintext inside the+ backup payload and re-encrypt it under the new device's key on+ restore. That path is the one that works; a raw file copy would only+ get in its way, on both the cloud and the device-to-device channel. - These rules now govern cloud backup too: the legacy android:backupAgent was removed.- It exported the conversation history DECRYPTED via SqlCipherDbCodec, bypassing the- <cloud-backup> denials below. (Its "passwords-db" name was the shared RoomRepository- default file name, not a distinct passwords database.) Cloud stays deny-all: the- models are gigabytes and re-downloadable, and the download markers are meaningless- without them. <device-transfer> carries the history and nothing else. -->+ SCOPE: openassistant 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: the codec-exported database plus datastore_default. The+ rules below govern <device-transfer>, and are the correct control if+ the backupAgent is ever removed. Model files stay out of every+ channel because they are gigabytes and re-downloadable.+--> <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" />+ <include domain="sharedpref" path="." />+ <exclude domain="sharedpref" path="secure_prefs.xml" />+ <include domain="external" path="." />+ <!-- Model downloads: gigabytes and re-downloadable. -->+ <exclude domain="external" path="gemma4" /> </cloud-backup> <device-transfer>- <!-- Whole-domain include so the -wal/-shm sidecars travel 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" />+ <include domain="sharedpref" path="." />+ <exclude domain="sharedpref" path="secure_prefs.xml" />+ <include domain="external" path="." />+ <!-- Model downloads: gigabytes and re-downloadable. -->+ <exclude domain="external" path="gemma4" /> </device-transfer> </data-extraction-rules>
openassistant/src/test/java/com/vayunmathur/openassistant/platform/OpenAssistantPlatformBackupTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/OpenAssistantPlatformBackupTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/OpenAssistantPlatformBackupTest.ktnew file mode 100644index 0000000000..aed740f05b--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/OpenAssistantPlatformBackupTest.kt@@ -0,0 +1,155 @@+package com.vayunmathur.openassistant.platform++import android.content.Context+import android.content.pm.ApplicationInfo+import android.content.res.XmlResourceParser+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.DatabaseHelper+import com.vayunmathur.openassistant.data.DB_NAME+import com.vayunmathur.testsupport.FakeAndroidKeyStore+import java.io.File+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 OpenAssistant's REAL manifest BackupAgent+ * ([AppBackupAgent], android:backupAgent=".platform.AppBackupAgent" without+ * fullBackupOnly, so cloud backup is key/value through this agent; the+ * extraction rules govern device transfer).+ *+ * Host limit, stated plainly: the SQLCipher codec's export/import needs the+ * native SQLCipher library, which a host JVM cannot load, so the actual+ * encrypted-database round-trip cannot execute here (the codec's own+ * pre/post-native contract is covered in :library:room's+ * SqlCipherDbCodecTest, and the remaining native round-trip is+ * device-only). This test therefore proves everything the host can prove:+ * the agent declares exactly the codec, the conversation database and the+ * DataStore holding the system prompt; the manifest names the agent; the+ * extraction rules never carry the raw database, its sidecars, the+ * keystore-wrapped passphrase or the re-downloadable model files; and the+ * real agent round-trips the DataStore through Robolectric's backup-data+ * streams (with no database file present the codec export is a no-op, so+ * the entity carries the DataStore alone).+ */+@RunWith(RobolectricTestRunner::class)+class OpenAssistantPlatformBackupTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ 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): android.os.ParcelFileDescriptor {+ if (!file.exists()) file.writeBytes(ByteArray(0))+ return android.os.ParcelFileDescriptor.open(+ file, android.os.ParcelFileDescriptor.MODE_READ_WRITE,+ )+ }++ @Test+ fun agentDeclaresCodecConversationDbAndSystemPromptDatastore() {+ FakeAndroidKeyStore.install()+ DatabaseHelper(ctx).storePassphrase("test-passphrase")+ val agent = attachedAgent()+ assertSame(SqlCipherDbCodec, agent.dbCodec)+ assertEquals(listOf(DB_NAME), agent.dbConfigs.map { it.first })+ assertTrue(agent.dbConfigs.single().second.isNotEmpty(), "passphrase present")+ assertEquals(listOf("datastore_default"), agent.datastoreNames)+ assertTrue(agent.prefNames.isEmpty(), "secure_prefs must never be a backup input")+ assertTrue(agent.extraFiles.isEmpty(), "model files are re-downloadable, not backed up")+ }++ @Test+ fun manifestDeclaresTheBackupAgent() {+ val info = ctx.packageManager.getApplicationInfo(ctx.packageName, 0)+ assertEquals(+ "com.vayunmathur.openassistant.platform.AppBackupAgent", info.backupAgentName,+ )+ assertTrue(info.flags and ApplicationInfo.FLAG_ALLOW_BACKUP != 0)+ }++ @Test+ fun extractionRulesNeverCarryRawDbPassphraseOrModels() {+ 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", "include" -> section?.let {+ sections.getValue(it).add(+ parser.name + ":" + parser.getAttributeValue(null, "domain") ++ ":" + parser.getAttributeValue(null, "path"),+ )+ }+ }+ }+ if (event == XmlResourceParser.END_TAG && parser.name in sections) section = null+ event = parser.next()+ }+ for (channel in listOf("cloud-backup", "device-transfer")) {+ val rules = sections[channel].orEmpty()+ for (excluded in listOf(+ "exclude:database:passwords-db",+ "exclude:database:passwords-db-wal",+ "exclude:database:passwords-db-shm",+ "exclude:database:passwords-db-journal",+ "exclude:sharedpref:secure_prefs.xml",+ "exclude:external:gemma4",+ )) {+ assertTrue(excluded in rules, "$channel must contain $excluded, was $rules")+ }+ }+ }++ @Test+ fun realAgentBackupThenRestoreRoundTripsDatastore() {+ FakeAndroidKeyStore.install()+ DatabaseHelper(ctx).storePassphrase("test-passphrase")+ // No database file exists in this sandbox, so the codec export is a+ // no-op and the payload carries the DataStore alone (see class doc).+ val datastoreFile = File(ctx.filesDir, "datastore_default.preferences_pb")+ .apply { parentFile?.mkdirs(); writeBytes(byteArrayOf(11, 22, 33, 44, 55)) }+ val agent = attachedAgent()++ val stateFile = File(ctx.cacheDir, "oa-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())++ datastoreFile.delete()+ assertTrue(!datastoreFile.exists())++ val restoreState = File(ctx.cacheDir, "oa-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), datastoreFile.readBytes().toList(),+ "system-prompt DataStore restored byte-identically",+ )+ assertEquals(8, restoreState.length())+ }+}
openassistant/src/test/java/com/vayunmathur/openassistant/util/CopyUriAndRouteTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/CopyUriAndRouteTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/CopyUriAndRouteTest.ktindex 67da5020d7..7bedbfaaa8 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/CopyUriAndRouteTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/CopyUriAndRouteTest.kt@@ -45,12 +45,15 @@ class CopyUriAndRouteTest { assertTrue(Route.ConversationPage(1L) != Route.ConversationPage(2L)) } - @Test fun manifestHasNoBackupAgentAndExtractionRulesGovern() {- // The legacy backup agent was removed (it exported conversation history- // decrypted, bypassing the deny-all cloud rules); data_extraction_- // rules.xml now governs both cloud backup and device transfer.+ @Test fun manifestDeclaresBackupAgentAndExtractionRules() {+ // The codec backup agent carries the conversation history (exported+ // to plaintext inside the payload, re-encrypted on restore);+ // data_extraction_rules.xml governs device transfer and excludes+ // the raw encrypted database on both channels. val info = ctx.packageManager.getApplicationInfo(ctx.packageName, 0)- assertEquals(null, info.backupAgentName)+ assertEquals(+ "com.vayunmathur.openassistant.platform.AppBackupAgent", info.backupAgentName,+ ) assertTrue(ctx.resources.getIdentifier("data_extraction_rules", "xml", ctx.packageName) != 0) } }