vpn: clean up .mavpn bundles on last config delete and open from files
- Commit
ace06dc13ff3a559dcc7366c43fcd3b0ed759a98- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-17 16:43 UTC (18 days ago)
- Parents
3404c70
Deleting the last VpnConfig of an imported .mavpn bundle left its files orphaned under files/mavpn-bundles/<bundleId>/. VpnViewModel.delete now deletes the database row first (the database stays authoritative), then asks the DAO whether any config still references the bundle, and only then removes the bundle directory via a new best-effort MavpnBundleStore.delete. Cleanup failures or a never-stored bundle never undo the delete, and MavpnBundleStore keeps its safeSegment confinement so a hostile bundle id cannot delete outside mavpn-bundles/. A File-based bundleDir/delete overload makes the store testable without a Context. MainActivity already routed ACTION_VIEW data URIs to the bundle importer, but AndroidManifest declared no VIEW filter for .mavpn, so file managers never offered the app. Add a VIEW/DEFAULT/BROWSABLE filter on content/file URIs scoped by the .mavpn path, following the notes (.md) and email (.eml) manifests: zip and octet-stream MIME types plus pathSuffix/pathPattern for the custom extension. Tests: MavpnBundleStore delete removes only the named bundle, is tolerant of a missing bundle, and is confined against traversal ids; VpnViewModel delete keeps bundle files while a bundle config remains, removes them with the last one, leaves plain configs alone, and tolerates missing bundle files. The manifest change is verified by lint. Verified: ./gradlew :vpn:testDevUnitTest :vpn:lintDev :vpn:detekt green (136 unit tests, no failures). No live file-manager open was tested (needs a device).
Diff
vpn/src/main/AndroidManifest.xml
diff --git a/vpn/src/main/AndroidManifest.xml b/vpn/src/main/AndroidManifest.xmlindex ba7e9ee3cb..2c1ac932de 100644--- a/vpn/src/main/AndroidManifest.xml+++ b/vpn/src/main/AndroidManifest.xml@@ -41,6 +41,25 @@ <action android:name="android.intent.action.APPLICATION_PREFERENCES" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter>+ <!-- .mavpn bundles are ZIP files under a custom extension, so file+ managers report them as zip/octet-stream (or with no useful+ type): match on content/file URIs scoped by the .mavpn path,+ the same shape notes/ uses for .md and email/ for .eml.+ MainActivity.handleIntent already routes VIEW data URIs to+ the bundle importer. -->+ <intent-filter>+ <action android:name="android.intent.action.VIEW" />+ <category android:name="android.intent.category.DEFAULT" />+ <category android:name="android.intent.category.BROWSABLE" />+ <data android:scheme="content" />+ <data android:scheme="file" />+ <data android:host="*" />+ <data android:mimeType="application/zip" />+ <data android:mimeType="application/x-zip-compressed" />+ <data android:mimeType="application/octet-stream" />+ <data android:pathSuffix=".mavpn" />+ <data android:pathPattern=".*\\.mavpn" />+ </intent-filter> </activity> <!-- systemExempted is the FGS type for preinstalled system apps; this VPN ships in
vpn/src/main/java/com/vayunmathur/vpn/data/MavpnImport.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/data/MavpnImport.kt b/vpn/src/main/java/com/vayunmathur/vpn/data/MavpnImport.ktindex f825d17071..5e16558d76 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/data/MavpnImport.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/data/MavpnImport.kt@@ -87,8 +87,10 @@ private const val DIGEST_BYTES = 6 * Config contents — including private keys — are never logged here. */ object MavpnBundleStore {- fun bundleDir(context: Context, bundleId: String): File =- File(File(context.filesDir, "mavpn-bundles"), safeSegment(bundleId))+ fun bundleDir(context: Context, bundleId: String): File = bundleDir(context.filesDir, bundleId)++ fun bundleDir(filesDir: File, bundleId: String): File =+ File(File(filesDir, "mavpn-bundles"), safeSegment(bundleId)) fun save(context: Context, bundleId: String, bundle: MavpnBundle<WgQuickImport>, manifestJson: String) { val dir = bundleDir(context, bundleId)@@ -106,6 +108,23 @@ object MavpnBundleStore { File(context.filesDir, "mavpn-bundles").listFiles { file -> file.isDirectory } ?.map { it.name }?.sorted().orEmpty() + /**+ * Best-effort removal of one bundle's stored files, for when its last+ * config has been deleted from the database. The database is the source+ * of truth, so a failure here (or a bundle that was never stored) must+ * never fail the delete that triggered it: it reports whether the bundle+ * directory is gone instead of throwing. [safeSegment] confines the target to `mavpn-bundles/`, so a+ * hostile bundle id cannot delete anything outside it.+ */+ fun delete(context: Context, bundleId: String): Boolean = delete(context.filesDir, bundleId)++ fun delete(filesDir: File, bundleId: String): Boolean =+ runCatching {+ val dir = bundleDir(filesDir, bundleId)+ dir.deleteRecursively()+ !dir.exists()+ }.getOrDefault(false)+ private fun safeSegment(raw: String): String = raw.map { char -> if (char.isLetterOrDigit() || char in "._-") char else '-' } .joinToString("").ifBlank { "bundle" }
vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.kt b/vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.ktindex 271afee314..d63b1036dc 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.kt@@ -162,7 +162,19 @@ class VpnViewModel( } fun delete(config: VpnConfig) {- viewModelScope.launch(Dispatchers.IO) { dao.delete(config.toEntity()) }+ viewModelScope.launch(Dispatchers.IO) {+ // The database row goes first and is authoritative: the bundle's+ // files are removed only once no config references the bundle any+ // more, and a failed file cleanup never undoes the delete.+ dao.delete(config.toEntity())+ if (config.bundleId.isBlank()) return@launch+ val bundleStillUsed = dao.getAll().any { it.bundleId == config.bundleId }+ if (!bundleStillUsed) {+ runCatching {+ MavpnBundleStore.delete(getApplication(), config.bundleId)+ }.onFailure { Log.status("VpnVM", "bundle file cleanup failed", it) }+ }+ } } fun upsert(config: VpnConfig, onSaved: ((Long) -> Unit)? = null) {
vpn/src/test/java/com/vayunmathur/vpn/data/MavpnImportTest.kt
diff --git a/vpn/src/test/java/com/vayunmathur/vpn/data/MavpnImportTest.kt b/vpn/src/test/java/com/vayunmathur/vpn/data/MavpnImportTest.ktindex 0ec6f8ec4c..eef200b149 100644--- a/vpn/src/test/java/com/vayunmathur/vpn/data/MavpnImportTest.kt+++ b/vpn/src/test/java/com/vayunmathur/vpn/data/MavpnImportTest.kt@@ -2,10 +2,13 @@ package com.vayunmathur.vpn.data import com.vayunmathur.vpn.domain.MavpnParser import java.io.ByteArrayOutputStream+import java.io.File+import java.nio.file.Files import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream import kotlin.test.Test import kotlin.test.assertEquals+import kotlin.test.assertFalse import kotlin.test.assertNotEquals import kotlin.test.assertNull import kotlin.test.assertTrue@@ -96,6 +99,41 @@ class MavpnImportTest { assertTrue(geo?.name?.contains("Frankfurt") == true) } + @Test fun bundleStoreDeleteRemovesOnlyThatBundle() {+ val filesDir = Files.createTempDirectory("mavpn-store").toFile()+ try {+ val bundleDir = MavpnBundleStore.bundleDir(filesDir, "bundle-a").apply { mkdirs() }+ File(bundleDir, "manifest.json").writeText("{}")+ File(File(bundleDir, "servers").apply { mkdirs() }, "de-1.conf").writeText(conf)+ val otherDir = MavpnBundleStore.bundleDir(filesDir, "bundle-b").apply { mkdirs() }+ File(otherDir, "manifest.json").writeText("{}")++ assertTrue(MavpnBundleStore.delete(filesDir, "bundle-a"))+ assertFalse(bundleDir.exists())+ assertTrue(otherDir.exists())+ assertEquals(listOf("bundle-b"), otherDir.parentFile?.listFiles()?.map { it.name })+ } finally {+ filesDir.deleteRecursively()+ }+ }++ @Test fun bundleStoreDeleteIsBestEffortAndConfined() {+ val root = Files.createTempDirectory("mavpn-store-confined").toFile()+ try {+ val filesDir = File(root, "files").apply { mkdirs() }+ val outside = File(root, "outside.txt").apply { writeText("keep") }++ // A bundle that was never stored deletes cleanly, without throwing.+ assertTrue(MavpnBundleStore.delete(filesDir, "never-stored"))+ // A traversal-shaped id is confined to mavpn-bundles/ by safeSegment.+ MavpnBundleStore.delete(filesDir, "../outside.txt")+ assertTrue(outside.exists())+ assertEquals("keep", outside.readText())+ } finally {+ root.deleteRecursively()+ }+ }+ @Test fun entityRoundTripKeepsBundleMetadata() { val config = VpnConfig( id = 7, name = "n", provider = "P", countryCode = "DE", city = "Berlin",
vpn/src/test/java/com/vayunmathur/vpn/platform/VpnViewModelTest.kt
diff --git a/vpn/src/test/java/com/vayunmathur/vpn/platform/VpnViewModelTest.kt b/vpn/src/test/java/com/vayunmathur/vpn/platform/VpnViewModelTest.ktindex f6959f8c1f..935876d12a 100644--- a/vpn/src/test/java/com/vayunmathur/vpn/platform/VpnViewModelTest.kt+++ b/vpn/src/test/java/com/vayunmathur/vpn/platform/VpnViewModelTest.kt@@ -109,6 +109,40 @@ class VpnViewModelTest { vm.clearStatus(); assertNull(vm.status.value) } } + @Test fun deletingLastBundleConfigRemovesBundleFiles() { runBlocking {+ val dao = FakeConfigDao(); val vm = vm(dao)+ val ctx = app as Context+ val bundleDir = File(File(ctx.filesDir, "mavpn-bundles"), "bundle-1").apply { mkdirs() }+ File(bundleDir, "manifest.json").writeText("{}")+ dao.rows.value = listOf(+ VpnConfigEntity(id = 1, name = "a", bundleId = "bundle-1", bundleServerId = "de-1"),+ VpnConfigEntity(id = 2, name = "b", bundleId = "bundle-1", bundleServerId = "us-1"),+ VpnConfigEntity(id = 3, name = "plain"),+ )+ // Deleting one of two bundle configs keeps the bundle files.+ vm.delete(VpnConfig(id = 1, name = "a", bundleId = "bundle-1", bundleServerId = "de-1"))+ withTimeout(5000) { while (dao.rows.value.any { it.id == 1L }) delay(20) }+ delay(100)+ assertTrue(bundleDir.exists())+ // Deleting the last bundle config removes them; the plain config is untouched.+ vm.delete(VpnConfig(id = 2, name = "b", bundleId = "bundle-1", bundleServerId = "us-1"))+ withTimeout(5000) { while (bundleDir.exists()) delay(20) }+ assertEquals(listOf(3L), dao.rows.value.map { it.id })+ // Deleting a plain (non-bundle) config never touches bundle storage.+ vm.delete(VpnConfig(id = 3, name = "plain"))+ withTimeout(5000) { while (dao.rows.value.isNotEmpty()) delay(20) }+ } }++ @Test fun deletingBundleConfigToleratesMissingBundleFiles() { runBlocking {+ val dao = FakeConfigDao(); val vm = vm(dao)+ dao.rows.value = listOf(+ VpnConfigEntity(id = 1, name = "a", bundleId = "never-stored", bundleServerId = "de-1"),+ )+ vm.delete(VpnConfig(id = 1, name = "a", bundleId = "never-stored", bundleServerId = "de-1"))+ withTimeout(5000) { while (dao.rows.value.isNotEmpty()) delay(20) }+ assertEquals(1, dao.deleted.size)+ } }+ @Test fun stopVpnSetsDisconnectedStatus() { val vm = vm() vm.stopVpn()