Modern Apps git

← Modern-Apps.git

web: private tabs no longer leave persistent site-data and download records

Commit
0d1d02eca95be96ab973ebd4a3dacbaa2b9a531b
Author
Vayun Mathur <[email protected]>
When
2026-12-01 09:48 UTC (5 days ago)
Parents
b5ce9d9
Private must leave no trace, but three persistent write
paths never consulted the owning tab's privacy flag: a
private tab's navigation upserted a storage-info row for its
origin (rendered in Settings), onPageFinished recorded its
storage footprint unconditionally, and the download listener
recorded every private download into the downloads list. The
gates existed only for history (explicitly gated with a
background-tab comment), favicons, thumbnails and tab
persistence — proving these were bugs, not intent; both
clients already captured isPrivateTab and simply did not
thread it to these writes.

Navigation now skips the storage upsert for the owning tab's
privacy (checked per-tabId, matching recordHistoryVisit's
rationale); updateStorageFootprint and addDownload return
early for private/incognito, threaded from the clients and
the listener (the actual DownloadManager enqueue is
untouched). Three regression tests cover a background
private tab's navigation, private footprint/download
records (with normal controls recorded) and incognito.
Verified: :web:testDevUnitTest 361 tests pass; lint errors
are pre-existing on untouched files.

Diff

