Skip to content

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

Refactor Rust core tests to separate root folder

Leendert de Borst3e0d3ec91904
diff --git a/core/rust/src/common/encoding.rs b/core/rust/src/common/encoding.rs
index 96b416e2e..90287a20f 100644
--- a/core/rust/src/common/encoding.rs
+++ b/core/rust/src/common/encoding.rs
@@ -74,39 +74,3 @@ pub(crate) fn uuid_from_bytes(mut bytes: [u8; 16], version: u8) -> String {
bytes[8] = (bytes[8] & 0x3f) | 0x80;
format_uuid(&bytes)
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn hex_round_trips_in_both_cases() {
- let bytes = vec![0x00u8, 0x1f, 0xab, 0xff];
- assert_eq!(hex_encode_lower(&bytes), "001fabff");
- assert_eq!(hex_encode_upper(&bytes), "001FABFF");
- assert_eq!(hex_decode("001fabff").unwrap(), bytes);
- assert_eq!(hex_decode("001FABFF").unwrap(), bytes);
- assert_eq!(hex_decode(""), Some(Vec::new()));
- assert_eq!(hex_decode("abc"), None);
- assert_eq!(hex_decode("gg"), None);
- assert_eq!(hex_decode("0é9"), None);
- }
-
- #[test]
- fn base64url_round_trips_without_padding() {
- let bytes = vec![0xfbu8, 0xff, 0xfe];
- let text = base64url_encode(&bytes);
- assert_eq!(text, "-__-");
- assert_eq!(base64url_decode(&text).unwrap(), bytes);
- assert!(base64url_decode("+//+").is_err());
- }
-
- #[test]
- fn uuid_text_form_is_lowercase_and_grouped() {
- let bytes = [0xABu8; 16];
- assert_eq!(format_uuid(&bytes), "abababab-abab-abab-abab-abababababab");
- let stamped = uuid_from_bytes([0xFFu8; 16], 4);
- assert_eq!(&stamped[14..15], "4");
- assert!(matches!(&stamped[19..20], "8" | "9" | "a" | "b"));
- }
-}
diff --git a/core/rust/src/common/mod.rs b/core/rust/src/common/mod.rs
index 020a28d2a..d22bde5b4 100644
--- a/core/rust/src/common/mod.rs
+++ b/core/rust/src/common/mod.rs
@@ -6,3 +6,6 @@ pub(crate) mod gzip;
pub(crate) mod rng;
pub(crate) mod secret;
pub mod timestamp;
+
+#[cfg(test)]
+mod tests;
diff --git a/core/rust/src/common/rng.rs b/core/rust/src/common/rng.rs
index 3e5f25f32..2c443f377 100644
--- a/core/rust/src/common/rng.rs
+++ b/core/rust/src/common/rng.rs
@@ -37,7 +37,7 @@ pub(crate) fn make_rng(seed: Option<&str>) -> StdRng {
}
/// Parse a 64-character hex string into a 32-byte seed, or `None` if it is malformed.
-fn parse_seed_hex(hex: &str) -> Option<[u8; 32]> {
+pub(super) fn parse_seed_hex(hex: &str) -> Option<[u8; 32]> {
crate::common::encoding::hex_decode(hex)?.try_into().ok()
}
@@ -59,50 +59,3 @@ pub(crate) fn unbiased_index<R: Rng + ?Sized>(rng: &mut R, max: usize) -> usize
}
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn seeded_rng() -> StdRng {
- StdRng::from_seed([7u8; 32])
- }
-
- #[test]
- fn unbiased_index_stays_in_range() {
- let mut rng = seeded_rng();
- for max in [2usize, 3, 10, 36, 100] {
- for _ in 0..1000 {
- assert!(unbiased_index(&mut rng, max) < max);
- }
- }
- }
-
- #[test]
- fn unbiased_index_handles_edge_maxes() {
- let mut rng = seeded_rng();
- // max <= 1 short-circuits to 0.
- assert_eq!(unbiased_index(&mut rng, 1), 0);
-
- // Powers of two divide 2^64 evenly (rem == 0): must accept immediately, never hang.
- for shift in [1u32, 8, 16] {
- let max = 1usize << shift;
- assert!(unbiased_index(&mut rng, max) < max);
- }
-
- #[cfg(target_pointer_width = "64")]
- {
- assert!(unbiased_index(&mut rng, 1usize << 62) < (1usize << 62));
- let big = (u32::MAX as usize) + 1;
- assert!(unbiased_index(&mut rng, big) < big);
- assert!(unbiased_index(&mut rng, usize::MAX) < usize::MAX);
- }
- }
-
- #[test]
- fn seed_must_be_exactly_32_bytes_of_hex() {
- assert!(parse_seed_hex(&"ab".repeat(32)).is_some());
- assert!(parse_seed_hex(&"ab".repeat(31)).is_none());
- assert!(parse_seed_hex(&"zz".repeat(32)).is_none());
- }
-}
diff --git a/core/rust/src/common/secret.rs b/core/rust/src/common/secret.rs
index fdbf03c02..4a087d447 100644
--- a/core/rust/src/common/secret.rs
+++ b/core/rust/src/common/secret.rs
@@ -16,22 +16,3 @@ pub fn serialize_option<S: Serializer>(value: &Option<SecretString>, serializer:
None => serializer.serialize_none(),
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use serde::{Deserialize, Serialize};
-
- #[derive(Debug, Serialize, Deserialize)]
- struct Holder {
- #[serde(serialize_with = "serialize_option")]
- key: Option<SecretString>,
- }
-
- #[test]
- fn round_trips_as_a_plain_string_and_never_prints() {
- let holder: Holder = serde_json::from_str(r#"{"key":"k"}"#).unwrap();
- assert_eq!(serde_json::to_string(&holder).unwrap(), r#"{"key":"k"}"#);
- assert!(format!("{:?}", holder).contains("[REDACTED]"));
- }
-}
diff --git a/core/rust/src/common/tests/encoding.rs b/core/rust/src/common/tests/encoding.rs
new file mode 100644
index 000000000..7fccd3649
--- /dev/null
+++ b/core/rust/src/common/tests/encoding.rs
@@ -0,0 +1,32 @@
+use crate::common::encoding::*;
+
+#[test]
+fn hex_round_trips_in_both_cases() {
+ let bytes = vec![0x00u8, 0x1f, 0xab, 0xff];
+ assert_eq!(hex_encode_lower(&bytes), "001fabff");
+ assert_eq!(hex_encode_upper(&bytes), "001FABFF");
+ assert_eq!(hex_decode("001fabff").unwrap(), bytes);
+ assert_eq!(hex_decode("001FABFF").unwrap(), bytes);
+ assert_eq!(hex_decode(""), Some(Vec::new()));
+ assert_eq!(hex_decode("abc"), None);
+ assert_eq!(hex_decode("gg"), None);
+ assert_eq!(hex_decode("0é9"), None);
+}
+
+#[test]
+fn base64url_round_trips_without_padding() {
+ let bytes = vec![0xfbu8, 0xff, 0xfe];
+ let text = base64url_encode(&bytes);
+ assert_eq!(text, "-__-");
+ assert_eq!(base64url_decode(&text).unwrap(), bytes);
+ assert!(base64url_decode("+//+").is_err());
+}
+
+#[test]
+fn uuid_text_form_is_lowercase_and_grouped() {
+ let bytes = [0xABu8; 16];
+ assert_eq!(format_uuid(&bytes), "abababab-abab-abab-abab-abababababab");
+ let stamped = uuid_from_bytes([0xFFu8; 16], 4);
+ assert_eq!(&stamped[14..15], "4");
+ assert!(matches!(&stamped[19..20], "8" | "9" | "a" | "b"));
+}
diff --git a/core/rust/src/common/tests/mod.rs b/core/rust/src/common/tests/mod.rs
new file mode 100644
index 000000000..10ab6fb80
--- /dev/null
+++ b/core/rust/src/common/tests/mod.rs
@@ -0,0 +1,6 @@
+//! Tests of the common modules, one file per module.
+
+mod encoding;
+mod rng;
+mod secret;
+mod timestamp;
diff --git a/core/rust/src/common/tests/rng.rs b/core/rust/src/common/tests/rng.rs
new file mode 100644
index 000000000..845c833c0
--- /dev/null
+++ b/core/rust/src/common/tests/rng.rs
@@ -0,0 +1,45 @@
+use crate::common::rng::*;
+use rand::rngs::StdRng;
+use rand::SeedableRng;
+
+fn seeded_rng() -> StdRng {
+ StdRng::from_seed([7u8; 32])
+}
+
+#[test]
+fn unbiased_index_stays_in_range() {
+ let mut rng = seeded_rng();
+ for max in [2usize, 3, 10, 36, 100] {
+ for _ in 0..1000 {
+ assert!(unbiased_index(&mut rng, max) < max);
+ }
+ }
+}
+
+#[test]
+fn unbiased_index_handles_edge_maxes() {
+ let mut rng = seeded_rng();
+ // max <= 1 short-circuits to 0.
+ assert_eq!(unbiased_index(&mut rng, 1), 0);
+
+ // Powers of two divide 2^64 evenly (rem == 0): must accept immediately, never hang.
+ for shift in [1u32, 8, 16] {
+ let max = 1usize << shift;
+ assert!(unbiased_index(&mut rng, max) < max);
+ }
+
+ #[cfg(target_pointer_width = "64")]
+ {
+ assert!(unbiased_index(&mut rng, 1usize << 62) < (1usize << 62));
+ let big = (u32::MAX as usize) + 1;
+ assert!(unbiased_index(&mut rng, big) < big);
+ assert!(unbiased_index(&mut rng, usize::MAX) < usize::MAX);
+ }
+}
+
+#[test]
+fn seed_must_be_exactly_32_bytes_of_hex() {
+ assert!(parse_seed_hex(&"ab".repeat(32)).is_some());
+ assert!(parse_seed_hex(&"ab".repeat(31)).is_none());
+ assert!(parse_seed_hex(&"zz".repeat(32)).is_none());
+}
diff --git a/core/rust/src/common/tests/secret.rs b/core/rust/src/common/tests/secret.rs
new file mode 100644
index 000000000..9737d1bd7
--- /dev/null
+++ b/core/rust/src/common/tests/secret.rs
@@ -0,0 +1,16 @@
+use crate::common::secret::*;
+use secrecy::SecretString;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Serialize, Deserialize)]
+struct Holder {
+ #[serde(serialize_with = "serialize_option")]
+ key: Option<SecretString>,
+}
+
+#[test]
+fn round_trips_as_a_plain_string_and_never_prints() {
+ let holder: Holder = serde_json::from_str(r#"{"key":"k"}"#).unwrap();
+ assert_eq!(serde_json::to_string(&holder).unwrap(), r#"{"key":"k"}"#);
+ assert!(format!("{:?}", holder).contains("[REDACTED]"));
+}
diff --git a/core/rust/src/common/tests/timestamp.rs b/core/rust/src/common/tests/timestamp.rs
new file mode 100644
index 000000000..e71e481f4
--- /dev/null
+++ b/core/rust/src/common/tests/timestamp.rs
@@ -0,0 +1,21 @@
+use crate::common::timestamp::*;
+use chrono::{DateTime, Utc};
+use std::collections::HashMap;
+
+#[test]
+fn updated_at_parses_both_spellings_a_vault_carries() {
+ let at = |value: &str| -> Option<DateTime<Utc>> { updated_at(&HashMap::from([("UpdatedAt".to_string(), serde_json::json!(value))])) };
+
+ assert_eq!(at("2025-12-11T06:50:10.674Z"), at("2025-12-11 06:50:10.674"));
+ assert!(at("2025-12-11T06:50:11Z") > at("2025-12-11 06:50:10.674"));
+ assert_eq!(at("not a timestamp"), None);
+ assert_eq!(updated_at(&HashMap::new()), None);
+}
+
+#[test]
+fn now_uses_the_vault_and_iso_formats() {
+ let stamp = now_vault_datetime();
+ assert_eq!(stamp.len(), 23);
+ assert_eq!(&stamp[10..11], " ");
+ assert!(now_iso_utc().ends_with('Z'));
+}
diff --git a/core/rust/src/common/timestamp.rs b/core/rust/src/common/timestamp.rs
index 861b07db4..be973d193 100644
--- a/core/rust/src/common/timestamp.rs
+++ b/core/rust/src/common/timestamp.rs
@@ -38,26 +38,3 @@ pub fn parse_vault_datetime(text: &str) -> Option<DateTime<Utc>> {
pub fn updated_at(row: &HashMap<String, serde_json::Value>) -> Option<DateTime<Utc>> {
row.get("UpdatedAt").and_then(|v| v.as_str()).and_then(parse_vault_datetime)
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn updated_at_parses_both_spellings_a_vault_carries() {
- let at = |value: &str| -> Option<DateTime<Utc>> { updated_at(&HashMap::from([("UpdatedAt".to_string(), serde_json::json!(value))])) };
-
- assert_eq!(at("2025-12-11T06:50:10.674Z"), at("2025-12-11 06:50:10.674"));
- assert!(at("2025-12-11T06:50:11Z") > at("2025-12-11 06:50:10.674"));
- assert_eq!(at("not a timestamp"), None);
- assert_eq!(updated_at(&HashMap::new()), None);
- }
-
- #[test]
- fn now_uses_the_vault_and_iso_formats() {
- let stamp = now_vault_datetime();
- assert_eq!(stamp.len(), 23);
- assert_eq!(&stamp[10..11], " ");
- assert!(now_iso_utc().ends_with('Z'));
- }
-}
diff --git a/core/rust/src/credential_matcher/domain.rs b/core/rust/src/credential_matcher/domain.rs
index 2485cf080..4eaf73e87 100644
--- a/core/rust/src/credential_matcher/domain.rs
+++ b/core/rust/src/credential_matcher/domain.rs
@@ -222,7 +222,7 @@ pub fn is_rp_id_allowed_for_host(rp_id: &str, host: &str) -> bool {
}
/// At most this many distinct registrable domain labels are read from a `/.well-known/webauthn` file.
-const MAX_RELATED_ORIGIN_LABELS: usize = 10;
+pub(super) const MAX_RELATED_ORIGIN_LABELS: usize = 10;
/// WebAuthn related origins validation.
pub fn is_related_origin_allowed(caller_origin: &str, origins: &[String]) -> bool {
@@ -268,307 +268,3 @@ fn normalize_rp_host(value: &str) -> Option<String> {
}
Some(normalized.to_string())
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn detects_app_package_names() {
- assert!(is_app_package_name("com.coolblue.app"));
- assert!(is_app_package_name("nl.marktplaats.android"));
- assert!(is_app_package_name("org.example.app"));
-
- assert!(!is_app_package_name("https://example.com"));
- assert!(!is_app_package_name("example.com"));
- assert!(!is_app_package_name("coolblue.nl"));
- assert!(!is_app_package_name("nodot"));
- assert!(is_app_package_name("tv.twitch.android.app"));
- assert!(!is_app_package_name("app.example.com"), "a scheme-less hostname under a common subdomain word");
- }
-
- #[test]
- fn extracts_domain() {
- assert_eq!(extract_domain("https://www.example.com/path"), "example.com");
- assert_eq!(extract_domain("http://example.com"), "example.com");
- assert_eq!(extract_domain("example.com"), "example.com");
- assert_eq!(extract_domain("www.example.com"), "example.com");
- assert_eq!(extract_domain("https://example.com?query=1"), "example.com");
- assert_eq!(extract_domain("https://example.com#fragment"), "example.com");
-
- // Package names should return empty
- assert_eq!(extract_domain("com.coolblue.app"), "");
-
- // Invalid domains
- assert_eq!(extract_domain(""), "");
- assert_eq!(extract_domain("nodot"), "");
-
- // Single-word hostnames WITH protocol should be supported
- // (common in self-hosted/homelab setups with local DNS or /etc/hosts)
- assert_eq!(extract_domain("http://localhost"), "localhost");
- assert_eq!(extract_domain("https://localhost"), "localhost");
- assert_eq!(extract_domain("http://localhost/path"), "localhost");
- assert_eq!(extract_domain("http://localhost?query=1"), "localhost");
- assert_eq!(extract_domain("http://plex"), "plex");
- assert_eq!(extract_domain("https://nas"), "nas");
- assert_eq!(extract_domain("http://router"), "router");
- assert_eq!(extract_domain("http://homeassistant"), "homeassistant");
- assert_eq!(extract_domain("http://pihole/admin"), "pihole");
-
- // Single-word hostnames without protocol should not be accepted
- // (to avoid matching random text as domains)
- assert_eq!(extract_domain("localhost"), "");
- assert_eq!(extract_domain("plex"), "");
- assert_eq!(extract_domain("randomword"), "");
- }
-
- #[test]
- fn extract_domain_single_word_hostname_with_port() {
- // Single-word hostnames with port (common for self-hosted services)
- assert_eq!(extract_domain("http://localhost:8080"), "localhost");
- assert_eq!(extract_domain("http://localhost:81"), "localhost");
- assert_eq!(extract_domain("http://localhost:3000/path"), "localhost");
- assert_eq!(extract_domain("http://plex:32400"), "plex");
- assert_eq!(extract_domain("https://nas:5001"), "nas");
- assert_eq!(extract_domain("http://router:8080/admin"), "router");
-
- // Without protocol - should not work (could be ambiguous)
- assert_eq!(extract_domain("localhost:8080"), "");
- assert_eq!(extract_domain("plex:32400"), "");
-
- // Test DomainWithPort struct with localhost
- let result = extract_domain_with_port("http://localhost:81");
- assert_eq!(result.domain, "localhost");
- assert_eq!(result.port, Some("81".to_string()));
- assert_eq!(result.with_port(), "localhost:81");
-
- let result = extract_domain_with_port("http://localhost:8080/path");
- assert_eq!(result.domain, "localhost");
- assert_eq!(result.port, Some("8080".to_string()));
-
- let result = extract_domain_with_port("http://localhost/path");
- assert_eq!(result.domain, "localhost");
- assert_eq!(result.port, None);
-
- // Test with other single-word hostnames
- let result = extract_domain_with_port("http://plex:32400");
- assert_eq!(result.domain, "plex");
- assert_eq!(result.port, Some("32400".to_string()));
-
- let result = extract_domain_with_port("https://nas:5001/files");
- assert_eq!(result.domain, "nas");
- assert_eq!(result.port, Some("5001".to_string()));
- }
-
- #[test]
- fn extract_domain_strips_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 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 extract_domain_normalizes_host() {
- // Userinfo is dropped: the host is what follows the last "@".
- assert_eq!(extract_domain("https://[email protected]/"), "evil.com");
- assert_eq!(extract_domain("https://user:[email protected]:8443/"), "example.com");
-
- // One trailing dot is dropped, before the "www." prefix.
- assert_eq!(extract_domain("https://paypal.com./"), "paypal.com");
- assert_eq!(extract_domain("https://www.paypal.com./"), "paypal.com");
- assert_eq!(extract_domain("https://paypal.com../"), "");
-
- // Underscores are accepted in host labels.
- assert_eq!(extract_domain("https://www_paypal.evil.com/"), "www_paypal.evil.com");
-
- // Bracketed IPv6 keeps its brackets and splits off the port after the bracket.
- let ipv6 = extract_domain_with_port("http://[::1]:8080/paypal");
- assert_eq!(ipv6.domain, "[::1]");
- assert_eq!(ipv6.port, Some("8080".to_string()));
- assert_eq!(extract_domain("http://[2001:db8::1]/"), "[2001:db8::1]");
- assert_eq!(extract_domain("http://[::1/"), "");
-
- // A blob URL resolves to the origin it wraps; other non-web schemes give no domain.
- assert_eq!(extract_domain("blob:https://paypal.evil.com/0b2c3d4e"), "paypal.evil.com");
- assert_eq!(extract_domain("blob:null/0b2c3d4e"), "");
- assert_eq!(extract_domain("filesystem:https://paypal.com/temporary/x"), "");
- assert_eq!(extract_domain("data:text/html,paypal.com"), "");
- }
-
- #[test]
- fn extracts_root_domain() {
- assert_eq!(extract_root_domain("sub.example.com"), "example.com");
- assert_eq!(extract_root_domain("example.com"), "example.com");
- assert_eq!(extract_root_domain("sub.example.co.uk"), "example.co.uk");
- assert_eq!(extract_root_domain("example.co.uk"), "example.co.uk");
- assert_eq!(extract_root_domain("sub.example.com.au"), "example.com.au");
- assert_eq!(extract_root_domain("preview.myproject.vercel.app"), "myproject.vercel.app");
-
- // A public suffix or single label has no root domain of its own and is returned as-is.
- assert_eq!(extract_root_domain("github.io"), "github.io");
- assert_eq!(extract_root_domain("localhost"), "localhost");
- assert_eq!(extract_root_domain("plex"), "plex");
-
- // A trailing dot never reduces a domain to its TLD: "bank.com." and "evil.com." must not share "com.".
- assert_eq!(extract_root_domain("bank.com."), "bank.com");
- assert_eq!(extract_root_domain("login.bank.com."), "bank.com");
- assert_eq!(extract_root_domain("victim.vercel.app."), "victim.vercel.app");
- assert_eq!(extract_root_domain("com."), "com.");
-
- // A malformed domain has no root domain and is returned as-is.
- assert_eq!(extract_root_domain(".com"), ".com");
- assert_eq!(extract_root_domain("a..b.com"), "a..b.com");
- assert_eq!(extract_root_domain(".."), "..");
- }
-
- #[test]
- fn extract_root_domain_keeps_ip_literals() {
- assert_eq!(extract_root_domain("192.168.1.5"), "192.168.1.5");
- assert_eq!(extract_root_domain("10.0.0.1"), "10.0.0.1");
- assert_eq!(extract_root_domain("::1"), "::1");
- assert_eq!(extract_root_domain("[2001:db8::1]"), "[2001:db8::1]");
- assert_eq!(extract_root_domain("192.168.1.5."), "192.168.1.5.");
- }
-
- #[test]
- fn related_origins_allowlist() {
- let origins = |list: &[&str]| list.iter().map(|o| o.to_string()).collect::<Vec<_>>();
-
- let x = origins(&["https://twitter.com", "https://x.com", "https://mobile.twitter.com:8443"]);
- assert!(is_related_origin_allowed("https://twitter.com", &x));
- assert!(is_related_origin_allowed("https://mobile.twitter.com:8443", &x));
- assert!(!is_related_origin_allowed("https://mobile.twitter.com", &x));
- assert!(!is_related_origin_allowed("http://twitter.com", &x));
- assert!(!is_related_origin_allowed("https://evil.com", &x));
- assert!(!is_related_origin_allowed("https://twitter.com", &[]));
-
- // Only the first MAX_RELATED_ORIGIN_LABELS distinct labels count; origins sharing a counted label stay reachable.
- let mut many: Vec<String> = (0..=MAX_RELATED_ORIGIN_LABELS).map(|i| format!("https://site{i}.com")).collect();
- many.extend(origins(&["https://shop.site0.co.uk", "https://www.site1.com"]));
- assert!(is_related_origin_allowed(&format!("https://site{}.com", MAX_RELATED_ORIGIN_LABELS - 1), &many));
- assert!(!is_related_origin_allowed(&format!("https://site{MAX_RELATED_ORIGIN_LABELS}.com"), &many));
- assert!(is_related_origin_allowed("https://shop.site0.co.uk", &many));
- assert!(is_related_origin_allowed("https://www.site1.com", &many));
-
- // Entries without a registrable domain neither match nor use up a label.
- let mut skipped = origins(&["https://vercel.app", "https://192.168.1.5", "https://localhost", "null"]);
- skipped.extend((1..=MAX_RELATED_ORIGIN_LABELS).map(|i| format!("https://{i}.com")));
- assert!(!is_related_origin_allowed("https://vercel.app", &skipped));
- assert!(!is_related_origin_allowed("https://192.168.1.5", &skipped));
- assert!(!is_related_origin_allowed("null", &skipped));
- assert!(is_related_origin_allowed(&format!("https://{MAX_RELATED_ORIGIN_LABELS}.com"), &skipped));
- }
-
- #[test]
- fn rp_id_allowed_for_host_or_parent() {
- // The host itself and parent domains below the public suffix.
- assert!(is_rp_id_allowed_for_host("example.com", "login.example.com"));
- assert!(is_rp_id_allowed_for_host("Example.COM.", "login.example.com"));
- assert!(is_rp_id_allowed_for_host("myproject.vercel.app", "preview.myproject.vercel.app"));
- assert!(is_rp_id_allowed_for_host("github.io", "github.io"));
-
- // Public suffixes, siblings and lookalikes.
- assert!(!is_rp_id_allowed_for_host("vercel.app", "evil.vercel.app"));
- assert!(!is_rp_id_allowed_for_host("district.sch.uk", "myschool.district.sch.uk"));
- assert!(!is_rp_id_allowed_for_host("accounts.example.com", "evil.example.com"));
- assert!(!is_rp_id_allowed_for_host("example.com", "myexample.com"));
-
- // IP addresses only as themselves, malformed input never.
- assert!(is_rp_id_allowed_for_host("192.168.1.5", "192.168.1.5"));
- assert!(!is_rp_id_allowed_for_host("1.5", "192.168.1.5"));
- assert!(!is_rp_id_allowed_for_host("", "example.com"));
- assert!(!is_rp_id_allowed_for_host("example.com:443", "example.com"));
- }
-
- #[test]
- fn ip_literals_require_exact_match() {
- // Same IP matches
- assert!(domains_match("192.168.1.5", "192.168.1.5"));
-
- // Distinct IPs sharing trailing octets must not match
- assert!(!domains_match("192.168.1.5", "10.0.1.5"));
-
- // An IP must not be treated as a "subdomain" of a suffix of itself
- assert!(!domains_match("192.168.1.5", "168.1.5"));
- assert!(!domains_match("168.1.5", "192.168.1.5"));
-
- // IP vs regular domain never matches
- assert!(!domains_match("192.168.1.5", "example.com"));
-
- // IPv6 literals: exact match only (bare and bracketed forms)
- assert!(domains_match("::1", "::1"));
- assert!(!domains_match("::1", "::2"));
- assert!(domains_match("[2001:db8::1]", "[2001:db8::1]"));
- assert!(!domains_match("[2001:db8::1]", "[2001:db8::2]"));
- }
-
- #[test]
- fn matches_domains() {
- // Exact match
- assert!(domains_match("example.com", "example.com"));
-
- // Subdomain match
- assert!(domains_match("sub.example.com", "example.com"));
- assert!(domains_match("example.com", "sub.example.com"));
-
- // Root domain match
- assert!(domains_match("app.example.com", "www.example.com"));
-
- // 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"));
- }
-
- #[test]
- fn domains_match_shared_hosting_tenants() {
- // Sibling tenants on a shared suffix never match; the same tenant matches across its own subdomains.
- assert!(!domains_match("myproject.vercel.app", "evil-phish.vercel.app"));
- assert!(domains_match("preview.myproject.vercel.app", "myproject.vercel.app"));
-
- // A public suffix never matches the hosts under it, only itself.
- assert!(!domains_match("vercel.app", "myproject.vercel.app"));
- assert!(!domains_match("myhome.duckdns.org", "duckdns.org"));
- assert!(domains_match("duckdns.org", "duckdns.org"));
-
- // Internal hosts under an unlisted suffix keep matching on their last two labels.
- assert!(domains_match("nas.home.lan", "plex.home.lan"));
- }
-}
diff --git a/core/rust/src/credential_matcher/public_suffix/mod.rs b/core/rust/src/credential_matcher/public_suffix/mod.rs
index 57363c707..91cec87a4 100644
--- a/core/rust/src/credential_matcher/public_suffix/mod.rs
+++ b/core/rust/src/credential_matcher/public_suffix/mod.rs
@@ -83,105 +83,3 @@ pub fn registrable_domain(host: &str) -> Option<&str> {
Some(&host[starts[label_count - suffix_labels - 1]..])
}
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn list_is_loaded_with_both_sections() {
- assert!(RULES.plain.len() > 5000, "expected the full list, got {} plain rules", RULES.plain.len());
- assert!(RULES.plain.contains("nl"), "ICANN section missing");
- assert!(RULES.plain.contains("co.uk"), "ICANN section missing");
- assert!(RULES.plain.contains("github.io"), "PRIVATE section missing");
- assert!(RULES.wildcard.contains("sch.uk"));
- assert!(RULES.exception.contains("www.ck"));
- }
-
- #[test]
- fn plain_rules() {
- assert_eq!(registrable_domain("example.com"), Some("example.com"));
- assert_eq!(registrable_domain("mijn.overheid.nl"), Some("overheid.nl"));
- assert_eq!(registrable_domain("login.bank.co.nl"), Some("bank.co.nl"));
- assert_eq!(registrable_domain("docs.example.co.uk"), Some("example.co.uk"));
- assert_eq!(registrable_domain("a.b.example.org.uk"), Some("example.org.uk"));
- // Rules with more labels win over shorter ones: "site.hosting-cluster.nl" is listed next to "hosting-cluster.nl".
- assert_eq!(registrable_domain("shop.hosting-cluster.nl"), Some("shop.hosting-cluster.nl"));
- assert_eq!(registrable_domain("www.shop.site.hosting-cluster.nl"), Some("shop.site.hosting-cluster.nl"));
- }
-
- #[test]
- fn public_suffix_itself_has_no_registrable_domain() {
- assert_eq!(registrable_domain("com"), None);
- assert_eq!(registrable_domain("nl"), None);
- assert_eq!(registrable_domain("co.uk"), None);
- assert_eq!(registrable_domain("gov.nl"), None);
- assert_eq!(registrable_domain("github.io"), None);
- assert_eq!(registrable_domain("localhost"), None);
- assert_eq!(registrable_domain(""), None);
- }
-
- #[test]
- fn private_section_splits_tenants() {
- assert_eq!(registrable_domain("myproject.vercel.app"), Some("myproject.vercel.app"));
- assert_eq!(registrable_domain("evil-phish.vercel.app"), Some("evil-phish.vercel.app"));
- assert_eq!(registrable_domain("preview.myproject.vercel.app"), Some("myproject.vercel.app"));
- assert_eq!(registrable_domain("user.github.io"), Some("user.github.io"));
- assert_eq!(registrable_domain("group.gitlab.io"), Some("group.gitlab.io"));
- assert_eq!(registrable_domain("site.pages.dev"), Some("site.pages.dev"));
- assert_eq!(registrable_domain("app.netlify.app"), Some("app.netlify.app"));
- assert_eq!(registrable_domain("api.herokuapp.com"), Some("api.herokuapp.com"));
- assert_eq!(registrable_domain("webshop.azurewebsites.net"), Some("webshop.azurewebsites.net"));
- assert_eq!(registrable_domain("myapp.readthedocs.io"), Some("myapp.readthedocs.io"));
- assert_eq!(registrable_domain("tax.service.gov.uk"), Some("tax.service.gov.uk"));
- }
-
- #[test]
- fn wildcard_rules() {
- // "*.sch.uk" makes every school district under sch.uk a public suffix.
- assert_eq!(registrable_domain("district.sch.uk"), None);
- assert_eq!(registrable_domain("myschool.district.sch.uk"), Some("myschool.district.sch.uk"));
- assert_eq!(registrable_domain("www.myschool.district.sch.uk"), Some("myschool.district.sch.uk"));
- // "*.elb.amazonaws.com" in the PRIVATE section: each load balancer is its own registrable domain.
- assert_eq!(registrable_domain("my-lb-123.eu-west-1.elb.amazonaws.com"), Some("my-lb-123.eu-west-1.elb.amazonaws.com"));
- }
-
- #[test]
- fn exception_rules() {
- // The list only has exception rules under .ck and a few Japanese cities: "*.ck" with "!www.ck".
- assert_eq!(registrable_domain("foo.ck"), None);
- assert_eq!(registrable_domain("bar.foo.ck"), Some("bar.foo.ck"));
- assert_eq!(registrable_domain("www.ck"), Some("www.ck"));
- assert_eq!(registrable_domain("sub.www.ck"), Some("www.ck"));
- }
-
- #[test]
- fn unlisted_suffix_falls_back_to_last_label() {
- assert_eq!(registrable_domain("nas.home.lan"), Some("home.lan"));
- assert_eq!(registrable_domain("myserver.local"), Some("myserver.local"));
- assert_eq!(registrable_domain("plex.myserver.local"), Some("myserver.local"));
- assert_eq!(registrable_domain("app.localhost"), Some("app.localhost"));
- }
-
- #[test]
- fn trailing_dot_and_empty_labels() {
- // A fully qualified host has the same registrable domain as without its trailing dot, never the bare TLD.
- assert_eq!(registrable_domain("bank.com."), Some("bank.com"));
- assert_eq!(registrable_domain("login.bank.com."), Some("bank.com"));
- assert_eq!(registrable_domain("victim.vercel.app."), Some("victim.vercel.app"));
- assert_eq!(registrable_domain("com."), None);
- assert_eq!(registrable_domain("vercel.app."), None);
-
- // Empty labels make a host malformed: no registrable domain at all.
- assert_eq!(registrable_domain(".com"), None);
- assert_eq!(registrable_domain("a..b.com"), None);
- assert_eq!(registrable_domain("bank.com.."), None);
- assert_eq!(registrable_domain(".."), None);
- assert_eq!(registrable_domain("."), None);
- }
-
- #[test]
- fn lookup_is_case_insensitive_and_keeps_input_casing() {
- assert_eq!(registrable_domain("Login.Example.CO.UK"), Some("Example.CO.UK"));
- assert_eq!(registrable_domain("My.Overheid.NL"), Some("Overheid.NL"));
- }
-}
diff --git a/core/rust/src/credential_matcher/tests/domain.rs b/core/rust/src/credential_matcher/tests/domain.rs
new file mode 100644
index 000000000..e0b6b1cef
--- /dev/null
+++ b/core/rust/src/credential_matcher/tests/domain.rs
@@ -0,0 +1,300 @@
+use crate::credential_matcher::domain::*;
+
+#[test]
+fn detects_app_package_names() {
+ assert!(is_app_package_name("com.coolblue.app"));
+ assert!(is_app_package_name("nl.marktplaats.android"));
+ assert!(is_app_package_name("org.example.app"));
+
+ assert!(!is_app_package_name("https://example.com"));
+ assert!(!is_app_package_name("example.com"));
+ assert!(!is_app_package_name("coolblue.nl"));
+ assert!(!is_app_package_name("nodot"));
+ assert!(is_app_package_name("tv.twitch.android.app"));
+ assert!(!is_app_package_name("app.example.com"), "a scheme-less hostname under a common subdomain word");
+}
+
+#[test]
+fn extracts_domain() {
+ assert_eq!(extract_domain("https://www.example.com/path"), "example.com");
+ assert_eq!(extract_domain("http://example.com"), "example.com");
+ assert_eq!(extract_domain("example.com"), "example.com");
+ assert_eq!(extract_domain("www.example.com"), "example.com");
+ assert_eq!(extract_domain("https://example.com?query=1"), "example.com");
+ assert_eq!(extract_domain("https://example.com#fragment"), "example.com");
+
+ // Package names should return empty
+ assert_eq!(extract_domain("com.coolblue.app"), "");
+
+ // Invalid domains
+ assert_eq!(extract_domain(""), "");
+ assert_eq!(extract_domain("nodot"), "");
+
+ // Single-word hostnames WITH protocol should be supported
+ // (common in self-hosted/homelab setups with local DNS or /etc/hosts)
+ assert_eq!(extract_domain("http://localhost"), "localhost");
+ assert_eq!(extract_domain("https://localhost"), "localhost");
+ assert_eq!(extract_domain("http://localhost/path"), "localhost");
+ assert_eq!(extract_domain("http://localhost?query=1"), "localhost");
+ assert_eq!(extract_domain("http://plex"), "plex");
+ assert_eq!(extract_domain("https://nas"), "nas");
+ assert_eq!(extract_domain("http://router"), "router");
+ assert_eq!(extract_domain("http://homeassistant"), "homeassistant");
+ assert_eq!(extract_domain("http://pihole/admin"), "pihole");
+
+ // Single-word hostnames without protocol should not be accepted
+ // (to avoid matching random text as domains)
+ assert_eq!(extract_domain("localhost"), "");
+ assert_eq!(extract_domain("plex"), "");
+ assert_eq!(extract_domain("randomword"), "");
+}
+
+#[test]
+fn extract_domain_single_word_hostname_with_port() {
+ // Single-word hostnames with port (common for self-hosted services)
+ assert_eq!(extract_domain("http://localhost:8080"), "localhost");
+ assert_eq!(extract_domain("http://localhost:81"), "localhost");
+ assert_eq!(extract_domain("http://localhost:3000/path"), "localhost");
+ assert_eq!(extract_domain("http://plex:32400"), "plex");
+ assert_eq!(extract_domain("https://nas:5001"), "nas");
+ assert_eq!(extract_domain("http://router:8080/admin"), "router");
+
+ // Without protocol - should not work (could be ambiguous)
+ assert_eq!(extract_domain("localhost:8080"), "");
+ assert_eq!(extract_domain("plex:32400"), "");
+
+ // Test DomainWithPort struct with localhost
+ let result = extract_domain_with_port("http://localhost:81");
+ assert_eq!(result.domain, "localhost");
+ assert_eq!(result.port, Some("81".to_string()));
+ assert_eq!(result.with_port(), "localhost:81");
+
+ let result = extract_domain_with_port("http://localhost:8080/path");
+ assert_eq!(result.domain, "localhost");
+ assert_eq!(result.port, Some("8080".to_string()));
+
+ let result = extract_domain_with_port("http://localhost/path");
+ assert_eq!(result.domain, "localhost");
+ assert_eq!(result.port, None);
+
+ // Test with other single-word hostnames
+ let result = extract_domain_with_port("http://plex:32400");
+ assert_eq!(result.domain, "plex");
+ assert_eq!(result.port, Some("32400".to_string()));
+
+ let result = extract_domain_with_port("https://nas:5001/files");
+ assert_eq!(result.domain, "nas");
+ assert_eq!(result.port, Some("5001".to_string()));
+}
+
+#[test]
+fn extract_domain_strips_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 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 extract_domain_normalizes_host() {
+ // Userinfo is dropped: the host is what follows the last "@".
+ assert_eq!(extract_domain("https://[email protected]/"), "evil.com");
+ assert_eq!(extract_domain("https://user:[email protected]:8443/"), "example.com");
+
+ // One trailing dot is dropped, before the "www." prefix.
+ assert_eq!(extract_domain("https://paypal.com./"), "paypal.com");
+ assert_eq!(extract_domain("https://www.paypal.com./"), "paypal.com");
+ assert_eq!(extract_domain("https://paypal.com../"), "");
+
+ // Underscores are accepted in host labels.
+ assert_eq!(extract_domain("https://www_paypal.evil.com/"), "www_paypal.evil.com");
+
+ // Bracketed IPv6 keeps its brackets and splits off the port after the bracket.
+ let ipv6 = extract_domain_with_port("http://[::1]:8080/paypal");
+ assert_eq!(ipv6.domain, "[::1]");
+ assert_eq!(ipv6.port, Some("8080".to_string()));
+ assert_eq!(extract_domain("http://[2001:db8::1]/"), "[2001:db8::1]");
+ assert_eq!(extract_domain("http://[::1/"), "");
+
+ // A blob URL resolves to the origin it wraps; other non-web schemes give no domain.
+ assert_eq!(extract_domain("blob:https://paypal.evil.com/0b2c3d4e"), "paypal.evil.com");
+ assert_eq!(extract_domain("blob:null/0b2c3d4e"), "");
+ assert_eq!(extract_domain("filesystem:https://paypal.com/temporary/x"), "");
+ assert_eq!(extract_domain("data:text/html,paypal.com"), "");
+}
+
+#[test]
+fn extracts_root_domain() {
+ assert_eq!(extract_root_domain("sub.example.com"), "example.com");
+ assert_eq!(extract_root_domain("example.com"), "example.com");
+ assert_eq!(extract_root_domain("sub.example.co.uk"), "example.co.uk");
+ assert_eq!(extract_root_domain("example.co.uk"), "example.co.uk");
+ assert_eq!(extract_root_domain("sub.example.com.au"), "example.com.au");
+ assert_eq!(extract_root_domain("preview.myproject.vercel.app"), "myproject.vercel.app");
+
+ // A public suffix or single label has no root domain of its own and is returned as-is.
+ assert_eq!(extract_root_domain("github.io"), "github.io");
+ assert_eq!(extract_root_domain("localhost"), "localhost");
+ assert_eq!(extract_root_domain("plex"), "plex");
+
+ // A trailing dot never reduces a domain to its TLD: "bank.com." and "evil.com." must not share "com.".
+ assert_eq!(extract_root_domain("bank.com."), "bank.com");
+ assert_eq!(extract_root_domain("login.bank.com."), "bank.com");
+ assert_eq!(extract_root_domain("victim.vercel.app."), "victim.vercel.app");
+ assert_eq!(extract_root_domain("com."), "com.");
+
+ // A malformed domain has no root domain and is returned as-is.
+ assert_eq!(extract_root_domain(".com"), ".com");
+ assert_eq!(extract_root_domain("a..b.com"), "a..b.com");
+ assert_eq!(extract_root_domain(".."), "..");
+}
+
+#[test]
+fn extract_root_domain_keeps_ip_literals() {
+ assert_eq!(extract_root_domain("192.168.1.5"), "192.168.1.5");
+ assert_eq!(extract_root_domain("10.0.0.1"), "10.0.0.1");
+ assert_eq!(extract_root_domain("::1"), "::1");
+ assert_eq!(extract_root_domain("[2001:db8::1]"), "[2001:db8::1]");
+ assert_eq!(extract_root_domain("192.168.1.5."), "192.168.1.5.");
+}
+
+#[test]
+fn related_origins_allowlist() {
+ let origins = |list: &[&str]| list.iter().map(|o| o.to_string()).collect::<Vec<_>>();
+
+ let x = origins(&["https://twitter.com", "https://x.com", "https://mobile.twitter.com:8443"]);
+ assert!(is_related_origin_allowed("https://twitter.com", &x));
+ assert!(is_related_origin_allowed("https://mobile.twitter.com:8443", &x));
+ assert!(!is_related_origin_allowed("https://mobile.twitter.com", &x));
+ assert!(!is_related_origin_allowed("http://twitter.com", &x));
+ assert!(!is_related_origin_allowed("https://evil.com", &x));
+ assert!(!is_related_origin_allowed("https://twitter.com", &[]));
+
+ // Only the first MAX_RELATED_ORIGIN_LABELS distinct labels count; origins sharing a counted label stay reachable.
+ let mut many: Vec<String> = (0..=MAX_RELATED_ORIGIN_LABELS).map(|i| format!("https://site{i}.com")).collect();
+ many.extend(origins(&["https://shop.site0.co.uk", "https://www.site1.com"]));
+ assert!(is_related_origin_allowed(&format!("https://site{}.com", MAX_RELATED_ORIGIN_LABELS - 1), &many));
+ assert!(!is_related_origin_allowed(&format!("https://site{MAX_RELATED_ORIGIN_LABELS}.com"), &many));
+ assert!(is_related_origin_allowed("https://shop.site0.co.uk", &many));
+ assert!(is_related_origin_allowed("https://www.site1.com", &many));
+
+ // Entries without a registrable domain neither match nor use up a label.
+ let mut skipped = origins(&["https://vercel.app", "https://192.168.1.5", "https://localhost", "null"]);
+ skipped.extend((1..=MAX_RELATED_ORIGIN_LABELS).map(|i| format!("https://{i}.com")));
+ assert!(!is_related_origin_allowed("https://vercel.app", &skipped));
+ assert!(!is_related_origin_allowed("https://192.168.1.5", &skipped));
+ assert!(!is_related_origin_allowed("null", &skipped));
+ assert!(is_related_origin_allowed(&format!("https://{MAX_RELATED_ORIGIN_LABELS}.com"), &skipped));
+}
+
+#[test]
+fn rp_id_allowed_for_host_or_parent() {
+ // The host itself and parent domains below the public suffix.
+ assert!(is_rp_id_allowed_for_host("example.com", "login.example.com"));
+ assert!(is_rp_id_allowed_for_host("Example.COM.", "login.example.com"));
+ assert!(is_rp_id_allowed_for_host("myproject.vercel.app", "preview.myproject.vercel.app"));
+ assert!(is_rp_id_allowed_for_host("github.io", "github.io"));
+
+ // Public suffixes, siblings and lookalikes.
+ assert!(!is_rp_id_allowed_for_host("vercel.app", "evil.vercel.app"));
+ assert!(!is_rp_id_allowed_for_host("district.sch.uk", "myschool.district.sch.uk"));
+ assert!(!is_rp_id_allowed_for_host("accounts.example.com", "evil.example.com"));
+ assert!(!is_rp_id_allowed_for_host("example.com", "myexample.com"));
+
+ // IP addresses only as themselves, malformed input never.
+ assert!(is_rp_id_allowed_for_host("192.168.1.5", "192.168.1.5"));
+ assert!(!is_rp_id_allowed_for_host("1.5", "192.168.1.5"));
+ assert!(!is_rp_id_allowed_for_host("", "example.com"));
+ assert!(!is_rp_id_allowed_for_host("example.com:443", "example.com"));
+}
+
+#[test]
+fn ip_literals_require_exact_match() {
+ // Same IP matches
+ assert!(domains_match("192.168.1.5", "192.168.1.5"));
+
+ // Distinct IPs sharing trailing octets must not match
+ assert!(!domains_match("192.168.1.5", "10.0.1.5"));
+
+ // An IP must not be treated as a "subdomain" of a suffix of itself
+ assert!(!domains_match("192.168.1.5", "168.1.5"));
+ assert!(!domains_match("168.1.5", "192.168.1.5"));
+
+ // IP vs regular domain never matches
+ assert!(!domains_match("192.168.1.5", "example.com"));
+
+ // IPv6 literals: exact match only (bare and bracketed forms)
+ assert!(domains_match("::1", "::1"));
+ assert!(!domains_match("::1", "::2"));
+ assert!(domains_match("[2001:db8::1]", "[2001:db8::1]"));
+ assert!(!domains_match("[2001:db8::1]", "[2001:db8::2]"));
+}
+
+#[test]
+fn matches_domains() {
+ // Exact match
+ assert!(domains_match("example.com", "example.com"));
+
+ // Subdomain match
+ assert!(domains_match("sub.example.com", "example.com"));
+ assert!(domains_match("example.com", "sub.example.com"));
+
+ // Root domain match
+ assert!(domains_match("app.example.com", "www.example.com"));
+
+ // 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"));
+}
+
+#[test]
+fn domains_match_shared_hosting_tenants() {
+ // Sibling tenants on a shared suffix never match; the same tenant matches across its own subdomains.
+ assert!(!domains_match("myproject.vercel.app", "evil-phish.vercel.app"));
+ assert!(domains_match("preview.myproject.vercel.app", "myproject.vercel.app"));
+
+ // A public suffix never matches the hosts under it, only itself.
+ assert!(!domains_match("vercel.app", "myproject.vercel.app"));
+ assert!(!domains_match("myhome.duckdns.org", "duckdns.org"));
+ assert!(domains_match("duckdns.org", "duckdns.org"));
+
+ // Internal hosts under an unlisted suffix keep matching on their last two labels.
+ assert!(domains_match("nas.home.lan", "plex.home.lan"));
+}
diff --git a/core/rust/src/credential_matcher/tests/mod.rs b/core/rust/src/credential_matcher/tests/mod.rs
index 330843039..45f764087 100644
--- a/core/rust/src/credential_matcher/tests/mod.rs
+++ b/core/rust/src/credential_matcher/tests/mod.rs
@@ -1,6 +1,9 @@
//! The autofill matcher: which credentials a URL, app package or page title offers, in priority order, and which
//! it must never offer (anti-phishing).
+mod domain;
+mod public_suffix;
+
use super::*;
fn credential(name: &str, urls: &[&str], username: &str) -> Credential {
diff --git a/core/rust/src/credential_matcher/tests/public_suffix.rs b/core/rust/src/credential_matcher/tests/public_suffix.rs
new file mode 100644
index 000000000..bd6bbd894
--- /dev/null
+++ b/core/rust/src/credential_matcher/tests/public_suffix.rs
@@ -0,0 +1,89 @@
+use crate::credential_matcher::public_suffix::*;
+
+#[test]
+fn plain_rules() {
+ assert_eq!(registrable_domain("example.com"), Some("example.com"));
+ assert_eq!(registrable_domain("mijn.overheid.nl"), Some("overheid.nl"));
+ assert_eq!(registrable_domain("login.bank.co.nl"), Some("bank.co.nl"));
+ assert_eq!(registrable_domain("docs.example.co.uk"), Some("example.co.uk"));
+ assert_eq!(registrable_domain("a.b.example.org.uk"), Some("example.org.uk"));
+ // Rules with more labels win over shorter ones: "site.hosting-cluster.nl" is listed next to "hosting-cluster.nl".
+ assert_eq!(registrable_domain("shop.hosting-cluster.nl"), Some("shop.hosting-cluster.nl"));
+ assert_eq!(registrable_domain("www.shop.site.hosting-cluster.nl"), Some("shop.site.hosting-cluster.nl"));
+}
+
+#[test]
+fn public_suffix_itself_has_no_registrable_domain() {
+ assert_eq!(registrable_domain("com"), None);
+ assert_eq!(registrable_domain("nl"), None);
+ assert_eq!(registrable_domain("co.uk"), None);
+ assert_eq!(registrable_domain("gov.nl"), None);
+ assert_eq!(registrable_domain("github.io"), None);
+ assert_eq!(registrable_domain("localhost"), None);
+ assert_eq!(registrable_domain(""), None);
+}
+
+#[test]
+fn private_section_splits_tenants() {
+ assert_eq!(registrable_domain("myproject.vercel.app"), Some("myproject.vercel.app"));
+ assert_eq!(registrable_domain("evil-phish.vercel.app"), Some("evil-phish.vercel.app"));
+ assert_eq!(registrable_domain("preview.myproject.vercel.app"), Some("myproject.vercel.app"));
+ assert_eq!(registrable_domain("user.github.io"), Some("user.github.io"));
+ assert_eq!(registrable_domain("group.gitlab.io"), Some("group.gitlab.io"));
+ assert_eq!(registrable_domain("site.pages.dev"), Some("site.pages.dev"));
+ assert_eq!(registrable_domain("app.netlify.app"), Some("app.netlify.app"));
+ assert_eq!(registrable_domain("api.herokuapp.com"), Some("api.herokuapp.com"));
+ assert_eq!(registrable_domain("webshop.azurewebsites.net"), Some("webshop.azurewebsites.net"));
+ assert_eq!(registrable_domain("myapp.readthedocs.io"), Some("myapp.readthedocs.io"));
+ assert_eq!(registrable_domain("tax.service.gov.uk"), Some("tax.service.gov.uk"));
+}
+
+#[test]
+fn wildcard_rules() {
+ // "*.sch.uk" makes every school district under sch.uk a public suffix.
+ assert_eq!(registrable_domain("district.sch.uk"), None);
+ assert_eq!(registrable_domain("myschool.district.sch.uk"), Some("myschool.district.sch.uk"));
+ assert_eq!(registrable_domain("www.myschool.district.sch.uk"), Some("myschool.district.sch.uk"));
+ // "*.elb.amazonaws.com" in the PRIVATE section: each load balancer is its own registrable domain.
+ assert_eq!(registrable_domain("my-lb-123.eu-west-1.elb.amazonaws.com"), Some("my-lb-123.eu-west-1.elb.amazonaws.com"));
+}
+
+#[test]
+fn exception_rules() {
+ // The list only has exception rules under .ck and a few Japanese cities: "*.ck" with "!www.ck".
+ assert_eq!(registrable_domain("foo.ck"), None);
+ assert_eq!(registrable_domain("bar.foo.ck"), Some("bar.foo.ck"));
+ assert_eq!(registrable_domain("www.ck"), Some("www.ck"));
+ assert_eq!(registrable_domain("sub.www.ck"), Some("www.ck"));
+}
+
+#[test]
+fn unlisted_suffix_falls_back_to_last_label() {
+ assert_eq!(registrable_domain("nas.home.lan"), Some("home.lan"));
+ assert_eq!(registrable_domain("myserver.local"), Some("myserver.local"));
+ assert_eq!(registrable_domain("plex.myserver.local"), Some("myserver.local"));
+ assert_eq!(registrable_domain("app.localhost"), Some("app.localhost"));
+}
+
+#[test]
+fn trailing_dot_and_empty_labels() {
+ // A fully qualified host has the same registrable domain as without its trailing dot, never the bare TLD.
+ assert_eq!(registrable_domain("bank.com."), Some("bank.com"));
+ assert_eq!(registrable_domain("login.bank.com."), Some("bank.com"));
+ assert_eq!(registrable_domain("victim.vercel.app."), Some("victim.vercel.app"));
+ assert_eq!(registrable_domain("com."), None);
+ assert_eq!(registrable_domain("vercel.app."), None);
+
+ // Empty labels make a host malformed: no registrable domain at all.
+ assert_eq!(registrable_domain(".com"), None);
+ assert_eq!(registrable_domain("a..b.com"), None);
+ assert_eq!(registrable_domain("bank.com.."), None);
+ assert_eq!(registrable_domain(".."), None);
+ assert_eq!(registrable_domain("."), None);
+}
+
+#[test]
+fn lookup_is_case_insensitive_and_keeps_input_casing() {
+ assert_eq!(registrable_domain("Login.Example.CO.UK"), Some("Example.CO.UK"));
+ assert_eq!(registrable_domain("My.Overheid.NL"), Some("Overheid.NL"));
+}
diff --git a/core/rust/src/sqlite_host/mod.rs b/core/rust/src/sqlite_host/mod.rs
index 6a3f3b4d1..9ddf5cbbb 100644
--- a/core/rust/src/sqlite_host/mod.rs
+++ b/core/rust/src/sqlite_host/mod.rs
@@ -263,82 +263,4 @@ pub fn exec(conn: &Connection, statements: &[SqlStatement]) -> VaultResult<()> {
}
#[cfg(test)]
-mod tests {
- use super::*;
- use crate::common::encoding::base64_encode;
-
- fn adversarial() -> Vec<Vec<u8>> {
- let large = crate::common::rng::random_bytes(1024 * 1024);
- vec![vec![], vec![0x00], vec![0xFF], vec![0x00, 0xFF], vec![0xC3, 0x28, 0xA0], vec![0xED, 0xA0, 0x80, 0xF8], b"QUJD".to_vec(), (0u8..=255).collect(), large]
- }
-
- #[test]
- fn blob_cells_round_trip_through_json_and_typed_values() {
- let db = MemoryDatabase::with_schema("CREATE TABLE T (Id INTEGER, Data BLOB);").unwrap();
- for (id, bytes) in adversarial().iter().enumerate() {
- db.exec(&[SqlStatement { sql: "INSERT INTO T (Id, Data) VALUES (?, ?)".to_string(), params: vec![json!(id), inline_bytes(bytes)] }]).unwrap();
- let rows = db.query("SELECT typeof(Data) AS Kind, Data FROM T WHERE Id = ?", &[json!(id)]).unwrap();
- assert_eq!(rows[0]["Kind"], "blob", "{} bytes", bytes.len());
- assert_eq!(rows[0]["Data"], json!({ "__b64": base64_encode(bytes) }), "{} bytes", bytes.len());
- let typed = db.query_values("SELECT Data FROM T WHERE Id = ?", &[SqlValue::Integer(id as i64)]).unwrap();
- assert_eq!(typed.rows[0][0], SqlValue::Blob(bytes.clone()));
- db.execute("UPDATE T SET Data = ? WHERE Id = ?", &[SqlValue::Blob(bytes.clone()), SqlValue::Integer(id as i64)]).unwrap();
- assert_eq!(db.export().map(|exported| MemoryDatabase::from_bytes(&exported).unwrap().query_values("SELECT Data FROM T WHERE Id = ?", &[SqlValue::Integer(id as i64)]).unwrap().rows[0][0].clone()).unwrap(), SqlValue::Blob(bytes.clone()));
- }
- }
-
- #[test]
- fn temporary_storage_stays_in_memory() {
- let db = MemoryDatabase::empty().unwrap();
- assert_eq!(db.query("PRAGMA temp_store", &[]).unwrap()[0]["temp_store"], json!(2));
- let reopened = MemoryDatabase::from_bytes(&db.export().unwrap()).unwrap();
- assert_eq!(reopened.query("PRAGMA temp_store", &[]).unwrap()[0]["temp_store"], json!(2));
- }
-
- #[test]
- fn foreign_keys_are_on_by_default() {
- let db = MemoryDatabase::empty().unwrap();
- assert_eq!(db.query("PRAGMA foreign_keys", &[]).unwrap()[0]["foreign_keys"], json!(1), "the hosts rely on the bundled SQLite default");
- }
-
- #[test]
- fn export_compacts_only_a_fragmented_database_outside_a_transaction() {
- let page_count = |db: &MemoryDatabase| db.query("PRAGMA page_count", &[]).unwrap()[0]["page_count"].as_i64().unwrap();
- let free_pages = |db: &MemoryDatabase| db.query("PRAGMA freelist_count", &[]).unwrap()[0]["freelist_count"].as_i64().unwrap();
- let db = MemoryDatabase::with_schema("CREATE TABLE T (Id INTEGER, Data BLOB);").unwrap();
- for id in 0..200 {
- db.execute("INSERT INTO T (Id, Data) VALUES (?, ?)", &[SqlValue::Integer(id), SqlValue::Blob(vec![7u8; 4096])]).unwrap();
- }
-
- db.execute("DELETE FROM T WHERE Id < 5", &[]).unwrap();
- let slightly_fragmented = free_pages(&db);
- assert!(slightly_fragmented > 0 && slightly_fragmented < VACUUM_MIN_FREE_PAGES);
- db.export().unwrap();
- assert_eq!(free_pages(&db), slightly_fragmented, "a few free pages are not worth a rewrite");
-
- db.execute_batch("BEGIN; DELETE FROM T WHERE Id < 150;").unwrap();
- db.export().unwrap();
- assert!(free_pages(&db) >= VACUUM_MIN_FREE_PAGES, "no VACUUM inside an open transaction");
- db.execute_batch("COMMIT").unwrap();
-
- let before = page_count(&db);
- let exported = db.export().unwrap();
- assert_eq!(free_pages(&db), 0);
- assert!(page_count(&db) < before);
- let reopened = MemoryDatabase::from_bytes(&exported).unwrap();
- assert_eq!(reopened.query("SELECT COUNT(*) AS N FROM T", &[]).unwrap()[0]["N"], json!(50));
- assert_eq!(free_pages(&reopened), 0);
- }
-
- #[test]
- fn invalid_base64_blob_parameter_fails_instead_of_binding_empty_bytes() {
- let db = MemoryDatabase::with_schema("CREATE TABLE T (Data BLOB);").unwrap();
- let statements = [
- SqlStatement { sql: "INSERT INTO T (Data) VALUES (?)".to_string(), params: vec![inline_bytes(&[1, 2, 3])] },
- SqlStatement { sql: "INSERT INTO T (Data) VALUES (?)".to_string(), params: vec![json!({ "__b64": "not base64!" })] },
- ];
- assert!(db.exec(&statements).is_err());
- assert!(db.query("SELECT * FROM T", &[]).unwrap().is_empty(), "the whole batch rolls back");
- assert!(db.query("SELECT * FROM T WHERE Data = ?", &[json!({ "__b64": "A" })]).is_err(), "a truncated parameter is refused, not read as empty");
- }
-}
+mod tests;
diff --git a/core/rust/src/sqlite_host/tests/mod.rs b/core/rust/src/sqlite_host/tests/mod.rs
new file mode 100644
index 000000000..7f7beb0dd
--- /dev/null
+++ b/core/rust/src/sqlite_host/tests/mod.rs
@@ -0,0 +1,77 @@
+use crate::sqlite_host::*;
+use crate::common::encoding::base64_encode;
+
+fn adversarial() -> Vec<Vec<u8>> {
+ let large = crate::common::rng::random_bytes(1024 * 1024);
+ vec![vec![], vec![0x00], vec![0xFF], vec![0x00, 0xFF], vec![0xC3, 0x28, 0xA0], vec![0xED, 0xA0, 0x80, 0xF8], b"QUJD".to_vec(), (0u8..=255).collect(), large]
+}
+
+#[test]
+fn blob_cells_round_trip_through_json_and_typed_values() {
+ let db = MemoryDatabase::with_schema("CREATE TABLE T (Id INTEGER, Data BLOB);").unwrap();
+ for (id, bytes) in adversarial().iter().enumerate() {
+ db.exec(&[SqlStatement { sql: "INSERT INTO T (Id, Data) VALUES (?, ?)".to_string(), params: vec![json!(id), inline_bytes(bytes)] }]).unwrap();
+ let rows = db.query("SELECT typeof(Data) AS Kind, Data FROM T WHERE Id = ?", &[json!(id)]).unwrap();
+ assert_eq!(rows[0]["Kind"], "blob", "{} bytes", bytes.len());
+ assert_eq!(rows[0]["Data"], json!({ "__b64": base64_encode(bytes) }), "{} bytes", bytes.len());
+ let typed = db.query_values("SELECT Data FROM T WHERE Id = ?", &[SqlValue::Integer(id as i64)]).unwrap();
+ assert_eq!(typed.rows[0][0], SqlValue::Blob(bytes.clone()));
+ db.execute("UPDATE T SET Data = ? WHERE Id = ?", &[SqlValue::Blob(bytes.clone()), SqlValue::Integer(id as i64)]).unwrap();
+ assert_eq!(db.export().map(|exported| MemoryDatabase::from_bytes(&exported).unwrap().query_values("SELECT Data FROM T WHERE Id = ?", &[SqlValue::Integer(id as i64)]).unwrap().rows[0][0].clone()).unwrap(), SqlValue::Blob(bytes.clone()));
+ }
+}
+
+#[test]
+fn temporary_storage_stays_in_memory() {
+ let db = MemoryDatabase::empty().unwrap();
+ assert_eq!(db.query("PRAGMA temp_store", &[]).unwrap()[0]["temp_store"], json!(2));
+ let reopened = MemoryDatabase::from_bytes(&db.export().unwrap()).unwrap();
+ assert_eq!(reopened.query("PRAGMA temp_store", &[]).unwrap()[0]["temp_store"], json!(2));
+}
+
+#[test]
+fn foreign_keys_are_on_by_default() {
+ let db = MemoryDatabase::empty().unwrap();
+ assert_eq!(db.query("PRAGMA foreign_keys", &[]).unwrap()[0]["foreign_keys"], json!(1), "the hosts rely on the bundled SQLite default");
+}
+
+#[test]
+fn export_compacts_only_a_fragmented_database_outside_a_transaction() {
+ let page_count = |db: &MemoryDatabase| db.query("PRAGMA page_count", &[]).unwrap()[0]["page_count"].as_i64().unwrap();
+ let free_pages = |db: &MemoryDatabase| db.query("PRAGMA freelist_count", &[]).unwrap()[0]["freelist_count"].as_i64().unwrap();
+ let db = MemoryDatabase::with_schema("CREATE TABLE T (Id INTEGER, Data BLOB);").unwrap();
+ for id in 0..200 {
+ db.execute("INSERT INTO T (Id, Data) VALUES (?, ?)", &[SqlValue::Integer(id), SqlValue::Blob(vec![7u8; 4096])]).unwrap();
+ }
+
+ db.execute("DELETE FROM T WHERE Id < 5", &[]).unwrap();
+ let slightly_fragmented = free_pages(&db);
+ assert!(slightly_fragmented > 0 && slightly_fragmented < VACUUM_MIN_FREE_PAGES);
+ db.export().unwrap();
+ assert_eq!(free_pages(&db), slightly_fragmented, "a few free pages are not worth a rewrite");
+
+ db.execute_batch("BEGIN; DELETE FROM T WHERE Id < 150;").unwrap();
+ db.export().unwrap();
+ assert!(free_pages(&db) >= VACUUM_MIN_FREE_PAGES, "no VACUUM inside an open transaction");
+ db.execute_batch("COMMIT").unwrap();
+
+ let before = page_count(&db);
+ let exported = db.export().unwrap();
+ assert_eq!(free_pages(&db), 0);
+ assert!(page_count(&db) < before);
+ let reopened = MemoryDatabase::from_bytes(&exported).unwrap();
+ assert_eq!(reopened.query("SELECT COUNT(*) AS N FROM T", &[]).unwrap()[0]["N"], json!(50));
+ assert_eq!(free_pages(&reopened), 0);
+}
+
+#[test]
+fn invalid_base64_blob_parameter_fails_instead_of_binding_empty_bytes() {
+ let db = MemoryDatabase::with_schema("CREATE TABLE T (Data BLOB);").unwrap();
+ let statements = [
+ SqlStatement { sql: "INSERT INTO T (Data) VALUES (?)".to_string(), params: vec![inline_bytes(&[1, 2, 3])] },
+ SqlStatement { sql: "INSERT INTO T (Data) VALUES (?)".to_string(), params: vec![json!({ "__b64": "not base64!" })] },
+ ];
+ assert!(db.exec(&statements).is_err());
+ assert!(db.query("SELECT * FROM T", &[]).unwrap().is_empty(), "the whole batch rolls back");
+ assert!(db.query("SELECT * FROM T WHERE Data = ?", &[json!({ "__b64": "A" })]).is_err(), "a truncated parameter is refused, not read as empty");
+}
diff --git a/core/rust/src/vault_codec/hash.rs b/core/rust/src/vault_codec/hash.rs
index 8e7041a44..fb41a8c4d 100644
--- a/core/rust/src/vault_codec/hash.rs
+++ b/core/rust/src/vault_codec/hash.rs
@@ -73,45 +73,3 @@ pub fn salted_blob_hash(bytes: &[u8], manifest_salt: &str) -> VaultResult<String
mac.update(bytes);
Ok(hex_encode_lower(&mac.finalize().into_bytes()))
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use serde_json::json;
-
- #[test]
- fn canonical_sorts_keys_recursively() {
- let v = json!({ "b": 1, "a": { "d": 2, "c": 3 } });
- assert_eq!(canonical_json(&v), r#"{"a":{"c":3,"d":2},"b":1}"#);
- }
-
- #[test]
- fn canonical_keeps_array_order() {
- let v = json!([3, 1, 2]);
- assert_eq!(canonical_json(&v), "[3,1,2]");
- }
-
- #[test]
- fn canonical_matches_js_string_escaping() {
- // Control chars use short forms; quotes/backslashes escaped; non-ascii left raw.
- let v = json!("a\"b\\c\nd\té");
- assert_eq!(canonical_json(&v), "\"a\\\"b\\\\c\\nd\\té\"");
- }
-
- #[test]
- fn derived_uuid_is_stable_and_well_formed() {
- let id = derived_uuid("aliasvault:test");
- // Known-answer vector: derived row ids must match on every platform, so this value must never change.
- assert_eq!(id, "eadc54c6-fb5f-89b0-93f0-18a3af670e1e");
- assert_eq!(id.len(), 36);
- assert_eq!(&id[14..15], "8");
- assert!(matches!(&id[19..20], "8" | "9" | "a" | "b"));
- }
-
- /// Known-answer vector: a changed output re-addresses every stored blob. Never regenerate it.
- #[test]
- fn salted_hash_is_stable() {
- // HMAC-SHA256(key = 00 ff, message = 01 02 03).
- assert_eq!(salted_blob_hash(&[1, 2, 3], "00ff").unwrap(), "4307c7b0faa3e0b307fc467d8f3c3db3cd548860c7555955b2f3f00fe70cbea1");
- }
-}
diff --git a/core/rust/src/vault_codec/tests/hash.rs b/core/rust/src/vault_codec/tests/hash.rs
new file mode 100644
index 000000000..ed6be3790
--- /dev/null
+++ b/core/rust/src/vault_codec/tests/hash.rs
@@ -0,0 +1,38 @@
+use crate::vault_codec::hash::*;
+use serde_json::json;
+
+#[test]
+fn canonical_sorts_keys_recursively() {
+ let v = json!({ "b": 1, "a": { "d": 2, "c": 3 } });
+ assert_eq!(canonical_json(&v), r#"{"a":{"c":3,"d":2},"b":1}"#);
+}
+
+#[test]
+fn canonical_keeps_array_order() {
+ let v = json!([3, 1, 2]);
+ assert_eq!(canonical_json(&v), "[3,1,2]");
+}
+
+#[test]
+fn canonical_matches_js_string_escaping() {
+ // Control chars use short forms; quotes/backslashes escaped; non-ascii left raw.
+ let v = json!("a\"b\\c\nd\té");
+ assert_eq!(canonical_json(&v), "\"a\\\"b\\\\c\\nd\\té\"");
+}
+
+#[test]
+fn derived_uuid_is_stable_and_well_formed() {
+ let id = derived_uuid("aliasvault:test");
+ // Known-answer vector: derived row ids must match on every platform, so this value must never change.
+ assert_eq!(id, "eadc54c6-fb5f-89b0-93f0-18a3af670e1e");
+ assert_eq!(id.len(), 36);
+ assert_eq!(&id[14..15], "8");
+ assert!(matches!(&id[19..20], "8" | "9" | "a" | "b"));
+}
+
+/// Known-answer vector: a changed output re-addresses every stored blob. Never regenerate it.
+#[test]
+fn salted_hash_is_stable() {
+ // HMAC-SHA256(key = 00 ff, message = 01 02 03).
+ assert_eq!(salted_blob_hash(&[1, 2, 3], "00ff").unwrap(), "4307c7b0faa3e0b307fc467d8f3c3db3cd548860c7555955b2f3f00fe70cbea1");
+}
diff --git a/core/rust/src/vault_codec/tests/mod.rs b/core/rust/src/vault_codec/tests/mod.rs
index e72118ab9..550fa32a8 100644
--- a/core/rust/src/vault_codec/tests/mod.rs
+++ b/core/rust/src/vault_codec/tests/mod.rs
@@ -6,6 +6,7 @@ pub(crate) mod support;
mod sharing;
mod compress;
+mod hash;
mod integrity;
mod normalize;
mod row;
@@ -116,7 +117,7 @@ fn a_vault_round_trips_through_manifest_buckets_and_blobs() {
let blobs = &manifest_of(&out).blobs;
assert_eq!(blobs.len(), 2);
- let logo_hash = hash::salted_blob_hash(&favicon, SALT).unwrap();
+ let logo_hash = super::hash::salted_blob_hash(&favicon, SALT).unwrap();
assert_eq!(blobs[&logo_hash].kind, "favicon");
assert_eq!(manifest.tables["Logos"][0]["FileData"], json!({ "__blobRef": logo_hash, "__blobKind": "favicon" }));
let attachments: HashMap<&str, &CodecRecord> = manifest.tables["Attachments"].iter().map(|r| (r["Id"].as_str().unwrap(), r)).collect();
@@ -145,7 +146,7 @@ fn packing_wraps_a_payload_in_a_verified_envelope() {
assert_eq!(serde_json::from_str::<serde_json::Value>(&unpack_payload(&packed).unwrap()).unwrap(), payload);
// Tampered: the original hash over a changed payload.
- let envelope = json!({ "schemaVersion": 1, "contentHash": hash::content_hash(&json!({ "a": 1 })), "payload": { "a": 2 } });
+ let envelope = json!({ "schemaVersion": 1, "contentHash": super::hash::content_hash(&json!({ "a": 1 })), "payload": { "a": 2 } });
assert!(unpack_payload(&super::compress::gzip(envelope.to_string().as_bytes()).unwrap()).is_err());
// A format version this build cannot read is reported as such, before the hash is checked.
@@ -159,7 +160,7 @@ fn salts_and_fingerprints() {
assert_eq!(salt.len(), 64);
assert!(salt.chars().all(|c| c.is_ascii_hexdigit()));
for bad in ["", "not-hex", "abc"] {
- assert!(hash::salted_blob_hash(&[1, 2, 3], bad).is_err(), "a blob hash without a usable salt would break the per-manifest separation");
+ assert!(super::hash::salted_blob_hash(&[1, 2, 3], bad).is_err(), "a blob hash without a usable salt would break the per-manifest separation");
}
// A content fingerprint ignores key order, whitespace and the volatile `canonicalizedAt`, and nothing else.
diff --git a/core/rust/src/vault_model/mod.rs b/core/rust/src/vault_model/mod.rs
index 1671b333d..d8a45f095 100644
--- a/core/rust/src/vault_model/mod.rs
+++ b/core/rust/src/vault_model/mod.rs
@@ -114,22 +114,4 @@ impl TableConfig {
}
#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn every_syncable_table_is_manifest_scoped() {
- for config in SYNCABLE_TABLES {
- assert!(config.manifest_scoped, "{} must be manifest_scoped or it merges across manifests", config.name);
- assert_eq!(config.identity_columns().first(), Some(&MANIFEST_ID_COL), "{} must be addressed by its manifest first", config.name);
- }
- assert!(!SYNCABLE_TABLE_NAMES.contains(&OVERFLOW_TABLE), "the overflow carrier rides inside the manifest, it is not synced as a table of its own");
- }
-
- #[test]
- fn id_keys_ignore_case_and_surrounding_whitespace() {
- assert_eq!(id_key(" 1DD1A3FD-8e0e-4b3f-9a3a-0f1a2b3c4d5e "), "1dd1a3fd-8e0e-4b3f-9a3a-0f1a2b3c4d5e");
- assert!(ids_equal("ABC", "abc "));
- assert!(!ids_equal("abc", "abd"));
- }
-}
+mod tests;
diff --git a/core/rust/src/vault_model/tests/mod.rs b/core/rust/src/vault_model/tests/mod.rs
new file mode 100644
index 000000000..547bb85fc
--- /dev/null
+++ b/core/rust/src/vault_model/tests/mod.rs
@@ -0,0 +1,17 @@
+use crate::vault_model::*;
+
+#[test]
+fn every_syncable_table_is_manifest_scoped() {
+ for config in SYNCABLE_TABLES {
+ assert!(config.manifest_scoped, "{} must be manifest_scoped or it merges across manifests", config.name);
+ assert_eq!(config.identity_columns().first(), Some(&MANIFEST_ID_COL), "{} must be addressed by its manifest first", config.name);
+ }
+ assert!(!SYNCABLE_TABLE_NAMES.contains(&OVERFLOW_TABLE), "the overflow carrier rides inside the manifest, it is not synced as a table of its own");
+}
+
+#[test]
+fn id_keys_ignore_case_and_surrounding_whitespace() {
+ assert_eq!(id_key(" 1DD1A3FD-8e0e-4b3f-9a3a-0f1a2b3c4d5e "), "1dd1a3fd-8e0e-4b3f-9a3a-0f1a2b3c4d5e");
+ assert!(ids_equal("ABC", "abc "));
+ assert!(!ids_equal("abc", "abd"));
+}