Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add port awareness to credential matcher (#1473)
Leendert de Borst99d8992667e9
diff --git a/core/rust/src/credential_matcher/domain.rs b/core/rust/src/credential_matcher/domain.rsindex d2c7e84d6..b696a5c29 100644--- a/core/rust/src/credential_matcher/domain.rs+++ b/core/rust/src/credential_matcher/domain.rs@@ -102,11 +102,31 @@ pub fn is_app_package_name(text: &str) -> bool {tld_set.contains(first_part.as_str())}-/// Extract domain from URL, handling both full URLs and partial domains.-/// Returns empty string if not a valid URL/domain.-pub fn extract_domain(url: &str) -> String {+/// Result of domain extraction containing both the domain and optional port.+#[derive(Debug, Clone, PartialEq)]+pub struct DomainWithPort {+ pub domain: String,+ pub port: Option<String>,+}++impl DomainWithPort {+ /// Returns the domain with port if present (e.g., "example.com:8080")+ pub fn with_port(&self) -> String {+ match &self.port {+ Some(p) => format!("{}:{}", self.domain, p),+ None => self.domain.clone(),+ }+ }+}++/// Extract domain and port from URL, handling both full URLs and partial domains.+/// Returns DomainWithPort with empty domain if not a valid URL/domain.+pub fn extract_domain_with_port(url: &str) -> DomainWithPort {if url.is_empty() {- return String::new();+ return DomainWithPort {+ domain: String::new(),+ port: None,+ };}let mut domain = url.to_lowercase();@@ -116,7 +136,10 @@ pub fn extract_domain(url: &str) -> String {// If no protocol and starts with TLD + dot, it's likely an app package nameif !has_protocol && is_app_package_name(&domain) {- return String::new();+ return DomainWithPort {+ domain: String::new(),+ port: None,+ };}// Remove protocol if present@@ -131,7 +154,7 @@ pub fn extract_domain(url: &str) -> String {domain = stripped.to_string();}- // Remove path, query, and fragment+ // Remove path, query, and fragment first (before extracting port)if let Some(pos) = domain.find('/') {domain = domain[..pos].to_string();}@@ -142,22 +165,55 @@ pub fn extract_domain(url: &str) -> String {domain = domain[..pos].to_string();}+ // Extract port number if present (e.g., :8080, :1234)+ let port = if let Some(pos) = domain.find(':') {+ let port_str = domain[pos + 1..].to_string();+ domain = domain[..pos].to_string();+ // Validate port is numeric+ if port_str.chars().all(|c| c.is_ascii_digit()) && !port_str.is_empty() {+ Some(port_str)+ } else {+ None+ }+ } else {+ None+ };+// Basic domain validation - must contain at least one dot and valid charactersif !domain.contains('.') {- return String::new();+ return DomainWithPort {+ domain: String::new(),+ port: None,+ };}// Check for valid domain characters- if !domain.chars().all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-') {- return String::new();+ if !domain+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-')+ {+ return DomainWithPort {+ domain: String::new(),+ port: None,+ };}// Ensure valid domain structureif domain.starts_with('.') || domain.ends_with('.') || domain.contains("..") {- return String::new();+ return DomainWithPort {+ domain: String::new(),+ port: None,+ };}- domain+ DomainWithPort { domain, port }+}++/// Extract domain from URL, handling both full URLs and partial domains.+/// Returns empty string if not a valid URL/domain.+/// Note: This strips port numbers. Use extract_domain_with_port() to preserve port info.+pub fn extract_domain(url: &str) -> String {+ extract_domain_with_port(url).domain}/// Extract root domain from a domain string.@@ -261,6 +317,44 @@ mod tests {assert_eq!(extract_domain("nodot"), "");}+ #[test]+ fn test_extract_domain_with_port() {+ // Port numbers should be stripped from extract_domain+ assert_eq!(extract_domain("https://example.com:8080"), "example.com");+ assert_eq!(extract_domain("https://example.com:8080/path"), "example.com");+ assert_eq!(extract_domain("https://blabla.asd.com:1234"), "blabla.asd.com");+ assert_eq!(extract_domain("https://www.example.com:443/login"), "example.com");+ assert_eq!(extract_domain("example.com:8080"), "example.com");+ assert_eq!(extract_domain("sub.domain.example.com:9000/path?query=1"), "sub.domain.example.com");+ }++ #[test]+ fn test_extract_domain_with_port_struct() {+ // Test the DomainWithPort struct+ let result = extract_domain_with_port("https://example.com:8080/path");+ assert_eq!(result.domain, "example.com");+ assert_eq!(result.port, Some("8080".to_string()));+ assert_eq!(result.with_port(), "example.com:8080");++ let result = extract_domain_with_port("https://example.com/path");+ assert_eq!(result.domain, "example.com");+ assert_eq!(result.port, None);+ assert_eq!(result.with_port(), "example.com");++ let result = extract_domain_with_port("https://www.myserver.local:9443/dashboard");+ assert_eq!(result.domain, "myserver.local");+ assert_eq!(result.port, Some("9443".to_string()));++ let result = extract_domain_with_port("myserver.local:8123");+ assert_eq!(result.domain, "myserver.local");+ assert_eq!(result.port, Some("8123".to_string()));++ // Test that ports are validated as numeric+ let result = extract_domain_with_port("https://example.com:abc/path");+ assert_eq!(result.domain, "example.com");+ assert_eq!(result.port, None); // Invalid port should be None+ }+#[test]fn test_extract_root_domain() {assert_eq!(extract_root_domain("sub.example.com"), "example.com");diff --git a/core/rust/src/credential_matcher/mod.rs b/core/rust/src/credential_matcher/mod.rsindex 2e0b90cc4..302185495 100644--- a/core/rust/src/credential_matcher/mod.rs+++ b/core/rust/src/credential_matcher/mod.rs@@ -15,7 +15,7 @@ mod stop_words;use serde::{Deserialize, Serialize};use std::collections::HashSet;-pub use domain::{extract_domain, extract_root_domain};+pub use domain::{extract_domain, extract_domain_with_port, extract_root_domain, DomainWithPort};use domain::{domains_match, is_app_package_name};use stop_words::STOP_WORDS;@@ -124,13 +124,18 @@ pub fn filter_credentials(input: CredentialMatcherInput) -> CredentialMatcherOut}// ═══════════════════════════════════════════════════════════════════════════════- // PRIORITY 2: URL Domain Matching+ // PRIORITY 2: URL Domain Matching (with port-aware priority)// Try to extract domain from current URL (skip if package name)+ //+ // Sub-priorities within URL matching:+ // Priority 1: Exact domain+port match (e.g., example.com:8080 == example.com:8080)+ // Priority 2: Exact domain match (ignoring port) (e.g., example.com:8080 == example.com)+ // Priority 3: Subdomain/root domain match (e.g., sub.example.com matches example.com)// ═══════════════════════════════════════════════════════════════════════════════if !is_package_name {- let current_domain = extract_domain(¤t_url);+ let current_domain_info = extract_domain_with_port(¤t_url);- if !current_domain.is_empty() {+ if !current_domain_info.domain.is_empty() {let mut filtered: Vec<CredentialWithPriority> = Vec::new();// Determine matching features based on mode@@ -155,24 +160,37 @@ pub fn filter_credentials(input: CredentialMatcherInput) -> CredentialMatcherOutcontinue;}- let cred_domain = extract_domain(item_url);- if cred_domain.is_empty() {+ let cred_domain_info = extract_domain_with_port(item_url);+ if cred_domain_info.domain.is_empty() {continue;}- // Check for exact match (priority 1)- if enable_exact_match && current_domain == cred_domain {+ // Check for exact domain+port match (priority 1 - highest)+ // Both must have same domain AND same port (or both no port)+ if enable_exact_match+ && current_domain_info.domain == cred_domain_info.domain+ && current_domain_info.port == cred_domain_info.port+ {best_priority = Some(1);- break; // Can't do better than exact match+ break; // Can't do better than exact domain+port match+ }++ // Check for exact domain match, ignoring port (priority 2)+ if enable_exact_match+ && current_domain_info.domain == cred_domain_info.domain+ && best_priority.map_or(true, |p| p > 2)+ {+ best_priority = Some(2);+ // Don't break - might find exact domain+port match in another URL}- // Check for subdomain/partial match (priority 2)+ // Check for subdomain/root domain match (priority 3)if enable_subdomain_match- && domains_match(¤t_domain, &cred_domain)+ && domains_match(¤t_domain_info.domain, &cred_domain_info.domain)&& best_priority.is_none(){- best_priority = Some(2);- // Don't break - might find exact match in another URL+ best_priority = Some(3);+ // Don't break - might find better match in another URL}}@@ -186,10 +204,24 @@ pub fn filter_credentials(input: CredentialMatcherInput) -> CredentialMatcherOut// EARLY RETURN if matches foundif !filtered.is_empty() {+ // Find the best (lowest) priority level we have+ let best_priority = filtered.iter().map(|c| c.priority).min().unwrap_or(3);++ // Only return credentials at the best priority level+ // This ensures that:+ // - If we have exact domain+port matches (1), we only show those+ // - If we have exact domain matches (2) but no port matches, we only show those+ // - If we only have subdomain matches (3), we show those+ let filtered_by_priority: Vec<CredentialWithPriority> = filtered+ .into_iter()+ .filter(|c| c.priority == best_priority)+ .collect();+// Sort by priority, deduplicate by ID, take first 3- filtered.sort_by_key(|c| c.priority);+ let mut sorted = filtered_by_priority;+ sorted.sort_by_key(|c| c.priority);let mut seen_ids: HashSet<String> = HashSet::new();- let unique_ids: Vec<String> = filtered+ let unique_ids: Vec<String> = sorted.into_iter().filter(|c| seen_ids.insert(c.credential.id.clone())).map(|c| c.credential.id)diff --git a/core/rust/src/credential_matcher/tests.rs b/core/rust/src/credential_matcher/tests.rsindex 1acbf3955..74e9020d0 100644--- a/core/rust/src/credential_matcher/tests.rs+++ b/core/rust/src/credential_matcher/tests.rs@@ -534,3 +534,194 @@ fn test_multi_url_app_package_matching() {assert_eq!(ios_matches.len(), 1);assert_eq!(ios_matches[0].item_name.as_deref(), Some("Coolblue"));}++/// [#27] - URLs with port numbers should match correctly+#[test]+fn test_url_with_port_matching() {+ let credentials = vec![+ create_test_credential("Local Dev", "https://dev.local:3000", "[email protected]"),+ create_test_credential("Staging Server", "https://staging.example.com:8080", "[email protected]"),+ create_test_credential("Production", "https://example.com", "[email protected]"),+ ];++ // URL with port should match credential with same URL+port+ let local_matches = filter(credentials.clone(), "https://dev.local:3000/login", "");+ assert_eq!(local_matches.len(), 1);+ assert_eq!(local_matches[0].item_name.as_deref(), Some("Local Dev"));++ // URL with different port should still match domain (subdomain matching)+ let staging_matches = filter(credentials.clone(), "https://staging.example.com:8080/dashboard", "");+ assert_eq!(staging_matches.len(), 1);+ assert_eq!(staging_matches[0].item_name.as_deref(), Some("Staging Server"));++ // Production URL should match production credential+ let prod_matches = filter(credentials, "https://example.com/app", "");+ assert_eq!(prod_matches.len(), 1);+ assert_eq!(prod_matches[0].item_name.as_deref(), Some("Production"));+}++/// [#28] - Exact match exclusivity: when exact URL match exists, subdomain matches should be excluded+#[test]+fn test_exact_match_excludes_subdomain_matches() {+ let credentials = vec![+ create_test_credential("Exact Match Site", "https://blabla.asd.com", "[email protected]"),+ create_test_credential("Root Domain", "https://asd.com", "[email protected]"),+ create_test_credential("Other Subdomain", "https://bloe.asd.com", "[email protected]"),+ ];++ // When visiting blabla.asd.com, only the exact match should be shown+ // NOT the root domain (asd.com) or other subdomains (bloe.asd.com)+ let matches = filter(credentials.clone(), "https://blabla.asd.com/page", "");+ assert_eq!(matches.len(), 1, "Should only return the exact match, not subdomain matches");+ assert_eq!(matches[0].item_name.as_deref(), Some("Exact Match Site"));++ // When visiting asd.com (root), only root domain credential should match+ let root_matches = filter(credentials.clone(), "https://asd.com/login", "");+ assert_eq!(root_matches.len(), 1, "Root domain should only match exact root credential");+ assert_eq!(root_matches[0].item_name.as_deref(), Some("Root Domain"));++ // When visiting bloe.asd.com, only that subdomain should match+ let bloe_matches = filter(credentials, "https://bloe.asd.com/app", "");+ assert_eq!(bloe_matches.len(), 1, "Subdomain should only match exact subdomain credential");+ assert_eq!(bloe_matches[0].item_name.as_deref(), Some("Other Subdomain"));+}++/// [#29] - Port-aware matching: exact domain+port beats exact domain beats subdomain+#[test]+fn test_port_aware_matching_priority() {+ // Scenario: Self-hosted user with multiple services on same domain but different ports+ let credentials = vec![+ create_test_credential("Service A (Port 8080)", "https://myserver.local:8080", "[email protected]"),+ create_test_credential("Service B (Port 9000)", "https://myserver.local:9000", "[email protected]"),+ create_test_credential("Service C (No Port)", "https://myserver.local", "[email protected]"),+ ];++ // When visiting myserver.local:8080, ONLY the port 8080 credential should match+ let port_8080_matches = filter(credentials.clone(), "https://myserver.local:8080/dashboard", "");+ assert_eq!(port_8080_matches.len(), 1, "Should only return exact domain+port match");+ assert_eq!(port_8080_matches[0].item_name.as_deref(), Some("Service A (Port 8080)"));++ // When visiting myserver.local:9000, ONLY the port 9000 credential should match+ let port_9000_matches = filter(credentials.clone(), "https://myserver.local:9000/api", "");+ assert_eq!(port_9000_matches.len(), 1, "Should only return exact domain+port match");+ assert_eq!(port_9000_matches[0].item_name.as_deref(), Some("Service B (Port 9000)"));++ // When visiting myserver.local (no port), ONLY the no-port credential should match+ let no_port_matches = filter(credentials.clone(), "https://myserver.local/home", "");+ assert_eq!(no_port_matches.len(), 1, "Should only return exact domain match (no port)");+ assert_eq!(no_port_matches[0].item_name.as_deref(), Some("Service C (No Port)"));++ // When visiting myserver.local:5000 (port not matching any credential),+ // all credentials with exact domain match (priority 2) should be returned (up to 3)+ // This is expected behavior - when no exact port match exists, we show all domain matches+ let diff_port_matches = filter(credentials, "https://myserver.local:5000/new", "");+ assert_eq!(diff_port_matches.len(), 3, "Should return all domain matches when no exact port match");+}++/// [#30] - Port numbers in URL should still allow exact matching with subdomain fallback+#[test]+fn test_port_url_exact_match_exclusivity() {+ let credentials = vec![+ create_test_credential("Exact Port Site", "https://blabla.asd.com:1234", "[email protected]"),+ create_test_credential("Root Domain", "https://asd.com", "[email protected]"),+ create_test_credential("Other Subdomain", "https://bloe.asd.com", "[email protected]"),+ ];++ // When visiting blabla.asd.com:1234, only the exact domain+port match should be shown+ let matches = filter(credentials.clone(), "https://blabla.asd.com:1234/page", "");+ assert_eq!(matches.len(), 1, "Should only return the exact domain+port match");+ assert_eq!(matches[0].item_name.as_deref(), Some("Exact Port Site"));++ // When visiting blabla.asd.com (no port), should match via domain-only (priority 2)+ // since we have a credential with same domain (but different port)+ let no_port_matches = filter(credentials, "https://blabla.asd.com/page", "");+ assert_eq!(no_port_matches.len(), 1, "Should match domain-only when port differs");+ assert_eq!(no_port_matches[0].item_name.as_deref(), Some("Exact Port Site"));+}++/// [#31] - When no exact match exists, subdomain matching should still work+#[test]+fn test_subdomain_matching_without_exact() {+ let credentials = vec![+ create_test_credential("Root Domain Only", "https://example.com", "[email protected]"),+ ];++ // Visiting a subdomain should match the root domain credential (subdomain matching)+ let subdomain_matches = filter(credentials.clone(), "https://app.example.com/login", "");+ assert_eq!(subdomain_matches.len(), 1, "Subdomain should match root domain when no exact match exists");+ assert_eq!(subdomain_matches[0].item_name.as_deref(), Some("Root Domain Only"));++ // Visiting another subdomain should also match+ let another_subdomain = filter(credentials, "https://api.example.com/v1", "");+ assert_eq!(another_subdomain.len(), 1);+ assert_eq!(another_subdomain[0].item_name.as_deref(), Some("Root Domain Only"));+}++/// [#32] - Multiple credentials with same domain but different ports+#[test]+fn test_multiple_same_domain_different_ports() {+ let credentials = vec![+ create_test_credential("Portainer", "https://server.home:9443", "admin@portainer"),+ create_test_credential("Nextcloud", "https://server.home:8443", "admin@nextcloud"),+ create_test_credential("Home Assistant", "https://server.home:8123", "admin@hass"),+ create_test_credential("Main Site", "https://server.home", "admin@main"),+ ];++ // Each port should only match its specific credential+ let portainer = filter(credentials.clone(), "https://server.home:9443", "");+ assert_eq!(portainer.len(), 1);+ assert_eq!(portainer[0].item_name.as_deref(), Some("Portainer"));++ let nextcloud = filter(credentials.clone(), "https://server.home:8443", "");+ assert_eq!(nextcloud.len(), 1);+ assert_eq!(nextcloud[0].item_name.as_deref(), Some("Nextcloud"));++ let hass = filter(credentials.clone(), "https://server.home:8123", "");+ assert_eq!(hass.len(), 1);+ assert_eq!(hass[0].item_name.as_deref(), Some("Home Assistant"));++ let main = filter(credentials, "https://server.home", "");+ assert_eq!(main.len(), 1);+ assert_eq!(main[0].item_name.as_deref(), Some("Main Site"));+}++/// [#33] - User's exact scenario: URL with port should ONLY match exact URL, not items named after domain+#[test]+fn test_user_scenario_url_with_port_vs_named_items() {+ // User has:+ // 1. An item with exact URL https://blabla.asd.com:1234+ // 2. Items named "asd.com" and "bloe.asd.com" (possibly with URLs to those domains)+ let credentials = vec![+ create_test_credential("blabla.asd.com service", "https://blabla.asd.com:1234", "[email protected]"),+ create_test_credential("asd.com", "https://asd.com", "[email protected]"),+ create_test_credential("bloe.asd.com", "https://bloe.asd.com", "[email protected]"),+ ];++ // When visiting https://blabla.asd.com:1234, ONLY the exact match should be returned+ let matches = filter(credentials.clone(), "https://blabla.asd.com:1234/some/path", "Some Page Title");++ // This should return ONLY 1 credential - the exact domain+port match+ assert_eq!(matches.len(), 1, "Should ONLY return the exact domain+port match, not subdomain matches");+ assert_eq!(matches[0].item_name.as_deref(), Some("blabla.asd.com service"));++ // Double-check: items with URLs should NOT be matched via title/name+ // because we already have a URL match (which takes priority)+}++/// [#34] - Items WITHOUT URLs should NOT match when URL match exists+#[test]+fn test_items_without_urls_not_matched_when_url_match_exists() {+ let credentials = vec![+ create_test_credential("blabla service", "https://blabla.asd.com:1234", "[email protected]"),+ // These items have NO URLs - they should NOT be matched via title when URL match exists+ create_test_credential("asd", "", "[email protected]"),+ create_test_credential("blabla", "", "[email protected]"),+ ];++ // When visiting blabla.asd.com:1234, only the URL match should be returned+ // The items named "asd" and "blabla" should NOT match even though page title might contain those words+ let matches = filter(credentials.clone(), "https://blabla.asd.com:1234/login", "Welcome to blabla asd service");++ assert_eq!(matches.len(), 1, "Should only return URL match, not title matches");+ assert_eq!(matches[0].item_name.as_deref(), Some("blabla service"));+}