#![forbid(unsafe_code)]
use std::borrow::Cow;
fn normalize(host: &str) -> Option<Cow<'_, str>> {
let h = host.trim().trim_matches('.');
if h.is_empty() || h.len() > 253 {
return None;
}
if !h.is_ascii() {
return None;
}
if h.bytes().any(|b| b.is_ascii_whitespace() || b.is_ascii_control()) {
return None;
}
if is_ip_literal(h) {
if h.bytes().any(|b| b.is_ascii_uppercase()) {
return Some(Cow::Owned(h.to_ascii_lowercase()));
} else {
return Some(Cow::Borrowed(h));
}
}
if h.contains("..") {
return None;
}
if h.contains('*') && !(h == "*" || (h.starts_with("*.") && !h[2..].contains('*'))) {
return None;
}
if h.rsplit('.').next().is_some_and(|tld| !tld.is_empty() && tld.bytes().all(|b| b.is_ascii_digit())) {
return None;
}
if !h.bytes().all(|b| {
b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.' || b == b'*'
}) {
return None;
}
for label in h.split('.') {
if label.is_empty() || label.len() > 63 {
return None;
}
if label.eq_ignore_ascii_case("xn--") {
return None;
}
}
if h.bytes().any(|b| b.is_ascii_uppercase()) {
Some(Cow::Owned(h.to_ascii_lowercase()))
} else {
Some(Cow::Borrowed(h))
}
}
fn is_ip_literal(host: &str) -> bool {
let s = host
.strip_prefix('[')
.and_then(|h| h.strip_suffix(']'))
.unwrap_or(host);
let addr_str = match s.split_once('%') {
Some((ip, _zone)) => ip,
None => s,
};
if addr_str.parse::<std::net::IpAddr>().is_ok() {
return true;
}
let parts: Vec<&str> = addr_str.split('.').collect();
if parts.len() >= 2 && parts.len() <= 4 {
if parts.iter().all(|part| parse_ipv4_octet(part).is_some()) {
return true;
}
}
false
}
fn parse_ipv4_octet(s: &str) -> Option<u8> {
if s.is_empty() {
return None;
}
if let Some(hex) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
u8::from_str_radix(hex, 16).ok()
} else if s.len() > 1 && s.starts_with('0') {
u8::from_str_radix(s, 8)
.ok()
.or_else(|| s.parse::<u8>().ok())
} else {
s.parse::<u8>().ok()
}
}
fn owned_ascii(bytes: &[u8]) -> String {
#[expect(
clippy::expect_used,
reason = "psl returns an ASCII subslice of the ASCII-validated input"
)]
core::str::from_utf8(bytes)
.expect("psl returns an ASCII subslice of the normalized host")
.to_owned()
}
#[must_use]
pub fn registrable_domain(host: &str) -> Option<String> {
let norm = normalize(host)?;
if is_ip_literal(&norm) {
return None;
}
let domain = psl::domain(norm.as_bytes())?;
Some(owned_ascii(domain.as_bytes()))
}
pub use self::registrable_domain as etld_plus_one;
pub use self::registrable_domain as apex_domain;
#[must_use]
pub fn public_suffix(host: &str) -> Option<String> {
let norm = normalize(host)?;
if is_ip_literal(&norm) {
return None;
}
let suffix = psl::suffix(norm.as_bytes())?;
Some(owned_ascii(suffix.as_bytes()))
}
#[must_use]
pub fn is_subdomain_of(child: &str, parent: &str) -> bool {
let (Some(c), Some(p)) = (normalize(child), normalize(parent)) else {
return false;
};
if c == p {
return true;
}
if is_ip_literal(&c) || is_ip_literal(&p) {
return false;
}
c.strip_suffix(p.as_ref())
.is_some_and(|prefix| prefix.ends_with('.'))
}
#[must_use]
pub fn same_registrable_domain(a: &str, b: &str) -> bool {
match (registrable_domain(a), registrable_domain(b)) {
(Some(ra), Some(rb)) => ra == rb,
_ => false,
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use super::*;
use proptest::prelude::*;
use std::borrow::Cow;
#[test]
fn normalize_borrows_already_normalized_host_and_owns_only_when_changed() {
match normalize("a.example.com") {
Some(Cow::Borrowed(s)) => assert_eq!(s, "a.example.com"),
other => panic!("expected borrowed, got {other:?}"),
}
match normalize(" a.example.com. ") {
Some(Cow::Borrowed(s)) => assert_eq!(s, "a.example.com"),
other => panic!("expected borrowed after trim, got {other:?}"),
}
match normalize("A.Example.COM") {
Some(Cow::Owned(s)) => assert_eq!(s, "a.example.com"),
other => panic!("expected owned, got {other:?}"),
}
assert!(normalize("b\u{fc}cher.de").is_none());
assert!(normalize("").is_none());
assert!(normalize(" ").is_none());
}
#[test]
fn resolved_names_are_ascii_without_lossy_replacement() {
let r = registrable_domain("Shop.Example.CO.UK").unwrap();
assert_eq!(r, "example.co.uk");
assert!(r.is_ascii());
assert!(!r.contains('\u{fffd}'));
let s = public_suffix("Shop.Example.CO.UK").unwrap();
assert_eq!(s, "co.uk");
assert!(s.is_ascii());
assert!(!s.contains('\u{fffd}'));
}
#[test]
fn registrable_simple_com() {
assert_eq!(
registrable_domain("example.com").as_deref(),
Some("example.com")
);
assert_eq!(
registrable_domain("a.b.example.com").as_deref(),
Some("example.com")
);
}
#[test]
fn registrable_multilabel_suffix_couk() {
assert_eq!(
registrable_domain("shop.example.co.uk").as_deref(),
Some("example.co.uk")
);
assert_eq!(
registrable_domain("example.com.au").as_deref(),
Some("example.com.au")
);
}
#[test]
fn registrable_normalizes_case_and_trailing_dot() {
assert_eq!(
registrable_domain("WWW.Example.COM.").as_deref(),
Some("example.com")
);
assert_eq!(
registrable_domain("Mail.Example.Co.Uk").as_deref(),
Some("example.co.uk")
);
}
#[test]
fn registrable_none_for_bare_suffix_and_empty() {
assert_eq!(registrable_domain("com"), None);
assert_eq!(registrable_domain("co.uk"), None);
assert_eq!(registrable_domain(""), None);
assert_eq!(registrable_domain(" "), None);
assert_eq!(registrable_domain("."), None);
}
#[test]
fn registrable_tolerates_repeated_trailing_dots() {
assert_eq!(
registrable_domain("example.com..").as_deref(),
Some("example.com")
);
assert_eq!(registrable_domain(".."), None);
}
#[test]
fn subdomain_of_empty_parent_is_false() {
assert!(!is_subdomain_of("example.com", ""));
assert!(!is_subdomain_of("example.com", " "));
assert!(!is_subdomain_of("example.com", "."));
}
#[test]
fn public_suffix_basic() {
assert_eq!(public_suffix("a.example.co.uk").as_deref(), Some("co.uk"));
assert_eq!(public_suffix("example.com").as_deref(), Some("com"));
assert_eq!(public_suffix(""), None);
}
#[test]
fn subdomain_label_boundary() {
assert!(is_subdomain_of("a.example.com", "example.com"));
assert!(is_subdomain_of("x.y.example.com", "example.com"));
assert!(is_subdomain_of("example.com", "example.com"));
assert!(!is_subdomain_of("notexample.com", "example.com"));
assert!(!is_subdomain_of("example.com", "a.example.com"));
assert!(!is_subdomain_of("", "example.com"));
}
#[test]
fn same_registrable() {
assert!(same_registrable_domain(
"mail.example.com",
"www.example.com"
));
assert!(same_registrable_domain(
"a.example.co.uk",
"b.c.example.co.uk"
));
assert!(!same_registrable_domain("example.com", "example.org"));
assert!(!same_registrable_domain("com", "example.com"));
}
#[test]
fn unicode_u_label_is_rejected() {
assert_eq!(registrable_domain("b\u{fc}cher.de"), None);
assert_eq!(public_suffix("b\u{fc}cher.de"), None);
assert!(!is_subdomain_of("www.b\u{fc}cher.de", "b\u{fc}cher.de"));
assert!(!same_registrable_domain("a.b\u{fc}cher.de", "b\u{fc}cher.de"));
}
#[test]
fn punycode_alabel_is_accepted() {
assert_eq!(
registrable_domain("xn--bcher-kva.de").as_deref(),
Some("xn--bcher-kva.de")
);
}
#[test]
fn aliases_match_registrable_domain() {
assert_eq!(
etld_plus_one("www.example.co.uk").as_deref(),
registrable_domain("www.example.co.uk").as_deref()
);
assert_eq!(
apex_domain("mail.example.com").as_deref(),
registrable_domain("mail.example.com").as_deref()
);
}
#[test]
fn is_subdomain_of_is_label_based_not_psl_based() {
assert!(is_subdomain_of("a.co.uk", "co.uk"));
assert!(is_subdomain_of("b.a.co.uk", "co.uk"));
assert!(is_subdomain_of("other.co.uk", "co.uk"));
assert!(is_subdomain_of("co.uk", "co.uk"));
assert!(!is_subdomain_of("baco.uk", "co.uk"));
assert!(!is_subdomain_of("notexample.com", "example.com"));
}
#[test]
fn public_suffix_on_bare_suffix_returns_itself() {
assert_eq!(public_suffix("com").as_deref(), Some("com"));
assert_eq!(public_suffix("co.uk").as_deref(), Some("co.uk"));
}
#[test]
fn registrable_domain_is_subset_of_public_suffix() {
let cases = [
"a.b.example.co.uk",
"mail.example.com",
"xn--bcher-kva.de",
"shop.example.com.au",
];
for host in cases {
let reg = registrable_domain(host);
let suf = public_suffix(host);
assert!(reg.is_some() && suf.is_some(), "{host}");
let r = reg.unwrap();
let s = suf.unwrap();
assert!(r.ends_with(&s), "{r} does not end with {s}");
let reg_suf = public_suffix(&r);
assert_eq!(reg_suf.as_deref(), Some(s.as_str()));
}
}
proptest! {
#[test]
fn registrable_domain_is_subset_of_public_suffix_prop(host in random_ascii_host()) {
if let Some(reg) = registrable_domain(&host) {
let suf = public_suffix(&host);
prop_assert!(suf.is_some());
let s = suf.unwrap();
prop_assert!(reg.ends_with(&s), "{} registrable_domain={} public_suffix={}", host, reg, s);
let reg_suf = public_suffix(®);
prop_assert_eq!(reg_suf.as_deref(), Some(s.as_str()));
}
}
}
fn random_ascii_host() -> impl Strategy<Value = String> {
prop::collection::vec(
"[a-z0-9]{1,10}".prop_map(|s| s.clone()),
1..=5,
)
.prop_map(|labels| labels.join("."))
}
#[test]
fn ipv4_literal_has_no_registrable_domain() {
assert_eq!(registrable_domain("1.2.3.4"), None);
assert_eq!(public_suffix("1.2.3.4"), None);
assert_eq!(registrable_domain("127.0.0.1"), None);
assert_eq!(public_suffix("127.0.0.1"), None);
assert_eq!(registrable_domain("0.0.0.0"), None);
assert_eq!(registrable_domain("255.255.255.255"), None);
assert_eq!(registrable_domain(" 1.2.3.4. "), None);
assert!(!same_registrable_domain("1.2.3.4", "1.2.3.4"));
assert!(!same_registrable_domain("10.0.0.1", "10.0.0.2"));
}
#[test]
fn out_of_range_ipv4_like_name_with_numeric_tld_returns_none() {
assert_eq!(registrable_domain("256.1.1.1"), None);
assert_eq!(public_suffix("256.1.1.1"), None);
}
#[test]
fn ipv6_literal_has_no_registrable_domain() {
assert_eq!(registrable_domain("::1"), None);
assert_eq!(public_suffix("::1"), None);
assert_eq!(registrable_domain("2001:db8::1"), None);
assert_eq!(public_suffix("2001:db8::1"), None);
assert_eq!(registrable_domain("[::1]"), None);
assert_eq!(public_suffix("[::1]"), None);
assert_eq!(registrable_domain("[2001:db8::1]"), None);
assert_eq!(public_suffix("[2001:db8::1]"), None);
assert_eq!(registrable_domain("[::ffff:127.0.0.1]"), None);
assert_eq!(public_suffix("[::ffff:127.0.0.1]"), None);
assert_eq!(registrable_domain("fe80::1%eth0"), None);
assert_eq!(public_suffix("fe80::1%eth0"), None);
assert_eq!(registrable_domain("[fe80::1%eth0]"), None);
assert_eq!(public_suffix("[fe80::1%eth0]"), None);
}
#[test]
fn ip_literals_are_not_subdomains() {
assert!(!is_subdomain_of("1.2.3.4", "3.4"));
assert!(!is_subdomain_of("a.1.2.3.4", "1.2.3.4"));
assert!(!is_subdomain_of("1.2.3.4", "example.com"));
assert!(!is_subdomain_of("example.com", "1.2.3.4"));
assert!(is_subdomain_of("1.2.3.4", "1.2.3.4"));
assert!(is_subdomain_of("[::1]", "[::1]"));
}
#[test]
fn registrable_normalizes_leading_and_trailing_dots() {
assert_eq!(
registrable_domain(".example.com.").as_deref(),
Some("example.com")
);
assert_eq!(
public_suffix(".example.com.").as_deref(),
Some("com")
);
assert!(is_subdomain_of(".a.example.com.", ".example.com."));
}
#[test]
fn hosts_with_control_bytes_or_interior_whitespace_are_rejected() {
for hostile in [
"a\0b.com",
"example.c\0om",
"ex ample.com",
"ex\tample.com",
"exa\nmple.com",
"exa\rmple.com",
"\u{1b}[31mexample.com",
"ex\u{7f}ample.com",
] {
assert_eq!(registrable_domain(hostile), None, "{hostile:?}");
assert_eq!(public_suffix(hostile), None, "{hostile:?}");
assert!(!is_subdomain_of(hostile, "example.com"), "{hostile:?}");
assert!(!same_registrable_domain(hostile, "example.com"), "{hostile:?}");
}
assert_eq!(
registrable_domain(" example.com ").as_deref(),
Some("example.com")
);
}
#[test]
fn underscore_and_hyphen_labels_still_resolve() {
assert_eq!(
registrable_domain("_dmarc.example.com").as_deref(),
Some("example.com")
);
assert_eq!(registrable_domain("-.com").as_deref(), Some("-.com"));
}
proptest! {
#![proptest_config(ProptestConfig {
// Fixed seed: the run is deterministic; a regression replays
// the exact same input stream on every machine.
rng_seed: prop::test_runner::RngSeed::Fixed(0xD155_9A1E_5EED_0001),
..ProptestConfig::default()
})]
#[test]
fn same_registrable_domain_is_symmetric_prop(
a in random_ascii_host(),
b in random_ascii_host(),
) {
prop_assert_eq!(
same_registrable_domain(&a, &b),
same_registrable_domain(&b, &a)
);
}
#[test]
fn registrable_domain_is_idempotent_prop(host in random_ascii_host()) {
if let Some(reg) = registrable_domain(&host) {
let again = registrable_domain(®);
prop_assert_eq!(again.as_deref(), Some(reg.as_str()));
}
}
#[test]
fn resolved_hosts_are_never_control_or_uppercase_prop(host in random_ascii_host()) {
if let Some(reg) = registrable_domain(&host) {
prop_assert!(reg.bytes().all(|b| b.is_ascii() && !b.is_ascii_uppercase()
&& !b.is_ascii_whitespace() && !b.is_ascii_control()));
}
}
}
#[test]
fn psl_dependency_is_pinned() {
let manifest = include_str!("../Cargo.toml");
let psl_line = manifest
.lines()
.find(|l| l.trim().starts_with("psl ") || l.trim().starts_with("psl="))
.expect("Cargo.toml must declare a psl dependency");
assert!(
psl_line.contains("\"=2.1.218\""),
"psl dependency must be pinned exactly to avoid silent PSL snapshot drift: {psl_line}"
);
}
#[test]
fn url_delimiters_ports_and_paths_are_rejected() {
for invalid in [
"example.com:80",
"[::1]:8080",
"http://example.com",
"https://a.b.example.com",
"user@example.com",
"user:pass@example.com",
"a/b.com",
"example.com/path",
"example.com?query=1",
"example.com#fragment",
] {
assert_eq!(registrable_domain(invalid), None, "{invalid:?}");
assert_eq!(public_suffix(invalid), None, "{invalid:?}");
assert!(!is_subdomain_of(invalid, "example.com"), "{invalid:?}");
assert!(!same_registrable_domain(invalid, "example.com"), "{invalid:?}");
}
}
#[test]
fn empty_labels_and_numeric_tlds_are_rejected() {
for invalid in [
"example..com",
"a..example.com",
"a.0.0",
"b.123",
"0.0",
] {
assert_eq!(registrable_domain(invalid), None, "{invalid:?}");
assert_eq!(public_suffix(invalid), None, "{invalid:?}");
}
}
#[test]
fn alternate_ipv4_spellings_are_rejected_as_ip_literals() {
for ip_alt in [
"0177.0.0.1",
"127.0.0.01",
"0x7f.0.0.1",
"127.1",
"10.0.1",
] {
assert_eq!(registrable_domain(ip_alt), None, "{ip_alt:?}");
assert_eq!(public_suffix(ip_alt), None, "{ip_alt:?}");
assert!(!same_registrable_domain(ip_alt, ip_alt), "{ip_alt:?}");
}
}
#[test]
fn malformed_wildcard_positions_are_rejected() {
for malformed in [
"exam*ple.com",
"example.*.com",
"foo*.com",
"*foo.com",
"a.b*.com",
"*.example.*.com",
"sub.example.*.co.uk",
] {
assert_eq!(registrable_domain(malformed), None, "{malformed:?}");
assert_eq!(public_suffix(malformed), None, "{malformed:?}");
assert!(!is_subdomain_of(malformed, "example.com"), "{malformed:?}");
assert!(!same_registrable_domain(malformed, "example.com"), "{malformed:?}");
}
assert_eq!(
registrable_domain("*.example.com").as_deref(),
Some("example.com")
);
assert_eq!(
public_suffix("*.example.com").as_deref(),
Some("com")
);
assert!(is_subdomain_of("*.example.com", "example.com"));
}
#[test]
fn bare_punycode_prefix_label_is_rejected() {
for bare in ["xn--", "XN--", "xn--.com", "a.XN--.com"] {
assert_eq!(registrable_domain(bare), None, "{bare:?}");
assert_eq!(public_suffix(bare), None, "{bare:?}");
}
}
}