Skip to content

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

Add e2e tests for autofill matching (#1404)

Leendert de Borst980376ccfb76
diff --git a/apps/browser-extension/playwright.config.ts b/apps/browser-extension/playwright.config.ts
index cc04f0b42..10f101c10 100644
--- a/apps/browser-extension/playwright.config.ts
+++ b/apps/browser-extension/playwright.config.ts
@@ -39,7 +39,7 @@ export default defineConfig({
],
// Global timeout for each test
- timeout: 10000,
+ timeout: 60000,
// Expect timeout
expect: {
diff --git a/apps/browser-extension/src/entrypoints/content.ts b/apps/browser-extension/src/entrypoints/content.ts
index 0d8f86902..261621108 100644
--- a/apps/browser-extension/src/entrypoints/content.ts
+++ b/apps/browser-extension/src/entrypoints/content.ts
@@ -14,7 +14,7 @@ import { BoolResponse as messageBoolResponse } from '@/utils/types/messaging/Boo
import { t } from '@/i18n/StandaloneI18n';
-import { defineContentScript, createShadowRootUi } from '#imports';
+import { defineContentScript, createShadowRootUi, storage } from '#imports';
export default defineContentScript({
matches: ['<all_urls>'],
@@ -37,12 +37,12 @@ export default defineContentScript({
// Wait for 750ms to give the host page time to load and to increase the chance that the body is available and ready.
await new Promise(resolve => setTimeout(resolve, 750));
- // Create a shadow root UI for isolation
+ // Create a shadow root UI for isolation (use 'open' mode in E2E tests for testability)
const ui = await createShadowRootUi(ctx, {
name: 'aliasvault-ui',
position: 'inline',
anchor: 'body',
- mode: 'closed',
+ mode: await storage.getItem('local:e2eTestMode') === true ? 'open' : 'closed',
/**
* Handle mount.
*/
diff --git a/apps/browser-extension/src/utils/VaultMergeService.ts b/apps/browser-extension/src/utils/VaultMergeService.ts
index 5b44db68e..ab85747a0 100644
--- a/apps/browser-extension/src/utils/VaultMergeService.ts
+++ b/apps/browser-extension/src/utils/VaultMergeService.ts
@@ -8,20 +8,10 @@ import init, { getSyncableTableNames, mergeVaults } from './dist/core/rust/alias
*/
type JsonRecord = { [key: string]: unknown };
-/**
- * Type for Rust merge function.
- */
-type MergeFunction = (input: IMergeInput) => IMergeOutput;
-
-/**
- * Type for Rust getSyncableTableNames function.
- */
-type GetTableNamesFunction = () => string[];
-
/**
* Table data structure for Rust merge input/output.
*/
-interface ITableData {
+type TableData = {
name: string;
records: JsonRecord[];
}
@@ -29,15 +19,15 @@ interface ITableData {
/**
* Input structure for Rust merge function.
*/
-interface IMergeInput {
- local_tables: ITableData[];
- server_tables: ITableData[];
+type MergeInput = {
+ local_tables: TableData[];
+ server_tables: TableData[];
}
/**
* SQL statement with parameters from Rust.
*/
-interface ISqlStatement {
+type SqlStatement = {
sql: string;
params: SqlValue[];
}
@@ -45,7 +35,7 @@ interface ISqlStatement {
/**
* Statistics from Rust merge.
*/
-interface IRustMergeStats {
+type RustMergeStats = {
tables_processed: number;
records_from_local: number;
records_from_server: number;
@@ -57,25 +47,25 @@ interface IRustMergeStats {
/**
* Output structure from Rust merge function.
*/
-interface IMergeOutput {
+type MergeOutput = {
success: boolean;
- statements: ISqlStatement[];
- stats: IRustMergeStats;
+ statements: SqlStatement[];
+ stats: RustMergeStats;
}
/**
* Result of a merge operation.
*/
-export interface IMergeResult {
+export type MergeResult = {
success: boolean;
mergedVaultBase64: string;
- stats: IMergeStats;
+ stats: MergeStats;
}
/**
* Statistics about what was merged.
*/
-export interface IMergeStats {
+export type MergeStats = {
tablesProcessed: number;
recordsFromLocal: number;
recordsFromServer: number;
@@ -129,7 +119,7 @@ export class VaultMergeService {
* @param serverVaultBase64 - The server vault (latest version) as base64 SQLite
* @returns MergeResult with the merged vault as base64
*/
- public async merge(localVaultBase64: string, serverVaultBase64: string): Promise<IMergeResult> {
+ public async merge(localVaultBase64: string, serverVaultBase64: string): Promise<MergeResult> {
try {
// Initialize Rust WASM
await this.initRust();
@@ -153,12 +143,12 @@ export class VaultMergeService {
const tableNames = getSyncableTableNames();
// Read all tables from both databases as JSON
- const localTables: ITableData[] = tableNames.map(name => ({
+ const localTables: TableData[] = tableNames.map(name => ({
name,
records: this.readTableAsJson(localDb, name),
}));
- const serverTables: ITableData[] = tableNames.map(name => ({
+ const serverTables: TableData[] = tableNames.map(name => ({
name,
records: this.readTableAsJson(serverDb, name),
}));
@@ -167,10 +157,10 @@ export class VaultMergeService {
* Call Rust WASM merge (or injected function).
* Use JSON stringify/parse to ensure no undefined values reach Rust/serde.
*/
- const mergeInput: IMergeInput = JSON.parse(JSON.stringify({
+ const mergeInput: MergeInput = JSON.parse(JSON.stringify({
local_tables: localTables,
server_tables: serverTables,
- })) as IMergeInput;
+ })) as MergeInput;
console.debug('[VaultMerge] Merge input:', {
localTableCount: localTables.length,
@@ -179,13 +169,7 @@ export class VaultMergeService {
serverTables: serverTables.map(t => ({ name: t.name, recordCount: t.records.length })),
});
- const mergeOutput = mergeVaults(mergeInput);
-
- console.debug('[VaultMerge] Merge output:', {
- success: mergeOutput.success,
- stats: mergeOutput.stats,
- statementCount: mergeOutput.statements.length,
- });
+ const mergeOutput = mergeVaults(mergeInput) as MergeOutput;
// Execute SQL statements from Rust on local database
for (const stmt of mergeOutput.statements) {
diff --git a/apps/browser-extension/src/utils/credentialMatcher/CredentialMatcher.ts b/apps/browser-extension/src/utils/credentialMatcher/CredentialMatcher.ts
index d1531eae0..b76c6291a 100644
--- a/apps/browser-extension/src/utils/credentialMatcher/CredentialMatcher.ts
+++ b/apps/browser-extension/src/utils/credentialMatcher/CredentialMatcher.ts
@@ -43,8 +43,6 @@ export async function filterCredentials(
): Promise<Credential[]> {
await ensureInit();
- console.log('filterCredentials', credentials, currentUrl, pageTitle, matchingMode);
-
const result = wasmFilterCredentials({
credentials: credentials.map(c => ({ Id: c.Id, ServiceName: c.ServiceName, ServiceUrl: c.ServiceUrl })),
current_url: currentUrl,
@@ -52,8 +50,6 @@ export async function filterCredentials(
matching_mode: matchingMode
}) as { matched_ids: string[] };
- console.log('result', result);
-
return result.matched_ids
.map(id => credentials.find(c => c.Id === id))
.filter((c): c is Credential => c !== undefined);
diff --git a/apps/browser-extension/tests/e2e/08-credential-matcher.spec.ts b/apps/browser-extension/tests/e2e/08-credential-matcher.spec.ts
new file mode 100644
index 000000000..f450e9907
--- /dev/null
+++ b/apps/browser-extension/tests/e2e/08-credential-matcher.spec.ts
@@ -0,0 +1,272 @@
+/**
+ * Category 8: Credential Matcher Integration (Requires API + Authentication)
+ *
+ * These tests verify the CredentialMatcher Rust WASM integration works correctly.
+ * The Rust core library is already unit tested natively; these tests verify the
+ * integration in the browser extension context through the autofill popup UI.
+ *
+ * Test scenarios:
+ * 1. No matches: URL that doesn't match any credentials
+ * 2. One match: URL that matches exactly one credential
+ * 3. Multiple matches: URL that matches multiple credentials (same root domain)
+ */
+import fs from 'fs';
+import path from 'path';
+import { fileURLToPath } from 'url';
+
+import type { Page } from '@playwright/test';
+
+import { test, expect, TestClient } from '../fixtures';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+/**
+ * Path to the test login page HTML fixture
+ */
+const TEST_PAGE_PATH = path.join(__dirname, '..', 'fixtures', 'test-pages', 'login.html');
+const TEST_PAGE_HTML = fs.readFileSync(TEST_PAGE_PATH, 'utf-8');
+
+/**
+ * Helper to get credential names from the autofill popup shadow DOM.
+ * Requires E2E test mode to be enabled (open shadow DOM).
+ */
+async function getAutofillPopupCredentials(page: Page): Promise<string[]> {
+ return page.evaluate(() => {
+ const ui = document.querySelector('aliasvault-ui');
+ if (!ui || !ui.shadowRoot) {
+ return [];
+ }
+
+ const credentialItems = ui.shadowRoot.querySelectorAll('.av-credential-item .av-service-name');
+ return Array.from(credentialItems).map(el => el.textContent?.trim() || '');
+ });
+}
+
+/**
+ * Helper to check if the autofill popup is visible.
+ */
+async function isAutofillPopupVisible(page: Page): Promise<boolean> {
+ return page.evaluate(() => {
+ const ui = document.querySelector('aliasvault-ui');
+ if (!ui || !ui.shadowRoot) {
+ return false;
+ }
+
+ const popup = ui.shadowRoot.querySelector('#aliasvault-credential-popup');
+ return popup !== null;
+ });
+}
+
+/**
+ * Helper to setup route interception to serve our test login page for a given domain.
+ */
+async function setupTestPageRoute(page: Page, domain: string): Promise<void> {
+ await page.route(`https://${domain}/**`, (route) => {
+ route.fulfill({
+ status: 200,
+ contentType: 'text/html',
+ body: TEST_PAGE_HTML,
+ });
+ });
+}
+
+test.describe.serial('8. Credential Matcher Integration', () => {
+ let client: TestClient;
+
+ test.afterAll(async () => {
+ await client?.cleanup();
+ });
+
+ test('8.1 should login and create test credentials with different URLs', async ({ testUser, apiUrl }) => {
+ client = await TestClient.create();
+ await client.login(apiUrl, testUser.username, testUser.password);
+
+ // Enable E2E test mode for open shadow DOM
+ await client.enableE2ETestMode();
+
+ // Create credentials with specific URLs for testing
+ // Credential 1: For example.com domain
+ await client
+ .goToVault()
+ .then((c) => c.createCredentialWithUrl(
+ 'Example Site Login',
+ 'ExamplePass123!',
+ 'https://example.com/login'
+ ));
+
+ // Credential 2: For test.example.com subdomain (same root domain)
+ await client
+ .goToVault()
+ .then((c) => c.createCredentialWithUrl(
+ 'Example Subdomain Login',
+ 'SubdomainPass123!',
+ 'https://test.example.com/auth'
+ ));
+
+ // Credential 3: For another-example.com (different domain)
+ await client
+ .goToVault()
+ .then((c) => c.createCredentialWithUrl(
+ 'Another Site Login',
+ 'AnotherPass123!',
+ 'https://another-example.com/signin'
+ ));
+
+ // Verify all credentials were created
+ await client.goToVault().then((c) => c.waitForVaultReady());
+ await client.verifyCredentialExists('Example Site Login');
+ await client.verifyCredentialExists('Example Subdomain Login');
+ await client.verifyCredentialExists('Another Site Login');
+
+ await client.screenshot('8.1-credentials-created.png');
+ });
+
+ test('8.2 should show no matches for unrelated domain', async () => {
+ const testPage = await client.context.newPage();
+
+ // Setup route to serve our test login page for unrelated-domain.com
+ await setupTestPageRoute(testPage, 'unrelated-domain.com');
+
+ // Navigate to the test page
+ await testPage.goto('https://unrelated-domain.com/login');
+ await testPage.waitForLoadState('domcontentloaded');
+
+ // Focus on the username field to trigger the autofill popup
+ const usernameField = testPage.locator('input#username');
+ await usernameField.click();
+
+ // Wait for the content script to initialize and the popup to appear
+ await testPage.waitForTimeout(2000);
+
+ // Verify the autofill popup is visible
+ const popupVisible = await isAutofillPopupVisible(testPage);
+ console.log('Autofill popup visible:', popupVisible);
+ expect(popupVisible).toBe(true);
+
+ // Get credentials shown in the popup
+ const credentials = await getAutofillPopupCredentials(testPage);
+ console.log('Credentials in popup for unrelated-domain.com:', credentials);
+
+ // Should NOT match any of our credentials
+ expect(credentials).not.toContain('Example Site Login');
+ expect(credentials).not.toContain('Example Subdomain Login');
+ expect(credentials).not.toContain('Another Site Login');
+ expect(credentials.length).toBe(0);
+
+ await testPage.screenshot({ path: 'tests/screenshots/8.2-no-matches.png' });
+ await testPage.close();
+ });
+
+ test('8.3 should show single matching credential on example.com', async () => {
+ const testPage = await client.context.newPage();
+
+ // Setup route to serve our test login page for example.com
+ await setupTestPageRoute(testPage, 'example.com');
+
+ // Navigate to example.com
+ await testPage.goto('https://example.com/login');
+ await testPage.waitForLoadState('domcontentloaded');
+
+ // Focus on the username field to trigger the autofill popup
+ const usernameField = testPage.locator('input#username');
+ await usernameField.click();
+
+ // Wait for the content script to initialize and the popup to appear
+ await testPage.waitForTimeout(2000);
+
+ // Verify the autofill popup is visible
+ const popupVisible = await isAutofillPopupVisible(testPage);
+ console.log('Autofill popup visible on example.com:', popupVisible);
+ expect(popupVisible).toBe(true);
+
+ // Get credentials shown in the popup
+ const credentials = await getAutofillPopupCredentials(testPage);
+ console.log('Credentials matched for example.com:', credentials);
+
+ // Should match the Example Site Login
+ expect(credentials).toContain('Example Site Login');
+
+ // Should NOT match another-example.com credential (different domain)
+ expect(credentials).not.toContain('Another Site Login');
+
+ await testPage.screenshot({ path: 'tests/screenshots/8.3-example-com-match.png' });
+ await testPage.close();
+ });
+
+ test('8.4 should show single matching credential on another-example.com', async () => {
+ const testPage = await client.context.newPage();
+
+ // Setup route to serve our test login page for another-example.com
+ await setupTestPageRoute(testPage, 'another-example.com');
+
+ // Navigate to another-example.com
+ await testPage.goto('https://another-example.com/signin');
+ await testPage.waitForLoadState('domcontentloaded');
+
+ // Focus on the username field to trigger the autofill popup
+ const usernameField = testPage.locator('input#username');
+ await usernameField.click();
+
+ // Wait for the content script to initialize and the popup to appear
+ await testPage.waitForTimeout(2000);
+
+ // Verify the autofill popup is visible
+ const popupVisible = await isAutofillPopupVisible(testPage);
+ console.log('Autofill popup visible on another-example.com:', popupVisible);
+ expect(popupVisible).toBe(true);
+
+ // Get credentials shown in the popup
+ const credentials = await getAutofillPopupCredentials(testPage);
+ console.log('Credentials matched for another-example.com:', credentials);
+
+ // Should match only Another Site Login
+ expect(credentials).toContain('Another Site Login');
+
+ // Should NOT match example.com credentials
+ expect(credentials).not.toContain('Example Site Login');
+ expect(credentials).not.toContain('Example Subdomain Login');
+
+ await testPage.screenshot({ path: 'tests/screenshots/8.4-another-example-match.png' });
+ await testPage.close();
+ });
+
+ test('8.5 should show multiple matching credentials for subdomain', async () => {
+ const testPage = await client.context.newPage();
+
+ // Setup route to serve our test login page for test.example.com
+ await setupTestPageRoute(testPage, 'test.example.com');
+
+ // Navigate to test.example.com subdomain
+ await testPage.goto('https://test.example.com/auth');
+ await testPage.waitForLoadState('domcontentloaded');
+
+ // Focus on the username field to trigger the autofill popup
+ const usernameField = testPage.locator('input#username');
+ await usernameField.click();
+
+ // Wait for the content script to initialize and the popup to appear
+ await testPage.waitForTimeout(2000);
+
+ // Verify the autofill popup is visible
+ const popupVisible = await isAutofillPopupVisible(testPage);
+ console.log('Autofill popup visible on test.example.com:', popupVisible);
+ expect(popupVisible).toBe(true);
+
+ // Get credentials shown in the popup
+ const credentials = await getAutofillPopupCredentials(testPage);
+ console.log('Credentials matched for test.example.com:', credentials);
+
+ // Should match the Example Subdomain Login (exact subdomain match)
+ expect(credentials).toContain('Example Subdomain Login');
+
+ // Should NOT match another-example.com credential
+ expect(credentials).not.toContain('Another Site Login');
+
+ await testPage.screenshot({ path: 'tests/screenshots/8.5-subdomain-match.png' });
+ await testPage.close();
+ });
+});
diff --git a/apps/browser-extension/tests/fixtures/TestClient.ts b/apps/browser-extension/tests/fixtures/TestClient.ts
index 07f0d8d28..8993ab444 100644
--- a/apps/browser-extension/tests/fixtures/TestClient.ts
+++ b/apps/browser-extension/tests/fixtures/TestClient.ts
@@ -227,6 +227,23 @@ export class TestClient {
return this;
}
+ /**
+ * Create a new login credential with a URL.
+ * This is used for testing credential matching based on URLs.
+ */
+ async createCredentialWithUrl(name: string, username: string, password: string, url: string): Promise<this> {
+ await this.openAddCredentialForm();
+ // All fields are now visible on the same page (no "Next" step)
+ await expect(this.popup.locator(FieldSelectors.LOGIN_USERNAME)).toBeVisible({ timeout: Timeouts.MEDIUM });
+ await this.popup.fill(FieldSelectors.ITEM_NAME, name);
+ await this.popup.fill(FieldSelectors.LOGIN_USERNAME, username);
+ await this.popup.fill(FieldSelectors.LOGIN_PASSWORD, password);
+ await this.popup.fill(FieldSelectors.LOGIN_URL, url);
+ await this.popup.click(ButtonSelectors.SAVE);
+ await waitForCredentialSaved(this.popup, name);
+ return this;
+ }
+
/**
* Click on a credential in the vault list.
*/
@@ -323,6 +340,35 @@ export class TestClient {
return this;
}
+ /**
+ * Enable E2E test mode which sets the shadow DOM to 'open' mode for testability.
+ * This must be called before navigating to pages where you want to inspect the autofill popup.
+ */
+ async enableE2ETestMode(): Promise<this> {
+ await this.popup.evaluate(() => {
+ return new Promise<void>((resolve) => {
+ chrome.storage.local.set({ e2eTestMode: true }, () => {
+ resolve();
+ });
+ });
+ });
+ return this;
+ }
+
+ /**
+ * Disable E2E test mode.
+ */
+ async disableE2ETestMode(): Promise<this> {
+ await this.popup.evaluate(() => {
+ return new Promise<void>((resolve) => {
+ chrome.storage.local.remove('e2eTestMode', () => {
+ resolve();
+ });
+ });
+ });
+ return this;
+ }
+
/**
* Enable offline mode by setting an invalid API URL.
*/
diff --git a/apps/browser-extension/tests/fixtures/selectors.ts b/apps/browser-extension/tests/fixtures/selectors.ts
index 2790df0ed..fb8f10010 100644
--- a/apps/browser-extension/tests/fixtures/selectors.ts
+++ b/apps/browser-extension/tests/fixtures/selectors.ts
@@ -51,7 +51,7 @@ export const FieldSelectors = {
// Login fields
LOGIN_USERNAME: `input#${escapeFieldKey(FieldKey.LoginUsername)}`,
LOGIN_PASSWORD: `input#${escapeFieldKey(FieldKey.LoginPassword)}`,
- LOGIN_URL: `input#${escapeFieldKey(FieldKey.LoginUrl)}`,
+ LOGIN_URL: `input#${escapeFieldKey(FieldKey.LoginUrl)}-0`, // Multi-value field uses -0 suffix for first entry
// Metadata fields (shared across item types)
LOGIN_NOTES: `textarea#${escapeFieldKey(FieldKey.MetadataNotes)}`,
diff --git a/apps/browser-extension/tests/fixtures/test-pages/login.html b/apps/browser-extension/tests/fixtures/test-pages/login.html
new file mode 100644
index 000000000..8fa2b6e9f
--- /dev/null
+++ b/apps/browser-extension/tests/fixtures/test-pages/login.html
@@ -0,0 +1,79 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>E2E Test Form</title>
+ <style>
+ body {
+ font-family: Arial, sans-serif;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ min-height: 100vh;
+ margin: 0;
+ background-color: #f0f0f0;
+ }
+ .login-form {
+ background: white;
+ padding: 2rem;
+ border-radius: 8px;
+ box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
+ width: 300px;
+ }
+ h1 {
+ margin-top: 0;
+ text-align: center;
+ color: #333;
+ }
+ .form-group {
+ margin-bottom: 1rem;
+ }
+ label {
+ display: block;
+ margin-bottom: 0.5rem;
+ color: #555;
+ }
+ input[type="text"],
+ input[type="password"] {
+ width: 100%;
+ padding: 0.75rem;
+ border: 1px solid #ddd;
+ border-radius: 4px;
+ font-size: 1rem;
+ box-sizing: border-box;
+ }
+ input:focus {
+ outline: none;
+ border-color: #007bff;
+ }
+ button[type="submit"] {
+ width: 100%;
+ padding: 0.75rem;
+ background-color: #007bff;
+ color: white;
+ border: none;
+ border-radius: 4px;
+ font-size: 1rem;
+ cursor: pointer;
+ }
+ button[type="submit"]:hover {
+ background-color: #0056b3;
+ }
+ </style>
+</head>
+<body>
+ <form class="login-form" action="#" method="post">
+ <h1>Login</h1>
+ <div class="form-group">
+ <label for="username">Username</label>
+ <input type="text" id="username" name="username" autocomplete="username" placeholder="Enter username">
+ </div>
+ <div class="form-group">
+ <label for="password">Password</label>
+ <input type="password" id="password" name="password" autocomplete="current-password" placeholder="Enter password">
+ </div>
+ <button type="submit">Sign In</button>
+ </form>
+</body>
+</html>
diff --git a/core/rust/src/credential_matcher/domain.rs b/core/rust/src/credential_matcher/domain.rs
index d0de91df0..d2c7e84d6 100644
--- a/core/rust/src/credential_matcher/domain.rs
+++ b/core/rust/src/credential_matcher/domain.rs
@@ -189,7 +189,7 @@ pub fn extract_root_domain(domain: &str) -> String {
}
}
-/// Check if two domains match, supporting partial matches.
+/// Check if two domains match, supporting subdomain matching.
/// Note: Both parameters should be pre-extracted domains (without protocol, www, path, etc.)
pub fn domains_match(domain1: &str, domain2: &str) -> bool {
if domain1.is_empty() || domain2.is_empty() {
@@ -201,8 +201,10 @@ pub fn domains_match(domain1: &str, domain2: &str) -> bool {
return true;
}
- // Check if one domain contains the other (for subdomain matching)
- if domain1.contains(domain2) || domain2.contains(domain1) {
+ // Check subdomain relationship (must end with ".domain" not just contain it)
+ // e.g., "sub.example.com" is a subdomain of "example.com"
+ // but "another-example.com" is NOT related to "example.com"
+ if is_subdomain_of(domain1, domain2) || is_subdomain_of(domain2, domain1) {
return true;
}
@@ -213,6 +215,19 @@ pub fn domains_match(domain1: &str, domain2: &str) -> bool {
d1_root == d2_root
}
+/// Check if domain1 is a subdomain of domain2.
+/// e.g., "sub.example.com" is a subdomain of "example.com"
+/// but "another-example.com" is NOT a subdomain of "example.com"
+fn is_subdomain_of(domain1: &str, domain2: &str) -> bool {
+ // domain1 must be longer and end with ".domain2"
+ if domain1.len() <= domain2.len() {
+ return false;
+ }
+
+ // Check if domain1 ends with ".domain2" (proper subdomain boundary)
+ domain1.ends_with(&format!(".{}", domain2))
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -270,5 +285,12 @@ mod tests {
// No match
assert!(!domains_match("example.com", "different.com"));
assert!(!domains_match("coolblue.nl", "coolblue.be"));
+
+ // CRITICAL: Substring match should NOT work (anti-phishing protection)
+ // "another-example.com" contains "example.com" but is NOT a subdomain
+ assert!(!domains_match("another-example.com", "example.com"));
+ assert!(!domains_match("example.com", "another-example.com"));
+ assert!(!domains_match("myexample.com", "example.com"));
+ assert!(!domains_match("example.com.evil.com", "example.com"));
}
}
diff --git a/core/rust/src/credential_matcher/tests.rs b/core/rust/src/credential_matcher/tests.rs
index 168936c26..61ee34709 100644
--- a/core/rust/src/credential_matcher/tests.rs
+++ b/core/rust/src/credential_matcher/tests.rs
@@ -395,3 +395,40 @@ fn test_max_three_results() {
// Should return max 3 results
assert!(matches.len() <= 3);
}
+
+/// [#23] - E2E test scenario: credentials with URLs should only match their specific domains
+/// This mirrors the browser extension E2E test setup
+#[test]
+fn test_e2e_scenario_url_only_matching() {
+ let credentials = vec![
+ create_test_credential("Example Site", "https://example.com/login", "[email protected]"),
+ create_test_credential("Example Subdomain", "https://test.example.com/auth", "[email protected]"),
+ create_test_credential("Another Site", "https://another-example.com/signin", "[email protected]"),
+ ];
+
+ // Test 1: Unrelated domain should return NO matches
+ let unrelated_matches = filter(credentials.clone(), "https://unrelated-domain.com/login", "E2E Test Form");
+ assert_eq!(unrelated_matches.len(), 0, "Unrelated domain should not match any credentials");
+
+ // Test 2: example.com should only match Example Site (and possibly subdomain due to root domain matching)
+ let example_matches = filter(credentials.clone(), "https://example.com/login", "E2E Test Form");
+ println!("example.com matches: {:?}", example_matches.iter().map(|c| c.service_name.as_deref()).collect::<Vec<_>>());
+ assert!(example_matches.len() >= 1, "example.com should match at least one credential");
+ assert!(example_matches.iter().any(|c| c.service_name.as_deref() == Some("Example Site")),
+ "example.com should match Example Site");
+ assert!(!example_matches.iter().any(|c| c.service_name.as_deref() == Some("Another Site")),
+ "example.com should NOT match Another Site");
+
+ // Test 3: another-example.com should only match Another Site
+ let another_matches = filter(credentials.clone(), "https://another-example.com/signin", "E2E Test Form");
+ assert_eq!(another_matches.len(), 1, "another-example.com should match exactly one credential");
+ assert_eq!(another_matches[0].service_name.as_deref(), Some("Another Site"));
+
+ // Test 4: test.example.com subdomain should match Example Subdomain
+ let subdomain_matches = filter(credentials, "https://test.example.com/auth", "E2E Test Form");
+ assert!(subdomain_matches.len() >= 1, "test.example.com should match at least one credential");
+ assert!(subdomain_matches.iter().any(|c| c.service_name.as_deref() == Some("Example Subdomain")),
+ "test.example.com should match Example Subdomain");
+ assert!(!subdomain_matches.iter().any(|c| c.service_name.as_deref() == Some("Another Site")),
+ "test.example.com should NOT match Another Site");
+}