Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update Android autofill matching logic to match other platforms (#1120)
Leendert de Borst893c06cc0021
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/CredentialMatcher.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/CredentialMatcher.ktindex 5e5d7be1c..929045789 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/CredentialMatcher.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/CredentialMatcher.kt@@ -4,27 +4,37 @@ import net.aliasvault.app.vaultstore.models.Credential/*** Helper class to match credentials against app/website information for autofill.- * This class handles the logic of determining which credentials are relevant- * for a given app or website context.+ * This implementation matches the iOS filtering logic exactly for cross-platform consistency.*/object CredentialMatcher {-+/*** Extract domain from URL, handling both full URLs and partial domains.- * @param url URL or domain string+ * @param urlString URL or domain string* @return Normalized domain without protocol or www*/- private fun extractDomain(url: String): String {- var domain = url.trim().lowercase()+ private fun extractDomain(urlString: String): String {+ if (urlString.isBlank()) return ""++ var domain = urlString.lowercase().trim()// Remove protocol if present- domain = domain.removePrefix("https://").removePrefix("http://")+ domain = domain.replace("https://", "").replace("http://", "")// Remove www. prefix- domain = domain.removePrefix("www.")+ domain = domain.replace("www.", "")// Remove path, query, and fragmentdomain = domain.substringBefore("/").substringBefore("?").substringBefore("#")return domain}-++ /**+ * Extract root domain from a domain string.+ * E.g., "sub.example.com" -> "example.com"+ */+ private fun extractRootDomain(domain: String): String {+ val parts = domain.split(".")+ return if (parts.size >= 2) parts.takeLast(2).joinToString(".") else domain+ }+/*** Check if two domains match, supporting partial matches.* @param domain1 First domain@@ -32,116 +42,81 @@ object CredentialMatcher {* @return True if domains match (including partial matches)*/private fun domainsMatch(domain1: String, domain2: String): Boolean {- if (domain1.isBlank() || domain2.isBlank()) return false-val d1 = extractDomain(domain1)val d2 = extractDomain(domain2)-+// Exact matchif (d1 == d2) return true-+// Check if one domain contains the other (for subdomain matching)if (d1.contains(d2) || d2.contains(d1)) return true-+// Check root domain matchval d1Root = extractRootDomain(d1)val d2Root = extractRootDomain(d2)-+return d1Root == d2Root}-+/**- * Filters a list of credentials based on app/package name or URL.- * Matching strategies in order of priority:- * 1. Exact domain match- * 2. Partial domain match (root domain match)- * 3. Domain key match (package middle segment or domain without TLD)- * 4. General text matching on service name and notes+ * Filter credentials based on search text with anti-phishing protection.+ * @param credentials List of credentials to filter+ * @param searchText Search term (app info, URL, etc.)+ * @return Filtered list of credentials+ *+ * **Security Note**: When searching with a URL, text search fallback only applies to+ * credentials with no service URL defined. This prevents phishing attacks where a+ * malicious site might match credentials intended for the legitimate site.*/fun filterCredentialsByAppInfo(credentials: List<Credential>,- appInfo: String,+ searchText: String,): List<Credential> {- if (appInfo.isBlank()) {+ if (searchText.isEmpty()) {return credentials}- val input = appInfo.trim()- val inputDomain = extractDomain(input)- val isPackageName = input.lowercase().matches(Regex("^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)+$"))-- val domainKey: String = if (isPackageName) {- // Extract key from package name (e.g., "coolblue" from "com.coolblue.app")- val parts = input.split('.')- if (parts.size >= 3) parts[1] else parts.firstOrNull() ?: input- } else {- // Extract domain without extension- extractDomainWithoutExtension(inputDomain)- }+ // Try to parse as URL first+ val searchDomain = extractDomain(searchText)- val matches = mutableListOf<Credential>()- val matchedIds = mutableSetOf<String>()-- // Priority 1: Domain matches (exact and partial)- if (inputDomain.isNotBlank()) {- credentials.forEach { cred ->- val serviceUrl = cred.service.url- if (!serviceUrl.isNullOrBlank() && cred.id !in matchedIds) {- if (domainsMatch(input, serviceUrl)) {- matches.add(cred)- matchedIds.add(cred.id)+ if (searchDomain.isNotEmpty()) {+ val matches = mutableSetOf<Credential>()++ // Check for domain matches with priority+ credentials.forEach { credential ->+ val serviceUrl = credential.service.url+ if (!serviceUrl.isNullOrEmpty()) {+ if (domainsMatch(searchText, serviceUrl)) {+ matches.add(credential)}}}- }-- // Priority 2: Domain key match against service name and notes- if (domainKey.isNotBlank()) {- credentials.forEach { cred ->- if (cred.id !in matchedIds) {- val nameMatches = cred.service.name?.lowercase()?.contains(domainKey) == true- val notesMatches = cred.notes?.lowercase()?.contains(domainKey) == true-- if (nameMatches || notesMatches) {- matches.add(cred)- matchedIds.add(cred.id)- }++ // SECURITY: If no domain matches found, only search text in credentials with NO service URL+ // This prevents phishing attacks by ensuring URL-based credentials only match their domains+ if (matches.isEmpty()) {+ val domainParts = searchDomain.split(".")+ val domainWithoutExtension = domainParts.firstOrNull()?.lowercase() ?: searchDomain.lowercase()++ val nameMatches = credentials.filter { credential ->+ // CRITICAL: Only search in credentials that have no service URL defined+ if (!credential.service.url.isNullOrEmpty()) return@filter false+ val serviceNameMatch = credential.service.name?.lowercase()?.contains(domainWithoutExtension) ?: false+ val notesMatch = credential.notes?.lowercase()?.contains(domainWithoutExtension) ?: false+ serviceNameMatch || notesMatch}+ matches.addAll(nameMatches)}- }-- // Priority 3: Fallback text search if no matches found- if (matches.isEmpty()) {- val searchText = input.lowercase()- credentials.forEach { cred ->- val nameMatches = cred.service.name?.lowercase()?.contains(searchText) == true- val urlMatches = cred.service.url?.lowercase()?.contains(searchText) == true- val notesMatches = cred.notes?.lowercase()?.contains(searchText) == true-- if (nameMatches || urlMatches || notesMatches) {- matches.add(cred)- }++ return matches.toList()+ } else {+ // Non-URL fallback: simple text search in service name, username, or notes+ val lowercasedSearch = searchText.lowercase()+ return credentials.filter { credential ->+ (credential.service.name?.lowercase()?.contains(lowercasedSearch) ?: false) ||+ (credential.username?.lowercase()?.contains(lowercasedSearch) ?: false) ||+ (credential.notes?.lowercase()?.contains(lowercasedSearch) ?: false)}}-- // Deduplicate matches based on credential ID to avoid duplicates from different matching strategies- return matches.distinctBy { it.id }- }-- /**- * Extracts the root domain from a host string.- * E.g., "sub.example.com" -> "example.com"- */- private fun extractRootDomain(host: String): String {- val parts = host.split('.')- return if (parts.size >= 2) parts.takeLast(2).joinToString(".") else host- }-- /**- * Extracts the domain key (name without extension/TLD).- * E.g., "example.com" -> "example"- */- private fun extractDomainWithoutExtension(domain: String): String {- return domain.substringBefore('.')}}diff --git a/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/AutofillTest.kt b/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/AutofillTest.ktindex 08c10e17a..40bfd66a3 100644--- a/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/AutofillTest.kt+++ b/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/AutofillTest.kt@@ -21,36 +21,11 @@ class AutofillTest {@Beforefun setup() {- // Create test credentials- testCredentials = listOf(- createTestCredential(- "Gmail",- "https://gmail.com",- "[email protected]",- ),- createTestCredential(- "Google",- "https://google.com",- "[email protected]",- ),- createTestCredential(- "Coolblue",- "https://www.coolblue.nl",- "[email protected]",- ),- createTestCredential(- "Amazon",- "https://amazon.com",- "[email protected]",- ),- createTestCredential(- "Coolblue App",- "com.coolblue.app",- "[email protected]",- ),- )+ // Create test credentials using shared test data structure+ testCredentials = createSharedTestCredentials()}+ // [#1] - Exact URL match@Testfun testExactUrlMatch() {val matches = CredentialMatcher.filterCredentialsByAppInfo(@@ -58,11 +33,11 @@ class AutofillTest {"www.coolblue.nl",)- assertEquals(2, matches.size)+ assertEquals(1, matches.size)assertEquals("Coolblue", matches[0].service.name)- assertEquals("Coolblue App", matches[1].service.name)}+ // [#2] - Base URL with path match@Testfun testBaseUrlMatch() {val matches = CredentialMatcher.filterCredentialsByAppInfo(@@ -74,6 +49,7 @@ class AutofillTest {assertEquals("Gmail", matches[0].service.name)}+ // [#3] - Root domain with subdomain match@Testfun testRootDomainMatch() {val matches = CredentialMatcher.filterCredentialsByAppInfo(@@ -85,50 +61,256 @@ class AutofillTest {assertEquals("Google", matches[0].service.name)}+ // [#4] - No matches for non-existent domain+ @Test+ fun testNoMatches() {+ val matches = CredentialMatcher.filterCredentialsByAppInfo(+ testCredentials,+ "https://nonexistent.com",+ )++ assertTrue(matches.isEmpty())+ }++ // [#5] - Partial URL stored matches full URL search+ @Test+ fun testPartialUrlMatchWithFullUrl() {+ // Test case: stored URL is "dumpert.nl", search with full URL+ val matches = CredentialMatcher.filterCredentialsByAppInfo(+ testCredentials,+ "https://www.dumpert.nl",+ )++ assertEquals(1, matches.size)+ assertEquals("Dumpert", matches[0].service.name)+ }++ // [#6] - Full URL stored matches partial URL search+ @Test+ fun testFullUrlMatchWithPartialUrl() {+ // Test case: stored URL is full, search with partial+ val matches = CredentialMatcher.filterCredentialsByAppInfo(+ testCredentials,+ "coolblue.nl",+ )++ assertEquals(1, matches.size)+ assertEquals("Coolblue", matches[0].service.name)+ }++ // [#7] - Protocol variations (http/https/none) match+ @Test+ fun testProtocolVariations() {+ // Test that http and https variations match+ val httpsMatches = CredentialMatcher.filterCredentialsByAppInfo(+ testCredentials,+ "https://github.com",+ )+ val httpMatches = CredentialMatcher.filterCredentialsByAppInfo(+ testCredentials,+ "http://github.com",+ )+ val noProtocolMatches = CredentialMatcher.filterCredentialsByAppInfo(+ testCredentials,+ "github.com",+ )++ assertEquals(1, httpsMatches.size)+ assertEquals(1, httpMatches.size)+ assertEquals(1, noProtocolMatches.size)+ assertEquals("GitHub", httpsMatches[0].service.name)+ assertEquals("GitHub", httpMatches[0].service.name)+ assertEquals("GitHub", noProtocolMatches[0].service.name)+ }++ // [#8] - WWW prefix variations match+ @Test+ fun testWwwVariations() {+ // Test that www variations match+ val withWww = CredentialMatcher.filterCredentialsByAppInfo(+ testCredentials,+ "www.dumpert.nl",+ )+ val withoutWww = CredentialMatcher.filterCredentialsByAppInfo(+ testCredentials,+ "dumpert.nl",+ )++ assertEquals(1, withWww.size)+ assertEquals(1, withoutWww.size)+ assertEquals("Dumpert", withWww[0].service.name)+ assertEquals("Dumpert", withoutWww[0].service.name)+ }++ // [#9] - Subdomain matching+ @Test+ fun testSubdomainMatching() {+ // Test subdomain matching+ val appSubdomain = CredentialMatcher.filterCredentialsByAppInfo(+ testCredentials,+ "https://app.example.com",+ )+ val wwwSubdomain = CredentialMatcher.filterCredentialsByAppInfo(+ testCredentials,+ "https://www.example.com",+ )+ val noSubdomain = CredentialMatcher.filterCredentialsByAppInfo(+ testCredentials,+ "https://example.com",+ )++ assertEquals(1, appSubdomain.size)+ assertEquals("Subdomain Example", appSubdomain[0].service.name)+ assertEquals(1, wwwSubdomain.size)+ assertEquals("Subdomain Example", wwwSubdomain[0].service.name)+ assertEquals(1, noSubdomain.size)+ assertEquals("Subdomain Example", noSubdomain[0].service.name)+ }++ // [#10] - Paths and query strings ignored+ @Test+ fun testPathAndQueryIgnored() {+ // Test that paths and query strings are ignored+ val withPath = CredentialMatcher.filterCredentialsByAppInfo(+ testCredentials,+ "https://github.com/user/repo",+ )+ val withQuery = CredentialMatcher.filterCredentialsByAppInfo(+ testCredentials,+ "https://stackoverflow.com/questions?tab=newest",+ )+ val withFragment = CredentialMatcher.filterCredentialsByAppInfo(+ testCredentials,+ "https://gmail.com#inbox",+ )++ assertEquals(1, withPath.size)+ assertEquals("GitHub", withPath[0].service.name)+ assertEquals(1, withQuery.size)+ assertEquals("Stack Overflow", withQuery[0].service.name)+ assertEquals(1, withFragment.size)+ assertEquals("Gmail", withFragment[0].service.name)+ }++ // [#11] - Complex URL variations+ @Test+ fun testComplexUrlVariations() {+ // Test complex URL matching scenario+ val complexUrl = CredentialMatcher.filterCredentialsByAppInfo(+ testCredentials,+ "https://www.coolblue.nl/product/12345?ref=google",+ )++ assertEquals(1, complexUrl.size)+ assertEquals("Coolblue", complexUrl[0].service.name)+ }++ // [#13] - Title-only matching+ @Test+ fun testTitleOnlyMatching() {+ // Test service name matching when no URL is available+ val matches = CredentialMatcher.filterCredentialsByAppInfo(+ testCredentials,+ "newyorktimes",+ )++ assertEquals(1, matches.size)+ assertEquals("Title Only newyorktimes", matches[0].service.name)+ }++ // [#14] - Domain name part matching (Android specific)@Testfun testDomainNamePartMatch() {+ // Test that unrelated domains don't match (coolblue.be doesn't match coolblue.nl)val matches = CredentialMatcher.filterCredentialsByAppInfo(testCredentials,"https://coolblue.be",)- assertEquals(2, matches.size)- assertTrue(matches.any { it.service.name == "Coolblue" })- assertTrue(matches.any { it.service.name == "Coolblue App" })+ // Should find no matches due to anti-phishing protection (Coolblue has URL so won't match on text)+ assertTrue(matches.isEmpty())+ }++ // [#12] - Priority ordering (not applicable to Android)+ @Test+ fun testPriorityOrdering() {+ // Android doesn't implement priority ordering like browser extension+ // but we include the test for cross-platform consistency+ val matches = CredentialMatcher.filterCredentialsByAppInfo(+ testCredentials,+ "coolblue.nl",+ )++ // Android should find domain match+ assertEquals(1, matches.size)+ assertEquals("Coolblue", matches[0].service.name)}+ // [#15] - Package name matching@Testfun testPackageNameMatch() {+ // Package names should match exact URL.val matches = CredentialMatcher.filterCredentialsByAppInfo(testCredentials,"com.coolblue.app",)- assertEquals(2, matches.size)- assertTrue(matches.any { it.service.name == "Coolblue" })+ // Should find exact URL match for "Coolblue App"+ assertEquals(1, matches.size)assertTrue(matches.any { it.service.name == "Coolblue App" })}+ // [#16] - Invalid URL handling@Test- fun testNoMatches() {+ fun testInvalidUrl() {val matches = CredentialMatcher.filterCredentialsByAppInfo(testCredentials,- "https://nonexistent.com",+ "not a url",)assertTrue(matches.isEmpty())}+ // [#17] - Anti-phishing protection@Test- fun testInvalidUrl() {+ fun testAntiPhishingProtection() {+ // Test that credentials with URLs don't match on text when URL is providedval matches = CredentialMatcher.filterCredentialsByAppInfo(testCredentials,- "not a url",+ "https://secure-bankk.com", // Phishing domain (extra 'k'))+ // Should find no matches - Bank Account has URL so won't match on textassertTrue(matches.isEmpty())}+ /**+ * Creates the shared test credential dataset used across all platforms.+ * This ensures consistent testing across Browser Extension, iOS, and Android.+ */+ private fun createSharedTestCredentials(): List<Credential> {+ return listOf(+ createTestCredential("Gmail", "https://gmail.com", "[email protected]"),+ createTestCredential("Google", "https://google.com", "[email protected]"),+ createTestCredential("Coolblue", "https://www.coolblue.nl", "[email protected]"),+ createTestCredential("Amazon", "https://amazon.com", "[email protected]"),+ createTestCredential("Coolblue App", "com.coolblue.app", "[email protected]"),+ createTestCredential("Dumpert", "dumpert.nl", "[email protected]"),+ createTestCredential("GitHub", "github.com", "[email protected]"),+ createTestCredential("Stack Overflow", "https://stackoverflow.com", "[email protected]"),+ createTestCredential("Subdomain Example", "https://app.example.com", "[email protected]"),+ createTestCredential("Title Only newyorktimes", "", ""),+ createTestCredential("Bank Account", "https://secure-bank.com", "[email protected]"),+ )+ }++ /**+ * Helper function to create test credentials with standardized structure.+ * @param serviceName The name of the service+ * @param serviceUrl The URL of the service+ * @param username The username for the service+ * @return A test credential matching the Android Credential type+ */private fun createTestCredential(serviceName: String,serviceUrl: String,