Modern Apps git

← Modern-Apps.git

passwords: autofill save can no longer overwrite another site's credential

Commit
80562dfe8264ee4e7ff8402da55c56baa15f03ea
Author
Vayun Mathur <[email protected]>
When
2026-12-01 04:30 UTC (5 days ago)
Parents
7d87600
The autofill-save path chose its update target by username/
email alone, ignoring the save's site entirely. With 'Bank'
(alice, bank-pass) in the vault, a save from shop.example.com
(username alice, password shop-pass) matched the bank entry,
overwrote its password, and created no shop entry: the bank
site is then offered the shop password while the real bank
password is gone. A save from a native app additionally
recorded no site at all, so the entry could never be matched
by a later fill.

Identity matches are now scoped by the existing fill-side
site matching (package incl. android-app://, or web domain
with stored-parent-fills-subdomain semantics): no site-
matching identity entry means create a new entry, never
overwrite; with no site context at all the historical
identity-only update stands. Created entries record the
site (web domain, else android-app://<package>), preserving
the email-shaped-username split. Nine JVM regression tests
cover the cross-site overwrite, site pick, subdomain/package
matching and the no-context fallback. Unlock gating, the
#949 edit flow, search, TOTP (RFC vectors), passkeys and CSV
import were audited and cleared; crypto and Rust untouched.
Verified: :passwords:testDevUnitTest 329 tests pass; lint
errors are pre-existing on untouched files.

Diff

passwords/src/main/java/com/vayunmathur/passwords/platform/PasswordAutofillService.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/platform/PasswordAutofillService.kt b/passwords/src/main/java/com/vayunmathur/passwords/platform/PasswordAutofillService.ktindex 52b09f985d..7352b46e70 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/platform/PasswordAutofillService.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/platform/PasswordAutofillService.kt@@ -22,7 +22,6 @@ import android.widget.RemoteViews import android.widget.inline.InlinePresentationSpec import androidx.autofill.inline.UiVersions import androidx.autofill.inline.v1.InlineSuggestionUi-import androidx.core.net.toUri import com.vayunmathur.library.util.DatabaseHelper import com.vayunmathur.passwords.R import com.vayunmathur.passwords.data.PasswordRepository@@ -83,7 +82,7 @@ class PasswordAutofillService : AutofillService() {                 val allPasswords = repository.getAllPasswords()                  val matches = allPasswords.filter { pass ->-                    pass.websites.any { site -> matchesContext(site, targetPackage, targetWebDomain) }+                    pass.websites.any { site -> autofillSiteMatches(site, targetPackage, targetWebDomain) }                 }                  if (matches.isEmpty()) {@@ -137,6 +136,7 @@ class PasswordAutofillService : AutofillService() {         val parser = StructureParser(request.fillContexts)         val username = parser.usernameText         val password = parser.passwordText+        val targetPackage = request.fillContexts.lastOrNull()?.structure?.activityComponent?.packageName          if (!username.isNullOrBlank() && !password.isNullOrBlank()) {             // SaveCallback is the autofill framework's async contract:@@ -146,20 +146,18 @@ class PasswordAutofillService : AutofillService() {             serviceScope.launch {                 try {                     val candidates = repository.getAllPasswords()-                    val existing = candidates.firstOrNull { it.username == username || it.email == username }+                    // Only an entry for THIS site/app may absorb the new+                    // password. An identity-only match would let a save on+                    // one site overwrite the same username's password on+                    // every other site (see findAutofillSaveTarget).+                    val existing = findAutofillSaveTarget(+                        candidates, username, targetPackage, parser.webDomain,+                    )                     if (existing != null) {                         repository.upsertPassword(existing.copy(password = password))                     } else {-                        val looksLikeEmail = username.contains("@")                         repository.upsertPassword(-                            Password(-                                name = "Saved Login",-                                username = if (looksLikeEmail) "" else username,-                                email = if (looksLikeEmail) username else "",-                                password = password,-                                totpSecret = null,-                                websites = listOfNotNull(parser.webDomain)-                            )+                            newAutofillSavedPassword(username, password, targetPackage, parser.webDomain)                         )                     }                     callback.onSuccess()@@ -210,30 +208,8 @@ class PasswordAutofillService : AutofillService() {         return builder.build()     } -    private fun matchesContext(storedSite: String, currentPkg: String?, currentWeb: String?): Boolean {-        if (currentPkg != null) {-            val normalized = storedSite.trim().lowercase().removeSuffix("/")-            val pkg = currentPkg.lowercase()-            if (normalized == pkg || normalized == "android-app://$pkg") return true-        }--        if (currentWeb != null) {-            val currentHost = try {-                val uri = if (currentWeb.contains("://")) currentWeb.toUri() else "https://$currentWeb".toUri()-                uri.host?.lowercase() ?: currentWeb-            } catch (_: IllegalArgumentException) {-                currentWeb-            }-            // The stored site is the parent: saving example.com fills on login.example.com, but-            // saving login.example.com does not fill on bare example.com.-            return DomainMatch.isSameSiteOrSubdomain(-                DomainMatch.normalizeSite(currentHost),-                DomainMatch.normalizeSite(storedSite),-            )-        }--        return false-    }+    private fun matchesContext(storedSite: String, currentPkg: String?, currentWeb: String?): Boolean =+        autofillSiteMatches(storedSite, currentPkg, currentWeb)      private class StructureParser(contexts: List<FillContext>) {         var usernameId: AutofillId? = null@@ -309,3 +285,75 @@ class PasswordAutofillService : AutofillService() {         }     } }++/**+ * True when a stored [storedSite] belongs to the autofill context identified+ * by [currentPkg] (the requesting app) and/or [currentWeb] (the page's web+ * domain). Pure and framework-free so the save/fill matching rules can be+ * unit tested without the vault.+ */+internal fun autofillSiteMatches(storedSite: String, currentPkg: String?, currentWeb: String?): Boolean {+    if (currentPkg != null) {+        val normalized = storedSite.trim().lowercase().removeSuffix("/")+        val pkg = currentPkg.lowercase()+        if (normalized == pkg || normalized == "android-app://$pkg") return true+    }++    if (currentWeb != null) {+        // The stored site is the parent: saving example.com fills on login.example.com, but+        // saving login.example.com does not fill on bare example.com. normalizeSite+        // reduces either spelling (bare host or full URL) to the bare host.+        return DomainMatch.isSameSiteOrSubdomain(+            DomainMatch.normalizeSite(currentWeb),+            DomainMatch.normalizeSite(storedSite),+        )+    }++    return false+}++/**+ * The existing entry an autofill save for [username] may update, or null when+ * the save must create a new entry.+ *+ * Identity alone is not enough: the same username on a different site is a+ * different credential, and overwriting it would both lose that site's+ * password and leave the new site with no entry of its own. So when the save+ * context names a site/app, only an identity match whose websites match that+ * context may absorb the new password. With no site context at all there is+ * nothing safer to key on, so the historical identity-only update applies.+ */+internal fun findAutofillSaveTarget(+    candidates: List<Password>,+    username: String,+    targetPackage: String?,+    targetWebDomain: String?,+): Password? {+    val identityMatches = candidates.filter { it.username == username || it.email == username }+    if (identityMatches.isEmpty()) return null+    if (targetPackage == null && targetWebDomain == null) return identityMatches.first()+    return identityMatches.firstOrNull { entry ->+        entry.websites.any { site -> autofillSiteMatches(site, targetPackage, targetWebDomain) }+    }+}++/** The fresh entry an autofill save creates when [findAutofillSaveTarget] finds no target. */+internal fun newAutofillSavedPassword(+    username: String,+    password: String,+    targetPackage: String?,+    targetWebDomain: String?,+): Password {+    val looksLikeEmail = username.contains("@")+    return Password(+        name = "Saved Login",+        username = if (looksLikeEmail) "" else username,+        email = if (looksLikeEmail) username else "",+        password = password,+        totpSecret = null,+        // Record where this credential belongs so a later fill can match it:+        // the web domain when the save came from a page, otherwise the+        // requesting app (the spelling autofillSiteMatches accepts).+        websites = listOfNotNull(targetWebDomain ?: targetPackage?.let { "android-app://$it" }),+    )+}
passwords/src/test/java/com/vayunmathur/passwords/platform/AutofillSaveTargetTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/AutofillSaveTargetTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/AutofillSaveTargetTest.ktnew file mode 100644index 0000000000..d07c1a3c8c--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/AutofillSaveTargetTest.kt@@ -0,0 +1,137 @@+package com.vayunmathur.passwords.platform++import com.vayunmathur.passwords.data.Password+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Regression tests for the autofill-save site scoping in+ * [findAutofillSaveTarget] / [newAutofillSavedPassword].+ *+ * The bug: `onSaveRequest` used to pick the entry to update by username/email+ * alone (`candidates.firstOrNull { it.username == username || it.email == username }`),+ * ignoring the site the save came from. With a vault holding alice's bank+ * password, saving alice's new shop password overwrote the bank entry and+ * created no shop entry at all — after which the bank site was offered the+ * shop password.+ *+ * These are plain JVM tests: the matching helpers are framework-free by+ * design, so no Robolectric or vault is needed.+ */+class AutofillSaveTargetTest {++    private val bank = Password(+        id = 1, name = "Bank", username = "alice", password = "bank-pass",+        websites = listOf("https://bank.example.com"),+    )+    private val shop = Password(+        id = 2, name = "Shop", username = "alice", password = "shop-pass-old",+        websites = listOf("https://shop.example.com"),+    )++    @Test fun saveOnAnotherSiteDoesNotTargetExistingEntry() {+        // Exact bug scenario: only the bank entry exists; the save arrives+        // from shop.example.com with the same username.+        val target = findAutofillSaveTarget(+            candidates = listOf(bank),+            username = "alice",+            targetPackage = "com.android.chrome",+            targetWebDomain = "shop.example.com",+        )+        assertNull(target)+    }++    @Test fun savePicksTheSiteMatchingEntryNotTheFirstIdentityMatch() {+        val target = findAutofillSaveTarget(+            candidates = listOf(bank, shop),+            username = "alice",+            targetPackage = "com.android.chrome",+            targetWebDomain = "shop.example.com",+        )+        assertEquals(shop, target)+    }++    @Test fun saveOnSubdomainTargetsParentSiteEntry() {+        val target = findAutofillSaveTarget(+            candidates = listOf(bank),+            username = "alice",+            targetPackage = "com.android.chrome",+            targetWebDomain = "login.bank.example.com",+        )+        assertEquals(bank, target)+    }++    @Test fun saveInAppTargetsPackageEntryAndRejectsOtherApps() {+        val appEntry = Password(+            id = 3, name = "App", username = "alice", password = "app-pass",+            websites = listOf("android-app://com.example.app"),+        )+        assertEquals(+            appEntry,+            findAutofillSaveTarget(listOf(appEntry, bank), "alice", "com.example.app", null),+        )+        assertNull(findAutofillSaveTarget(listOf(appEntry), "alice", "com.other.app", null))+    }++    @Test fun saveMatchesOnEmailIdentityWithinSameSite() {+        val emailEntry = Password(+            id = 4, name = "Mail", username = "", email = "[email protected]",+            password = "mail-pass", websites = listOf("example.com"),+        )+        assertEquals(+            emailEntry,+            findAutofillSaveTarget(+                listOf(emailEntry), "[email protected]", "com.android.chrome", "example.com",+            ),+        )+        // Same identity, different site: still no target.+        assertNull(+            findAutofillSaveTarget(+                listOf(emailEntry), "[email protected]", "com.android.chrome", "other.example",+            )+        )+    }++    @Test fun saveWithoutSiteContextKeepsIdentityOnlyUpdate() {+        assertEquals(+            bank,+            findAutofillSaveTarget(listOf(bank, shop), "alice", null, null),+        )+        assertNull(findAutofillSaveTarget(listOf(bank), "bob", null, null))+    }++    @Test fun identityMatchWithNoWebsitesCannotAbsorbScopedSave() {+        val siteless = Password(+            id = 5, name = "Manual", username = "alice", password = "manual-pass",+        )+        assertNull(+            findAutofillSaveTarget(+                listOf(siteless), "alice", "com.android.chrome", "shop.example.com",+            )+        )+    }++    @Test fun newEntryRecordsWebDomainOrAppPackage() {+        val web = newAutofillSavedPassword("alice", "new-pass", "com.android.chrome", "shop.example.com")+        assertEquals(listOf("shop.example.com"), web.websites)+        assertEquals("alice", web.username)+        assertEquals("", web.email)+        assertEquals("new-pass", web.password)++        val app = newAutofillSavedPassword("alice", "new-pass", "com.example.app", null)+        assertEquals(listOf("android-app://com.example.app"), app.websites)++        // A created entry must be findable by a later save/fill for its site.+        assertTrue(autofillSiteMatches(app.websites.single(), "com.example.app", null))+        assertTrue(autofillSiteMatches(web.websites.single(), "com.android.chrome", "shop.example.com"))+    }++    @Test fun newEntrySplitsEmailShapedUsername() {+        val entry = newAutofillSavedPassword("[email protected]", "new-pass", null, "example.com")+        assertEquals("", entry.username)+        assertEquals("[email protected]", entry.email)+        assertEquals(listOf("example.com"), entry.websites)+    }+}