dnsname 0.1.4

Canonical registrable-domain (eTLD+1) and public-suffix resolution, backed by the Public Suffix List
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
//! `dnsname`: canonical registrable-domain (eTLD+1) and public-suffix
//! resolution for the Santh fleet.
//!
//! Before this crate, eTLD+1 was computed three different ways across the
//! tree: some crates called the [`psl`] crate directly (gossan, wafrift),
//! while others hand-rolled a "last two labels" heuristic (scald, sear,
//! daylight) that is **wrong** for multi-label public suffixes
//! (`example.co.uk` → the heuristic returns `co.uk`, this crate returns
//! `example.co.uk`). This is the one place that owns the Public Suffix List
//! lookup, so every consumer agrees and the bug is fixed once.
//!
//! # What this is NOT
//!
//! This is the *registrable domain* (eTLD+1), not a host-cache-key
//! normalizer. `scanclient::urlutil::registrable_domain` is a different
//! operation (lowercase host with `www.` stripped, full host retained) and
//! is intentionally left alone (do not route it here).
//!
//! # Inputs
//!
//! All functions take a bare host (`"a.b.example.co.uk"`), not a URL. Strip
//! the scheme/port/path before calling. Input is normalized: surrounding
//! whitespace and surrounding FQDN dots are removed and the host is
//! ASCII-lowercased. Input containing ASCII whitespace or control bytes
//! anywhere is rejected: such strings can never be DNS names. IP literals
//! (IPv4 and IPv6, standard forms including bracketed `[::1]` and
//! zone-scoped `fe80::1%eth0` as parsed by [`std::net::IpAddr`]) have no
//! registrable domain or public suffix and return `None` from
//! [`registrable_domain`] and [`public_suffix`]; note that non-standard IP
//! spellings Rust's parser rejects (hex octets like `0x7f.0.0.1`, collapsed
//! forms like `127.1`) are a known gap and still resolve as ordinary
//! unknown-TLD names. Punycode/IDNA is the caller's responsibility; pass
//! an A-label (`xn--…`) host if the source is internationalized.
//!
//! # Public Suffix List snapshot
//!
//! This crate bundles the PSL snapshot that ships with the pinned `psl`
//! crate version (`2.1.218` at the time of writing). It does not load a
//! runtime Tier-B data file, so the snapshot ages with the dependency.
//! Keep `psl` pinned in `Cargo.toml` and bump it deliberately after
//! verifying the new PSL list; `dnsname::tests::psl_dependency_is_pinned`
//! enforces the exact pin.

#![forbid(unsafe_code)]

use std::borrow::Cow;

/// Normalize a host for PSL lookup: trim whitespace, drop surrounding FQDN
/// dots, ASCII-lowercase. Returns `None` for an empty result, for any
/// non-ASCII input (U-labels; callers must supply punycode A-labels), and
/// for input containing ASCII whitespace or control bytes anywhere -
/// such a string can never be a DNS name, so it is rejected rather than
/// silently resolved to a "registrable domain" carrying the junk byte.
///
/// Zero-copy on the common path: a host that is already trimmed and
/// lowercase ASCII is returned borrowed, and invalid input is rejected
/// *before* any allocation. Only an input that actually contains an ASCII
/// uppercase byte allocates the single lowercased `String`.
fn normalize(host: &str) -> Option<Cow<'_, str>> {
    let h = host.trim().trim_matches('.');
    if h.is_empty() || h.len() > 253 {
        return None;
    }
    // psl::domain expects A-labels (punycode/ASCII). Passing a U-label as raw
    // UTF-8 silently produces wrong results, so reject it here - before any
    // allocation, since ASCII-lowercasing never changes ASCII-ness.
    if !h.is_ascii() {
        return None;
    }
    // Interior whitespace or control bytes (NUL, tab, CR/LF, ANSI escapes,
    // DEL) can never appear in a DNS name. A hostile mirror or malformed
    // target list can smuggle them in; resolving such input would emit
    // "domains" that poison downstream target queues and log output.
    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));
        }
    }
    // Hostnames must not contain empty labels / consecutive dots (e.g. "example..com").
    if h.contains("..") {
        return None;
    }
    // In DNS (RFC 4592 / RFC 6125), wildcard '*' is only valid as a standalone
    // leftmost label (e.g. "*.example.com" or "*"). Reject embedded wildcards
    // (exam*ple.com), non-leftmost wildcards (example.*.com), or multi-wildcards
    // (*.example.*.com) to prevent silent fallback of malformed inputs into bogus domains.
    if h.contains('*') && !(h == "*" || (h.starts_with("*.") && !h[2..].contains('*'))) {
        return None;
    }
    // Top-Level Domains (TLDs) in DNS cannot be purely numeric (e.g. ".0", ".1").
    // Rejects numeric TLD fallbacks (like "a.0.0" -> "0.0" or "256.1.1.1" -> "1.1").
    if h.rsplit('.').next().is_some_and(|tld| !tld.is_empty() && tld.bytes().all(|b| b.is_ascii_digit())) {
        return None;
    }
    // Non-IP hostnames must consist strictly of valid DNS label characters:
    // ASCII alphanumeric, hyphen ('-'), underscore ('_'), dot ('.'), or wildcard ('*').
    // URL delimiters, ports, userinfo, scheme prefixes, and path characters (':', '/', '@', '?', '#', '\\', etc.)
    // are rejected to prevent silent fallback of malformed inputs into bogus domain names.
    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))
    }
}

