Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add credentialmatcher and autofill test scaffolding (#846)

Leendert de Borst765625b16378
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/AutofillService.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/AutofillService.kt
index 1789bd089..bdcc7c7e6 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/AutofillService.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/AutofillService.kt
@@ -41,9 +41,11 @@ import android.widget.RemoteViews
import net.aliasvault.app.vaultstore.VaultStore
import net.aliasvault.app.vaultstore.VaultStore.CredentialOperationCallback
import net.aliasvault.app.vaultstore.models.Credential
+import net.aliasvault.app.autofill.CredentialMatcher
class AutofillService : AutofillService() {
private val TAG = "AliasVaultAutofill"
+ private val credentialMatcher = CredentialMatcher()
override fun onFillRequest(
request: FillRequest,
@@ -64,6 +66,7 @@ class AutofillService : AutofillService() {
// Find any autofillable fields in the form
val fieldFinder = FieldFinder()
+ fieldFinder.structure = structure
parseStructure(structure, fieldFinder)
// If no password field was found, return an empty response
@@ -87,7 +90,7 @@ class AutofillService : AutofillService() {
// In a full implementation, you would:
// 1. Extract the username/password from the SaveRequest
// 2. Launch an activity to let the user confirm saving
- // 3. Save the credential using the SharedCredentialStore
+ // 3. Save the credential using the VaultStore
// For now, just acknowledge the request
callback.onSuccess()
@@ -96,6 +99,17 @@ class AutofillService : AutofillService() {
private fun launchActivityForAutofill(fieldFinder: FieldFinder, callback: FillCallback) {
Log.d(TAG, "Launching activity for autofill authentication")
+ // Get the app/website information from the structure
+ val appInfo = getAppInfo(fieldFinder.structure)
+ Log.d(TAG, "Autofill request from: $appInfo")
+
+ // Ignore requests from our own unlock page as this would cause a loop
+ if (appInfo == "net.aliasvault.app") {
+ Log.d(TAG, "Skipping autofill request from AliasVault app itself")
+ callback.onSuccess(null)
+ return
+ }
+
// First try to get an existing instance
val store = VaultStore.getExistingInstance()
@@ -112,11 +126,27 @@ class AutofillService : AutofillService() {
return
}
- // Create a response with all credentials
+ // Filter credentials based on app/website info
+ val filteredCredentials = if (appInfo != null) {
+ filterCredentialsByAppInfo(result, appInfo)
+ } else {
+ result
+ }
+
+ Log.d(TAG, "Amount of credentials filtered with this app info: ${filteredCredentials.size}")
+
+ // If there are no results, disable autofill.
+ if (filteredCredentials.size == 0) {
+ Log.d(TAG, "No credentials found for this app, disabling autofill")
+ callback.onSuccess(null)
+ return
+ }
+
+ // Create a response with filtered credentials
val responseBuilder = FillResponse.Builder()
// Add each credential as a dataset
- for (credential in result) {
+ for (credential in filteredCredentials) {
// Create a dataset for this credential
addDatasetForCredential(responseBuilder, fieldFinder, credential)
}
@@ -157,6 +187,95 @@ class AutofillService : AutofillService() {
startActivity(intent)
}
+ private fun getAppInfo(structure: AssistStructure?): String? {
+ if (structure == null) {
+ return null
+ }
+
+ // First check if this is web content
+ val nodeCount = structure.windowNodeCount
+ for (i in 0 until nodeCount) {
+ val windowNode = structure.getWindowNodeAt(i)
+ val rootNode = windowNode.rootViewNode
+
+ // Check for web-specific information
+ val webInfo = findWebInfoInNode(rootNode)
+ if (webInfo != null) {
+ Log.d(TAG, "Found web info: $webInfo")
+ return webInfo
+ }
+ }
+
+ // If no web info found, fall back to package name
+ val packageName = structure.activityComponent?.packageName
+ if (packageName != null) {
+ Log.d(TAG, "Using package name: $packageName")
+ return packageName
+ }
+
+ return null
+ }
+
+ private fun findWebInfoInNode(node: AssistStructure.ViewNode): String? {
+ // Check for web domain
+ val webDomain = node.webDomain
+ if (webDomain != null) {
+ return webDomain
+ }
+
+ // Check for web URL
+ val webUrl = node.webDomain
+ if (webUrl != null) {
+ try {
+ val uri = android.net.Uri.parse(webUrl)
+ val host = uri.host
+ if (host != null) {
+ return host
+ }
+ } catch (e: Exception) {
+ Log.e(TAG, "Error parsing web URL: $webUrl", e)
+ }
+ }
+
+ // Check HTML info for domain or URL
+ val htmlInfo = node.htmlInfo
+ if (htmlInfo != null) {
+ val attributes = htmlInfo.attributes
+ if (attributes != null) {
+ for (i in 0 until attributes.size) {
+ val name = attributes.get(i)?.first
+ val value = attributes.get(i)?.second
+ if (name == "domain" || name == "host" || name == "url") {
+ return value
+ }
+ }
+ }
+ }
+
+ // Check for web-specific hints
+ val hints = node.autofillHints
+ if (hints != null) {
+ for (hint in hints) {
+ if (hint.contains("web", ignoreCase = true) ||
+ hint.contains("url", ignoreCase = true) ||
+ hint.contains("domain", ignoreCase = true)) {
+ return hint
+ }
+ }
+ }
+
+ // Recursively check child nodes
+ val childCount = node.childCount
+ for (i in 0 until childCount) {
+ val webInfo = findWebInfoInNode(node.getChildAt(i))
+ if (webInfo != null) {
+ return webInfo
+ }
+ }
+
+ return null
+ }
+
// Helper method to create a dataset from a credential
private fun addDatasetForCredential(
responseBuilder: FillResponse.Builder,
@@ -332,12 +451,17 @@ class AutofillService : AutofillService() {
return false
}
+ private fun filterCredentialsByAppInfo(credentials: List<Credential>, appInfo: String): List<Credential> {
+ return credentialMatcher.filterCredentialsByAppInfo(credentials, appInfo)
+ }
+
private class FieldFinder {
// Store pairs of (AutofillId, isPasswordField)
val autofillableFields = mutableListOf<Pair<AutofillId, Boolean>>()
var foundPasswordField = false
var lastUsernameField: AutofillId? = null
var lastField: AutofillId? = null
+ var structure: AssistStructure? = null
}
companion object {
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/CredentialMatcher.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/CredentialMatcher.kt
new file mode 100644
index 000000000..ad050aa6e
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/CredentialMatcher.kt
@@ -0,0 +1,122 @@
+package net.aliasvault.app.autofill
+
+import android.net.Uri
+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.
+ */
+class CredentialMatcher {
+ /**
+ * Filters a list of credentials based on app/website information.
+ * Uses multiple matching strategies in order of specificity:
+ * 1. Exact URL match
+ * 2. Base URL match (excluding query/path)
+ * 3. Root domain match
+ * 4. Domain name part match
+ * 5. General text matching on service name, username, and URL
+ */
+ fun filterCredentialsByAppInfo(credentials: List<Credential>, appInfo: String): List<Credential> {
+ // First try URL-based matching
+ val uri = try {
+ Uri.parse(appInfo)
+ } catch (e: Exception) {
+ null
+ }
+
+ val matches = mutableListOf<Credential>()
+
+ if (uri != null && uri.host != null) {
+ val host = uri.host!!
+ val baseUrl = "${uri.scheme}://$host"
+ val rootDomain = extractRootDomain(host)
+ val domainWithoutExtension = extractDomainWithoutExtension(rootDomain)
+
+ // 1. Exact URL match
+ matches.addAll(credentials.filter { credential ->
+ credential.service.url?.equals(appInfo, ignoreCase = true) == true
+ })
+
+ // 2. Base URL match (excluding query/path)
+ if (matches.isEmpty()) {
+ matches.addAll(credentials.filter { credential ->
+ credential.service.url?.startsWith(baseUrl, ignoreCase = true) == true
+ })
+ }
+
+ // 3. Root domain match (e.g., coolblue.nl)
+ if (matches.isEmpty()) {
+ matches.addAll(credentials.filter { credential ->
+ credential.service.url?.let { url ->
+ extractRootDomain(url)?.equals(rootDomain, ignoreCase = true) == true
+ } ?: false
+ })
+ }
+
+ // 4. Domain name part match (e.g., "coolblue" in service name)
+ if (matches.isEmpty()) {
+ matches.addAll(credentials.filter { credential ->
+ credential.service.name?.let { name ->
+ name.contains(domainWithoutExtension, ignoreCase = true) ||
+ domainWithoutExtension.contains(name, ignoreCase = true)
+ } ?: false
+ })
+ }
+ }
+
+ // If no URL matches found or appInfo is not a URL, try non-URL matching
+ if (matches.isEmpty()) {
+ // Split appInfo into words for better matching
+ val searchTerms = appInfo.split(Regex("[\\s._-]+")).filter { it.isNotEmpty() }
+
+ matches.addAll(credentials.filter { credential ->
+ // Check service name
+ credential.service.name?.let { name ->
+ searchTerms.any { term ->
+ name.contains(term, ignoreCase = true) ||
+ term.contains(name, ignoreCase = true)
+ }
+ } ?: false ||
+ // Check username
+ credential.username?.let { username ->
+ searchTerms.any { term ->
+ username.contains(term, ignoreCase = true) ||
+ term.contains(username, ignoreCase = true)
+ }
+ } ?: false ||
+ // Check service URL (even if appInfo isn't a URL)
+ credential.service.url?.let { url ->
+ searchTerms.any { term ->
+ url.contains(term, ignoreCase = true) ||
+ term.contains(url, ignoreCase = true)
+ }
+ } ?: false
+ })
+ }
+
+ return matches
+ }
+
+ /**
+ * Extracts the root domain from a host string.
+ * For example: "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 name without its extension.
+ * For example: "example.com" -> "example"
+ */
+ private fun extractDomainWithoutExtension(domain: String): String {
+ return domain.split(".").firstOrNull() ?: domain
+ }
+}
\ No newline at end of file
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.kt
new file mode 100644
index 000000000..3e167c487
--- /dev/null
+++ b/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/AutofillTest.kt
@@ -0,0 +1,151 @@
+package net.aliasvault.app.nativevaultmanager
+
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+import net.aliasvault.app.autofill.CredentialMatcher
+import net.aliasvault.app.vaultstore.models.Credential
+import net.aliasvault.app.vaultstore.models.Service
+import java.util.Date
+import java.util.UUID
+import kotlin.test.*
+
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [28])
+class AutofillTest {
+ private lateinit var credentialMatcher: CredentialMatcher
+ private lateinit var testCredentials: List<Credential>
+
+ @Before
+ fun setup() {
+ credentialMatcher = CredentialMatcher()
+
+ // Create test credentials
+ testCredentials = listOf(
+ createTestCredential(
+ "Gmail",
+ "https://gmail.com",
+ ),
+ createTestCredential(
+ "Coolblue",
+ "https://www.coolblue.nl",
+ ),
+ createTestCredential(
+ "Amazon",
+ "https://amazon.com",
+ ),
+ createTestCredential(
+ "Coolblue App",
+ "com.coolblue.app",
+ )
+ )
+ }
+
+ @Test
+ fun testExactUrlMatch() {
+ val matches = credentialMatcher.filterCredentialsByAppInfo(
+ testCredentials,
+ "https://gmail.com"
+ )
+
+ assertEquals(1, matches.size)
+ assertEquals("Gmail", matches[0].service.name)
+ }
+
+ @Test
+ fun testBaseUrlMatch() {
+ val matches = credentialMatcher.filterCredentialsByAppInfo(
+ testCredentials,
+ "https://gmail.com/signin"
+ )
+
+ assertEquals(1, matches.size)
+ assertEquals("Gmail", matches[0].service.name)
+ }
+
+ @Test
+ fun testRootDomainMatch() {
+ val matches = credentialMatcher.filterCredentialsByAppInfo(
+ testCredentials,
+ "https://mail.google.com"
+ )
+
+ assertEquals(1, matches.size)
+ assertEquals("Gmail", matches[0].service.name)
+ }
+
+ @Test
+ fun testDomainNamePartMatch() {
+ 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" })
+ }
+
+ @Test
+ fun testPackageNameMatch() {
+ val matches = credentialMatcher.filterCredentialsByAppInfo(
+ testCredentials,
+ "com.coolblue.app"
+ )
+
+ assertEquals(1, matches.size)
+ assertEquals("Coolblue App", matches[0].service.name)
+ }
+
+ @Test
+ fun testNoMatches() {
+ val matches = credentialMatcher.filterCredentialsByAppInfo(
+ testCredentials,
+ "https://nonexistent.com"
+ )
+
+ assertTrue(matches.isEmpty())
+ }
+
+ @Test
+ fun testInvalidUrl() {
+ val matches = credentialMatcher.filterCredentialsByAppInfo(
+ testCredentials,
+ "not a url"
+ )
+
+ assertTrue(matches.isEmpty())
+ }
+
+ private fun createTestCredential(
+ serviceName: String,
+ serviceUrl: String,
+ username: String
+ ): Credential {
+ return Credential(
+ id = UUID.randomUUID(),
+ service = Service(
+ id = UUID.randomUUID(),
+ name = serviceName,
+ url = serviceUrl,
+ logo = null,
+ createdAt = Date(),
+ updatedAt = Date(),
+ isDeleted = false
+ ),
+ username = username,
+ password = null,
+ alias = null,
+ notes = null,
+ createdAt = Date(),
+ updatedAt = Date(),
+ isDeleted = false,
+ )
+ }
+}
diff --git a/docs/mobile-apps/android/autofill.md b/docs/mobile-apps/android/autofill.md
index 24a37467f..ddf90a1aa 100644
--- a/docs/mobile-apps/android/autofill.md
+++ b/docs/mobile-apps/android/autofill.md
@@ -19,3 +19,11 @@ Android has added multiple autofill APIs throughout the years, which include Acc
If you're running into any specific issues with your specific device make/model, feel free to raise an issue on GitHub.
+
+## Using Native Autofill in Chrome
+Currently AliasVault implements the `Native Autofill` API which shows an autofill popup on supported input fields. The Chrome browser on Android from **version 135** onwards support native autofill via third party apps. You need to enable this manually.
+
+To configure AliasVault as the autofill provider in Chrome:
+1. Open Chrome
+2. Go to Menu > Settings > Autofill services
+3. Choose the option `Autofill using another service`
\ No newline at end of file