web/src/main/java/com/vayunmathur/web/platform/WebViewModelSiteData.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/WebViewModelSiteData.kt b/web/src/main/java/com/vayunmathur/web/platform/WebViewModelSiteData.ktindex f7c72eebce..33a44d0010 100644--- a/web/src/main/java/com/vayunmathur/web/platform/WebViewModelSiteData.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/WebViewModelSiteData.kt@@ -34,8 +34,12 @@ fun WebViewModel.updateStorageFootprint(     hasLocalStorage: Boolean,     hasIndexedDb: Boolean,     hasServiceWorker: Boolean,-    estBytes: Long+    estBytes: Long,+    isPrivateTab: Boolean = false ) {+    // Persisted site-data rows are visible outside the private tab (site-data+    // screen, settings count); a private visit must not create or refresh one.+    if (isPrivateTab || incognito) return     scope.launch {         val existing = repository.storage.byOrigin(origin)         val info = if (existing != null) {@@ -108,7 +112,17 @@ fun WebViewModel.clearAllSiteData() {  // ---- Downloads ---- -fun WebViewModel.addDownload(url: String, fileName: String, mime: String?, length: Long) {+fun WebViewModel.addDownload(+    url: String,+    fileName: String,+    mime: String?,+    length: Long,+    isPrivateTab: Boolean = false+) {+    // The file itself still downloads (the user asked for it); only the+    // persisted record — URL + file name in the shared downloads list — is+    // suppressed for a private tab, mirroring recordHistoryVisit.+    if (isPrivateTab || incognito) return     scope.launch {         val entry = DownloadEntry(url = url, fileName = fileName, mimeType = mime, contentLength = length)         repository.downloads.upsert(entry)
web/src/main/java/com/vayunmathur/web/platform/WebViewModelTabs.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/WebViewModelTabs.kt b/web/src/main/java/com/vayunmathur/web/platform/WebViewModelTabs.ktindex d3b182d5ac..d5ee81143c 100644--- a/web/src/main/java/com/vayunmathur/web/platform/WebViewModelTabs.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/WebViewModelTabs.kt@@ -26,7 +26,12 @@ fun WebViewModel.onTabUrlChange(tabId: String, url: String) {         // A native search tab shows its query, not its search:// pseudo-URL.         omniboxText = displayTextForUrl(url)     }-    if (BrowserUtils.isWebUrl(url)) {+    // Site-data bookkeeping is persisted and shown in the normal site-data UI, so a+    // private tab must not write it — same gate as history (recordHistoryVisit),+    // favicons and thumbnails. Use the owning tab's flag, not the active tab's:+    // background tabs change URL while another tab is active.+    val isPrivateTab = incognito || tabs.find { it.id == tabId }?.isPrivate == true+    if (!isPrivateTab && BrowserUtils.isWebUrl(url)) {         val origin = BrowserUtils.originFromUrl(url)         val host = BrowserUtils.hostFromUrl(url)         scope.launch {
web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.kt b/web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.ktindex 5a91bf6e20..0f02325fbe 100644--- a/web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.kt@@ -198,7 +198,7 @@ fun WebViewBrowser(                 setDownloadListener(DownloadListener { url, userAgent, contentDisposition, mimeType, contentLength ->                     val fileName = android.webkit.URLUtil.guessFileName(url, contentDisposition, mimeType)                     Log.dev(WEB_VIEW_BROWSER_TAG, "Download: $fileName $url")-                    viewModel.addDownload(url, fileName, mimeType, contentLength)+                    viewModel.addDownload(url, fileName, mimeType, contentLength, isPrivateTab)                     runCatching {                         val dm = ctx.getSystemService(android.app.DownloadManager::class.java)                         val request = android.app.DownloadManager.Request(Uri.parse(url)).apply {
web/src/main/java/com/vayunmathur/web/ui/WebViewClients.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/WebViewClients.kt b/web/src/main/java/com/vayunmathur/web/ui/WebViewClients.ktindex fc62c6ead6..c34cbd8590 100644--- a/web/src/main/java/com/vayunmathur/web/ui/WebViewClients.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/WebViewClients.kt@@ -122,7 +122,7 @@ internal fun createBrowserWebViewClient(                     val origin = BrowserUtils.originFromUrl(u)                     val cookies = CookieManager.getInstance().getCookie(u)                     val cookieCount = cookies?.split(";")?.count { it.isNotBlank() } ?: 0-                    view.evalJsForStorageInfo(origin, cookieCount, viewModel)+                    view.evalJsForStorageInfo(origin, cookieCount, viewModel, isPrivateTab)                 }.onFailure { e ->                     Log.status(WEB_VIEW_BROWSER_TAG, "storage snapshot failed", e)                 }
web/src/main/java/com/vayunmathur/web/ui/WebViewSettings.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/WebViewSettings.kt b/web/src/main/java/com/vayunmathur/web/ui/WebViewSettings.ktindex fb234c0f22..5ed9118b70 100644--- a/web/src/main/java/com/vayunmathur/web/ui/WebViewSettings.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/WebViewSettings.kt@@ -132,7 +132,12 @@ internal fun applyWebViewSettings(webView: WebView, viewModel: WebViewModel) {     applySafeBrowsing(settings) } -internal fun WebView.evalJsForStorageInfo(origin: String, cookieCount: Int, vm: WebViewModel) {+internal fun WebView.evalJsForStorageInfo(+    origin: String,+    cookieCount: Int,+    vm: WebViewModel,+    isPrivateTab: Boolean = false+) {     evaluateJavascript(         """(function(){             try{@@ -155,7 +160,7 @@ internal fun WebView.evalJsForStorageInfo(origin: String, cookieCount: Int, vm:             val hasIDB = s.contains("\"hasIDB\":true")             val hasSW = s.contains("\"hasSW\":true")             val est = Regex("\"est\":(\\d+)").find(s)?.groupValues?.get(1)?.toLongOrNull() ?: 0L-            vm.updateStorageFootprint(origin, cookieCount, hasLS, hasIDB, hasSW, est)+            vm.updateStorageFootprint(origin, cookieCount, hasLS, hasIDB, hasSW, est, isPrivateTab)         } catch (_: Exception) {}     } }
web/src/test/java/com/vayunmathur/web/platform/PrivatePersistenceLeakTest.kt
diff --git a/web/src/test/java/com/vayunmathur/web/platform/PrivatePersistenceLeakTest.kt b/web/src/test/java/com/vayunmathur/web/platform/PrivatePersistenceLeakTest.ktnew file mode 100644index 0000000000..0a02dafdfd--- /dev/null+++ b/web/src/test/java/com/vayunmathur/web/platform/PrivatePersistenceLeakTest.kt@@ -0,0 +1,137 @@+package com.vayunmathur.web.platform++import android.content.Context+import android.os.Looper+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.web.data.WebDatabase+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertTrue+import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++/**+ * Private tabs must not leave persisted traces in the shared Room stores:+ * site-data rows (Settings / site-data screen) and download records+ * (downloads list) are visible from normal browsing after the private tab+ * is gone. History, favicons and thumbnails already gate on the owning+ * tab's privacy flag; these tests pin the same gate for the storage-info+ * writes in [onTabUrlChange]/[updateStorageFootprint] and for [addDownload].+ */+@RunWith(RobolectricTestRunner::class)+class PrivatePersistenceLeakTest {++    private val context = ApplicationProvider.getApplicationContext<Context>()+    private val db = Room.inMemoryDatabaseBuilder(context, WebDatabase::class.java)+        .allowMainThreadQueries().build()+    private val stores = TestStores(db)+    private val createdVms = mutableListOf<WebViewModel>()++    @AfterTest fun cleanup() {+        val m = androidx.lifecycle.ViewModel::class.java.getDeclaredMethod("onCleared")+        m.isAccessible = true+        createdVms.forEach { runCatching { m.invoke(it) } }+        createdVms.clear()+        context.getSharedPreferences("web_prefs", Context.MODE_PRIVATE).edit().clear().commit()+        db.close()+    }++    private fun vm(windowId: String, incognito: Boolean = false): WebViewModel {+        val v = WebViewModel(stores, context, windowId = windowId, incognito = incognito)+        createdVms += v+        shadowOf(Looper.getMainLooper()).idle()+        return v+    }++    private fun await(description: String, condition: () -> Boolean) {+        runBlocking {+            repeat(300) {+                shadowOf(Looper.getMainLooper()).idle()+                if (condition()) return@runBlocking+                delay(10)+            }+            assertTrue(condition(), "timed out: $description")+        }+    }++    /** Give every already-launched write a chance to land before asserting absence. */+    private fun settle() {+        runBlocking {+            repeat(50) {+                shadowOf(Looper.getMainLooper()).idle()+                delay(10)+            }+            shadowOf(Looper.getMainLooper()).idle()+        }+    }++    @Test fun privateTabUrlChangeDoesNotWriteStorageInfo() {+        val v = vm(windowId = "private-storage-url")+        await("initial tab") { v.tabs.isNotEmpty() }+        v.newTab(url = "https://public.example/", makeActive = true)+        v.newTab(url = "https://secret.example/", isPrivate = true, makeActive = false)+        val publicId = v.tabs.first { it.url == "https://public.example/" }.id+        val secretId = v.tabs.first { it.url == "https://secret.example/" }.id+        // The private tab is a background tab here: gating on the active+        // (normal) tab instead of the owning tab would still leak it.+        v.onTabUrlChange(secretId, "https://secret.example/page")+        v.onTabUrlChange(publicId, "https://public.example/page")+        await("public storage recorded") {+            v.storageInfos.value.any { it.origin == "https://public.example" }+        }+        settle()+        assertTrue(+            v.storageInfos.value.none { it.origin == "https://secret.example" },+            "private tab URL change leaked its origin into persisted storage info",+        )+    }++    @Test fun privateStorageFootprintAndDownloadAreNotPersisted() {+        val v = vm(windowId = "private-storage-download")+        await("initial tab") { v.tabs.isNotEmpty() }+        v.updateStorageFootprint(+            "https://secret.example", cookieCount = 3, hasLocalStorage = true,+            hasIndexedDb = true, hasServiceWorker = false, estBytes = 42, isPrivateTab = true,+        )+        v.addDownload("https://secret.example/file.zip", "file.zip", "application/zip", 42, isPrivateTab = true)+        v.updateStorageFootprint(+            "https://public.example", cookieCount = 1, hasLocalStorage = false,+            hasIndexedDb = false, hasServiceWorker = false, estBytes = 7, isPrivateTab = false,+        )+        v.addDownload("https://public.example/file.txt", "file.txt", "text/plain", 7, isPrivateTab = false)+        await("public storage recorded") {+            v.storageInfos.value.any { it.origin == "https://public.example" }+        }+        await("public download recorded") {+            v.downloads.value.any { it.url == "https://public.example/file.txt" }+        }+        settle()+        assertTrue(+            v.storageInfos.value.none { it.origin == "https://secret.example" },+            "private storage footprint leaked into persisted storage info",+        )+        assertTrue(+            v.downloads.value.none { it.url == "https://secret.example/file.zip" },+            "private download leaked into the persisted downloads list",+        )+    }++    @Test fun incognitoWindowWritesNoStorageInfoOrDownloads() {+        val v = vm(windowId = "private-incognito", incognito = true)+        await("initial tab") { v.tabs.isNotEmpty() }+        val tabId = v.activeTabId!!+        v.onTabUrlChange(tabId, "https://secret.example/page")+        v.updateStorageFootprint(+            "https://secret.example", cookieCount = 1, hasLocalStorage = true,+            hasIndexedDb = false, hasServiceWorker = false, estBytes = 1,+        )+        v.addDownload("https://secret.example/file.zip", "file.zip", "application/zip", 1)+        settle()+        assertTrue(v.storageInfos.value.none { it.origin == "https://secret.example" })+        assertTrue(v.downloads.value.none { it.url == "https://secret.example/file.zip" })+    }+}