/// Whether `host` is an IP literal (IPv4 or IPv6) rather than a DNS name.
/// An IP literal has no registrable domain or public suffix: the naive
/// label-based reading groups `1.2.3.4` under the bogus domain `3.4`,
/// which would merge unrelated scan targets that happen to share their
/// last two octets. Supports standard IPv4 and IPv6 forms, including
/// bracketed IPv6 (`[::1]`, `[2001:db8::1]`), zone-scoped IPv6
/// (`fe80::1%eth0`), bracketed IPv4 (`[127.0.0.1]`), and non-standard
/// IPv4 spellings (leading zeros in octets like `0177.0.0.1`, `127.0.0.01`,
/// and hex octets like `0x7f.0.0.1`).
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()
    }
}

/// Convert the ASCII byte subslice `psl` borrowed from our normalized host
/// into an owned `String`. The bytes are a label-boundary subslice of an
/// ASCII-validated input, so they are valid UTF-8; we parse (not lossily
/// replace) and fail loud on the impossible invariant break instead of
/// silently emitting U+FFFD-mangled hostnames.
fn owned_ascii(bytes: &[u8]) -> String {
    // The workspace lint table denies `expect_used` crate-wide. This
    // conversion is a true invariant (`normalize` rejects non-ASCII input
    // before any psl call, and psl returns a subslice of that input), so
    // the `expect` can never fire; `#[expect]` documents that and fails CI
    // if the allowance ever becomes unnecessary.
    #[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()
}

/// The registrable domain (eTLD+1) of `host`, e.g.
/// `a.b.example.co.uk` → `example.co.uk`, `example.com` → `example.com`.
///
/// Returns `None` when `host` has no registrable domain under the Public
/// Suffix List, a bare public suffix (`com`, `co.uk`), an IP literal
/// (`1.2.3.4`, `::1`), an empty/whitespace input, or an unlisted single
/// label.
#[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()))
}

/// Alias for [`registrable_domain`] (the eTLD+1).
pub use self::registrable_domain as etld_plus_one;

/// Alias for [`registrable_domain`] (the apex / organizational domain).
pub use self::registrable_domain as apex_domain;

/// The effective top-level domain (public suffix) of `host`, e.g.
/// `a.example.co.uk` → `co.uk`, `example.com` → `com`.
///
/// Returns `None` for an empty input, an IP literal, or a host whose
/// suffix is not in the Public Suffix List.
#[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()))
}

/// Whether `child` is the same DNS label sequence as, or a DNS subdomain of,
/// `parent`. Both are normalized first. `a.example.com` is a subdomain of
/// `example.com`; `example.com` is "of" itself; `notexample.com` is not a
/// This is intentionally a pure DNS-label check, NOT a Public-Suffix-aware
/// operation: `is_subdomain_of("a.co.uk", "co.uk")` returns `true` because
/// `co.uk` is a parent label sequence, even though `co.uk` is itself a public
/// suffix rather than a registrable domain. Use [`registrable_domain`] when you
/// need the eTLD+1 boundary. IP literals are not DNS names; distinct IP
/// literals or comparisons between an IP and a domain return `false`.
#[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('.'))
}

/// Whether two hosts share the same registrable domain (same organization),
/// e.g. `mail.example.com` and `www.example.com` → `true`. Returns `false`
/// if either host has no registrable domain.
#[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)]
// Test assertions legitimately unwrap/expect/panic on failure; the
// workspace lint table denies those constructs crate-wide, so scope the
// allowance to this module only.
#[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() {
        // Already trimmed lowercase ASCII → zero-copy borrow, no allocation.
        match normalize("a.example.com") {
            Some(Cow::Borrowed(s)) => assert_eq!(s, "a.example.com"),
            other => panic!("expected borrowed, got {other:?}"),
        }
        // Trailing FQDN dot + surrounding whitespace still yields a borrowed
        // slice of the input (trim/trim_end_matches never allocate).
        match normalize("  a.example.com.  ") {
            Some(Cow::Borrowed(s)) => assert_eq!(s, "a.example.com"),
            other => panic!("expected borrowed after trim, got {other:?}"),
        }
        // An ASCII-uppercase byte is the ONLY case that allocates the
        // single lowercased String.
        match normalize("A.Example.COM") {
            Some(Cow::Owned(s)) => assert_eq!(s, "a.example.com"),
            other => panic!("expected owned, got {other:?}"),
        }
        // Non-ASCII is rejected before any allocation.
        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() {
        // psl borrows the ASCII-normalized host, so the owned String is built
        // via from_utf8 (not the from_utf8_lossy replacement scan). Assert the
        // exact value and that no U+FFFD ever leaks in.
        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() {
        // The bug the hand-rolled "last two labels" extractors got wrong.
        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() {
        // Case-folded, trailing FQDN dot dropped, and collapsed to eTLD+1:
        // www.example.com → example.com.
        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);
    }

    /// BOUNDARY: `normalize` drops ALL trailing dots (`trim_end_matches`),
    /// not one. A double FQDN dot is malformed input; the lookup still
    /// resolves to the same registrable domain instead of failing or
    /// returning a suffix-shifted answer. Pins the lenient behavior the
    /// crate docs describe so a future "one dot only" tightening is a
    /// deliberate, test-visible change.
    #[test]
    fn registrable_tolerates_repeated_trailing_dots() {
        assert_eq!(
            registrable_domain("example.com..").as_deref(),
            Some("example.com")
        );
        assert_eq!(registrable_domain(".."), None);
    }

    /// BOUNDARY: an empty parent must not act as a universal suffix.
    /// `is_subdomain_of(child, "")` normalizes the empty parent to `None`
    /// and returns `false`; without that guard a `strip_suffix("")` match
    /// would make every host a "subdomain" of nothing, which would
    /// silently widen any same-site check built on this function.
    #[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"));
        // Must respect the label boundary (not a substring match).
        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() {
        // b\u{fc}cher.de as a U-label must not be silently mis-parsed.
        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() {
        // The A-label form is ASCII and should resolve normally.
        assert_eq!(
            registrable_domain("xn--bcher-kva.de").as_deref(),
            Some("xn--bcher-kva.de")
        );
    }

    #[test]
    fn aliases_match_registrable_domain() {
        // etld_plus_one and apex_domain must be exact aliases for the
        // canonical function so the public surface has one true owner.
        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() {
        // Documented behavior: this is a label check, not a PSL check.
        // `co.uk` is a public suffix, but it is also a parent label sequence,
        // so these all return true.
        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"));
        // A bare public suffix is still "of" itself.
        assert!(is_subdomain_of("co.uk", "co.uk"));
        // Non-matching label sequences are still rejected (not a substring match).
        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() {
        // The public suffix of a bare suffix is the suffix 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() {
        // For any host with a registrable domain, that registrable domain's
        // public suffix must match the host's public suffix and the registrable
        // domain must end with the 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()) {
            // For any well-formed host, if it has a registrable domain then
            // the public suffix is defined and the registrable domain ends
            // with that suffix, and the registrable domain itself resolves to
            // the same public suffix.
            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(&reg);
                prop_assert_eq!(reg_suf.as_deref(), Some(s.as_str()));
            }
        }
    }

    fn random_ascii_host() -> impl Strategy<Value = String> {
        // 1 to 5 labels, each 1-10 ASCII letters/digits/hyphens, joined by dots.
        // Labels are normalized before PSL lookup so case does not matter.
        prop::collection::vec(
            "[a-z0-9]{1,10}".prop_map(|s| s.clone()),
            1..=5,
        )
        .prop_map(|labels| labels.join("."))
    }


    /// ADVERSARIAL: an IPv4 literal is not a DNS name. Before the fix,
    /// `registrable_domain("1.2.3.4")` returned `Some("3.4")` and
    /// `public_suffix("127.0.0.1")` returned `Some("1")` via the PSL
    /// unknown-TLD fallback, which silently grouped every target sharing
    /// its last two octets under one bogus "organization domain".
    #[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);
        // Uppercase/whitespace/FQDN-dot decorated forms still detect the IP.
        assert_eq!(registrable_domain(" 1.2.3.4. "), None);
        // same_registrable_domain inherits the rejection on both sides.
        assert!(!same_registrable_domain("1.2.3.4", "1.2.3.4"));
        assert!(!same_registrable_domain("10.0.0.1", "10.0.0.2"));
    }

    /// ADVERSARIAL: an IPv4-like name with an out-of-range octet (e.g. `256.1.1.1`)
    /// ends with a numeric TLD (`.1`). Numeric TLDs do not exist in DNS;
    /// before the fix, PSL unknown-TLD fallback silently resolved `256.1.1.1` to
    /// bogus domain `1.1`. With silent-fallback hardening, numeric TLDs return `None`.
    #[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);
    }

    /// ADVERSARIAL: an IPv6 literal has no registrable domain either.
    /// `::1` is a single ASCII label, so without the IP check the PSL
    /// fallback reported it as its own public suffix. Supports standard
    /// bracketed (`[::1]`, `[2001:db8::1]`) and zone-scoped (`fe80::1%eth0`)
    /// spellings.
    #[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);

        // Bracketed IPv6 literals (standard Host/URL formatting)
        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);

        // Zone-scoped IPv6 literals (RFC 6874)
        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);
    }

    /// BOUNDARY: IP literals are not DNS names. Distinct IP literals or
    /// comparisons between an IP and a domain must return `false` from
    /// `is_subdomain_of`, preventing naive label grouping like treating `1.2.3.4`
    /// as a subdomain of `3.4`.
    #[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"));

        // Identical IP literal returns true (same host check).
        assert!(is_subdomain_of("1.2.3.4", "1.2.3.4"));
        assert!(is_subdomain_of("[::1]", "[::1]"));
    }

    /// BOUNDARY: `normalize` drops surrounding FQDN dots (both leading and
    /// trailing). `".example.com."` normalizes to `"example.com"`.
    #[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."));
    }
    /// name (NUL, tab, CR/LF, ANSI escape, DEL, interior space) must be
    /// rejected, not resolved. A hostile certificate mirror or target list
    /// can smuggle them in; before the fix `registrable_domain("a\0b.com")`
    /// returned `Some("a\0b.com")`, injecting a NUL into downstream target
    /// queues and logs. Leading/trailing whitespace is still trimmed (that
    /// is well-formed input); only interior junk disqualifies the host.
    #[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:?}");
        }
        // Surrounding whitespace is trimmed, not rejected.
        assert_eq!(
            registrable_domain("  example.com  ").as_deref(),
            Some("example.com")
        );
    }

    /// BOUNDARY: underscores and hyphens are legal in real-world DNS names
    /// (SRV/TXT records, hostnames in the wild), so they must keep
    /// resolving after the control-byte hardening.
    #[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"));
    }

    /// PROPERTY: `same_registrable_domain` is symmetric for every input
    /// pair, and `registrable_domain` is idempotent (resolving a resolved
    /// domain returns the same domain). Both are invariants downstream
    /// grouping logic relies on; fixed-seed proptest keeps the run
    /// deterministic.
    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(&reg);
                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()) {
            // Any host the crate emits must be lowercase ASCII with no
            // whitespace or control bytes; a normalization regression would
            // leak raw hostile bytes into the fleet.
            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() {
        // The PSL snapshot is baked into the `psl` crate at compile time;
        // an unpinned `>=` dependency would silently change the list on
        // `cargo update`. Assert `Cargo.toml` records an exact version.
        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}"
        );
    }
    /// ADVERSARIAL: URL delimiters, ports, userinfo, scheme prefixes, and path characters
    /// (`:`, `/`, `@`, `?`, `#`, `\`, etc.) are rejected during normalization.
    /// Before the fix, PSL unknown-TLD fallback silently returned `Some("example.com:80")`
    /// or `Some("http://example.com")`, poisoning downstream queues with non-bare-host junk.
    #[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:?}");
        }
    }

    /// ADVERSARIAL: consecutive dots (empty labels `..`) and numeric TLDs (`.0`, `.1`) are rejected.
    /// Before the fix, `example..com` returned `Some(".com")` (leading dot) and `a.0.0` returned `Some("0.0")`.
    #[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:?}");
        }
    }

    /// ADVERSARIAL: alternate IPv4 spellings (leading zeros in octets like `0177.0.0.1`,
    /// `127.0.0.01`, hex octets `0x7f.0.0.1`, and shorthand `127.1`) are detected as IP literals
    /// and return `None` rather than silently falling back to bogus domain names like `0.1`.
    #[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:?}");
        }
    }
    /// ADVERSARIAL: wildcard '*' is only permitted as a standalone leftmost label (`*.example.com`).
    /// Embedded wildcards (`exam*ple.com`), non-leftmost wildcards (`example.*.com`), and
    /// multi-wildcards (`*.example.*.com`) are malformed DNS names and must return `None`.
    #[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:?}");
        }
        // Valid wildcard positions resolve correctly.
        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"));
    }

    /// ADVERSARIAL: bare 'xn--' labels without Punycode payload are rejected.
    #[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:?}");
        }
    }
}