Skip to main content

feedparser_rs/util/
ssrf.rs

1//! Server-Side Request Forgery (SSRF) validation shared by the HTTP fetcher
2//! and `xml:base` URL resolution.
3//!
4//! This module is the single source of truth for what counts as a "safe"
5//! destination (public host, no loopback/private/link-local/metadata
6//! address). It has no dependency on the `http` feature so it is always
7//! compiled, letting [`crate::util::base_url`] reuse it even when the
8//! `reqwest`-based HTTP client is disabled.
9
10use std::fmt;
11use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
12use url::Url;
13
14/// Localhost variations that should be blocked.
15const LOCALHOST_VARIANTS: &[&str] = &[
16    "localhost",
17    "localhost.localdomain",
18    "127.0.0.1",
19    "::1",
20    "[::1]",
21];
22
23/// Internal TLDs that should be blocked.
24const INTERNAL_TLDS: &[&str] = &[
25    ".local",
26    ".localhost",
27    ".internal",
28    ".intranet",
29    ".corp",
30    ".home",
31    ".lan",
32];
33
34/// Cloud metadata endpoints that should be blocked.
35const METADATA_DOMAINS: &[&str] = &[
36    "metadata.google.internal",
37    "169.254.169.254",
38    "metadata",
39    "metadata.azure.com",
40];
41
42/// The SSRF rule that matched a rejected address (opaque).
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct SsrfRule {
45    label: &'static str,
46    range: Option<&'static str>,
47}
48
49/// Why SSRF protection rejected a URL, redirect hop or resolved address.
50#[derive(Debug, Clone, PartialEq, Eq)]
51#[non_exhaustive]
52pub enum SsrfRejection {
53    /// Scheme other than `http`/`https`.
54    UnsupportedScheme {
55        /// The rejected scheme.
56        scheme: String,
57    },
58    /// URL without a host.
59    MissingHost,
60    /// Reserved IP literal or resolved address.
61    ReservedIp {
62        /// The rejected address.
63        ip: IpAddr,
64        /// The rule that matched.
65        rule: SsrfRule,
66    },
67    /// Blocked host name.
68    BlockedHost {
69        /// The rejected host.
70        host: String,
71        /// The rule that matched.
72        rule: SsrfRule,
73    },
74    /// DNS resolution produced no public address (possible DNS rebinding).
75    #[cfg(feature = "http")]
76    NoPublicAddress {
77        /// The host that was resolved.
78        host: String,
79    },
80}
81
82impl fmt::Display for SsrfRejection {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        match self {
85            Self::UnsupportedScheme { scheme } => write!(
86                f,
87                "Unsupported URL scheme '{scheme}': only 'http' and 'https' are allowed"
88            ),
89            Self::MissingHost => f.write_str("URL must have a host"),
90            Self::ReservedIp { ip, rule } => {
91                write!(f, "{} not allowed: {ip}", rule.label)?;
92                rule.range.map_or(Ok(()), |range| write!(f, " ({range})"))
93            }
94            Self::BlockedHost { host, rule } => write!(f, "{} not allowed: {host}", rule.label),
95            #[cfg(feature = "http")]
96            Self::NoPublicAddress { host } => write!(
97                f,
98                "DNS resolution for '{host}' returned no public IP addresses \
99                 (possible DNS rebinding attempt)"
100            ),
101        }
102    }
103}
104
105impl std::error::Error for SsrfRejection {}
106
107/// Why [`validate_url`] rejected a URL.
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub enum UrlRejection {
110    /// The string is not a parseable URL.
111    Invalid(url::ParseError),
112    /// The URL parsed but its target is not allowed.
113    Blocked(SsrfRejection),
114}
115
116impl From<SsrfRejection> for UrlRejection {
117    fn from(rejection: SsrfRejection) -> Self {
118        Self::Blocked(rejection)
119    }
120}
121
122fn reserved(
123    ip: impl Into<IpAddr>,
124    label: &'static str,
125    range: Option<&'static str>,
126) -> SsrfRejection {
127    SsrfRejection::ReservedIp {
128        ip: ip.into(),
129        rule: SsrfRule { label, range },
130    }
131}
132
133fn blocked_host(host: &str, label: &'static str) -> SsrfRejection {
134    SsrfRejection::BlockedHost {
135        host: host.to_string(),
136        rule: SsrfRule { label, range: None },
137    }
138}
139
140/// Validates a URL to prevent Server-Side Request Forgery (SSRF) attacks.
141///
142/// This is the canonical check reused by [`crate::http::validation::validate_url`]
143/// (initial request validation and redirect re-validation) and
144/// [`crate::util::base_url::is_safe_url`] (`xml:base` resolution), so both call
145/// sites enforce the same rule set.
146///
147/// # Errors
148///
149/// Returns [`UrlRejection::Invalid`] if the URL is malformed and
150/// [`UrlRejection::Blocked`] if it uses an unsupported scheme or resolves to a
151/// private/loopback/link-local/metadata host.
152pub fn validate_url(url_str: &str) -> Result<Url, UrlRejection> {
153    let url = Url::parse(url_str).map_err(UrlRejection::Invalid)?;
154
155    match url.scheme() {
156        "http" | "https" => {}
157        scheme => {
158            return Err(SsrfRejection::UnsupportedScheme {
159                scheme: scheme.to_string(),
160            }
161            .into());
162        }
163    }
164
165    let host = url.host().ok_or(SsrfRejection::MissingHost)?;
166
167    match host {
168        url::Host::Ipv4(ip) => validate_ipv4(ip)?,
169        url::Host::Ipv6(ip) => validate_ipv6(ip)?,
170        url::Host::Domain(domain) => validate_domain(domain)?,
171    }
172
173    Ok(url)
174}
175
176/// Validates a resolved socket-level IP address.
177///
178/// Used to re-check DNS resolution results at connect time, closing the DNS
179/// rebinding gap where a domain passes [`validate_url`] with a public IP but
180/// is later repointed to a private/internal address.
181///
182/// # Errors
183///
184/// Returns the matching [`SsrfRejection`] if `ip` is a private, loopback,
185/// link-local, or otherwise disallowed address.
186///
187/// Gated behind the `http` feature: it is only consumed by
188/// `http::resolver::SsrfSafeResolver`, and would otherwise be dead code (and
189/// fail a `-D warnings` build) with `http` disabled.
190#[cfg(feature = "http")]
191pub fn validate_ip_addr(ip: IpAddr) -> Result<(), SsrfRejection> {
192    match ip {
193        IpAddr::V4(ip) => validate_ipv4(ip),
194        IpAddr::V6(ip) => validate_ipv6(ip),
195    }
196}
197
198/// Validates an IPv4 address to prevent SSRF.
199fn validate_ipv4(ip: Ipv4Addr) -> Result<(), SsrfRejection> {
200    if ip.is_private() {
201        return Err(reserved(ip, "Private IP address", Some("RFC 1918")));
202    }
203
204    if ip.is_loopback() {
205        return Err(reserved(ip, "Loopback address", None));
206    }
207
208    if ip.is_link_local() {
209        return Err(reserved(ip, "Link-local address", Some("169.254.0.0/16")));
210    }
211
212    if ip.is_broadcast() {
213        return Err(reserved(ip, "Broadcast address", None));
214    }
215
216    if ip.is_documentation() {
217        return Err(reserved(ip, "Documentation IP", Some("RFC 5737")));
218    }
219
220    if ip.is_multicast() {
221        return Err(reserved(ip, "Multicast address", Some("224.0.0.0/4")));
222    }
223
224    validate_ipv4_special_purpose(ip, ip.octets())
225}
226
227/// Validates IANA special-purpose IPv4 ranges not covered by `Ipv4Addr`'s
228/// built-in classifiers, plus cloud-metadata/CGN/this-network/AS112/AMT
229/// blocks. Split out of [`validate_ipv4`] to keep that function close to the
230/// project's function-length target.
231fn validate_ipv4_special_purpose(ip: Ipv4Addr, octets: [u8; 4]) -> Result<(), SsrfRejection> {
232    // Reserved for future use (RFC 1112), excluding 255.255.255.255 which
233    // is already covered by the broadcast check in `validate_ipv4`.
234    if octets[0] >= 240 {
235        return Err(reserved(ip, "Reserved address", Some("240.0.0.0/4")));
236    }
237
238    // IETF Protocol Assignments (RFC 6890)
239    if octets[0] == 192 && octets[1] == 0 && octets[2] == 0 {
240        return Err(reserved(
241            ip,
242            "IETF protocol assignment address",
243            Some("192.0.0.0/24"),
244        ));
245    }
246
247    // 6to4 relay anycast (RFC 3068); deprecated by RFC 7526 but still seen
248    // in older configurations.
249    if octets[0] == 192 && octets[1] == 88 && octets[2] == 99 {
250        return Err(reserved(
251            ip,
252            "6to4 relay anycast address",
253            Some("192.88.99.0/24"),
254        ));
255    }
256
257    // Benchmarking (RFC 2544)
258    if octets[0] == 198 && (octets[1] & 0xFE) == 18 {
259        return Err(reserved(ip, "Benchmarking address", Some("198.18.0.0/15")));
260    }
261
262    // Block cloud metadata endpoints specifically
263    if octets[0] == 169 && octets[1] == 254 && octets[2] == 169 && octets[3] == 254 {
264        return Err(reserved(ip, "AWS metadata endpoint", None));
265    }
266
267    // Block carrier-grade NAT (100.64.0.0/10)
268    if octets[0] == 100 && (octets[1] & 0xC0) == 64 {
269        return Err(reserved(
270            ip,
271            "Carrier-grade NAT address",
272            Some("100.64.0.0/10"),
273        ));
274    }
275
276    // AS112-v4 (RFC 7535)
277    if octets[0] == 192 && octets[1] == 31 && octets[2] == 196 {
278        return Err(reserved(ip, "AS112-v4 address", Some("192.31.196.0/24")));
279    }
280
281    // AMT (RFC 7450)
282    if octets[0] == 192 && octets[1] == 52 && octets[2] == 193 {
283        return Err(reserved(ip, "AMT address", Some("192.52.193.0/24")));
284    }
285
286    // Direct Delegation AS112 Service (RFC 7534)
287    if octets[0] == 192 && octets[1] == 175 && octets[2] == 48 {
288        return Err(reserved(
289            ip,
290            "Direct Delegation AS112 Service address",
291            Some("192.175.48.0/24"),
292        ));
293    }
294
295    // Block 0.0.0.0/8
296    if octets[0] == 0 {
297        return Err(reserved(ip, "0.0.0.0/8 range", None));
298    }
299
300    Ok(())
301}
302
303/// Well-known NAT64 (RFC 6052) prefix `64:ff9b::/96`: the first 6 segments
304/// of any address translated by a standard NAT64/DNS64 gateway.
305const NAT64_PREFIX: [u16; 6] = [0x0064, 0xff9b, 0, 0, 0, 0];
306
307/// The zero prefix shared by deprecated IPv4-compatible addresses
308/// (`::a.b.c.d`), distinct from the IPv4-mapped prefix (`::ffff:a.b.c.d`),
309/// which `Ipv6Addr::to_ipv4_mapped` already covers.
310const IPV4_COMPATIBLE_PREFIX: [u16; 6] = [0, 0, 0, 0, 0, 0];
311
312/// Extracts the IPv4 address embedded in the low 32 bits of a segment array.
313const fn embedded_ipv4(segments: [u16; 8]) -> Ipv4Addr {
314    Ipv4Addr::from_octets([
315        (segments[6] >> 8) as u8,
316        (segments[6] & 0xFF) as u8,
317        (segments[7] >> 8) as u8,
318        (segments[7] & 0xFF) as u8,
319    ])
320}
321
322/// Validates an IPv6 address to prevent SSRF.
323fn validate_ipv6(ip: Ipv6Addr) -> Result<(), SsrfRejection> {
324    // IPv4-mapped addresses (::ffff:0:0/96) embed an IPv4 address that the
325    // OS resolves to on the wire; e.g. `::ffff:127.0.0.1` is loopback but
326    // none of the native IPv6 checks below recognize it as such, so it must
327    // be unwrapped and validated against the IPv4 rules instead.
328    if let Some(mapped) = ip.to_ipv4_mapped() {
329        return validate_ipv4(mapped);
330    }
331
332    let segments = ip.segments();
333
334    // IPv4-compatible addresses (deprecated `::a.b.c.d` form, distinct from
335    // the IPv4-mapped form above) similarly embed a real IPv4 target that
336    // bypasses every native IPv6 check below. `::` and `::1` are excluded
337    // since is_unspecified()/is_loopback() already classify those natively
338    // (and correctly) further down.
339    let low32 = (u32::from(segments[6]) << 16) | u32::from(segments[7]);
340    if segments[..6] == IPV4_COMPATIBLE_PREFIX && low32 > 1 {
341        return validate_ipv4(embedded_ipv4(segments));
342    }
343
344    // NAT64 (RFC 6052): IPv6-only networks with NAT64/DNS64 — standard on
345    // modern cloud IPv6-only subnets — translate this prefix straight
346    // through to the embedded IPv4 address (e.g. `64:ff9b::a9fe:a9fe`
347    // reaches 169.254.169.254 on a real NAT64 gateway), bypassing every
348    // native IPv6 check below just like the mapped/compatible forms.
349    if segments[..6] == NAT64_PREFIX {
350        return validate_ipv4(embedded_ipv4(segments));
351    }
352
353    // Known follow-up gap, deliberately out of scope here: 6to4 addresses
354    // (`2002::/16`, RFC 3056) also embed an IPv4 address in the same way,
355    // but 6to4 relay infrastructure has been widely decommissioned and the
356    // range is not standard on any current cloud network, unlike the three
357    // forms above (mapped/compatible are used by real dual-stack stacks,
358    // NAT64 is standard on modern IPv6-only cloud subnets).
359
360    if ip.is_loopback() {
361        return Err(reserved(ip, "IPv6 loopback address", None));
362    }
363
364    if ip.is_unspecified() {
365        return Err(reserved(ip, "IPv6 unspecified address", None));
366    }
367
368    if ip.is_unicast_link_local() {
369        return Err(reserved(ip, "IPv6 link-local address", Some("fe80::/10")));
370    }
371
372    // Check for Unique Local Addresses (ULA) - fc00::/7
373    if (segments[0] & 0xFE00) == 0xFC00 {
374        return Err(reserved(ip, "IPv6 unique local address", Some("fc00::/7")));
375    }
376
377    validate_ipv6_special_purpose(ip, segments)?;
378    validate_ipv6_special_purpose_extended(ip, segments)?;
379
380    if ip.is_multicast() {
381        return Err(reserved(ip, "IPv6 multicast address", Some("ff00::/8")));
382    }
383
384    Ok(())
385}
386
387/// Validates IANA special-purpose IPv6 ranges not covered by `Ipv6Addr`'s
388/// built-in classifiers: the entire `2001::/23` IETF Protocol Assignments
389/// block (Teredo, `ORCHIDv2`, deprecated ORCHID, DRIP, PCP/TURN/DNS-SD
390/// anycast, AMT, AS112-v6, and any future IANA registration inside the
391/// block — see #474), the separate documentation range, discard-only, the
392/// RFC 9780 dummy prefix, the RFC 8215 NAT64 local-use prefix, and the AS112
393/// service range. Split out of [`validate_ipv6`] to keep that function under
394/// the project's function-length limit.
395fn validate_ipv6_special_purpose(ip: Ipv6Addr, segments: [u16; 8]) -> Result<(), SsrfRejection> {
396    // IETF Protocol Assignments (RFC 6890), 2001::/23: blocks the whole
397    // block in one check rather than allowlisting sub-ranges by omission,
398    // so a future IANA registration inside it can't silently become
399    // reachable (see #474).
400    if segments[0] == 0x2001 && (segments[1] & 0xFE00) == 0 {
401        return Err(reserved(
402            ip,
403            "IPv6 IETF Protocol Assignments address",
404            Some("2001::/23, RFC 6890"),
405        ));
406    }
407
408    // Documentation range (RFC 3849): a separate top-level IANA allocation,
409    // not a sub-range of 2001::/23 above (2001:0db8 falls outside the
410    // block's segments[1] mask).
411    if segments[0] == 0x2001 && segments[1] == 0x0db8 {
412        return Err(reserved(
413            ip,
414            "IPv6 documentation address",
415            Some("2001:db8::/32"),
416        ));
417    }
418
419    // Discard-only prefix (RFC 6666)
420    if segments[0] == 0x0100 && segments[1] == 0 && segments[2] == 0 && segments[3] == 0 {
421        return Err(reserved(ip, "IPv6 discard-only address", Some("100::/64")));
422    }
423
424    // Dummy IPv6 Prefix (RFC 9780), distinct from the discard-only prefix
425    // above — the IANA registry lists these as two independent /64 entries,
426    // not sub-ranges of a common parent block.
427    if segments[0] == 0x0100 && segments[1] == 0 && segments[2] == 0 && segments[3] == 1 {
428        return Err(reserved(
429            ip,
430            "IPv6 dummy prefix address",
431            Some("100:0:0:1::/64"),
432        ));
433    }
434
435    // NAT64 local-use prefix (RFC 8215), distinct from the well-known
436    // 64:ff9b::/96 prefix unwrapped to its embedded IPv4 address in
437    // `validate_ipv6`.
438    if segments[0] == 0x0064 && segments[1] == 0xff9b && segments[2] == 0x0001 {
439        return Err(reserved(
440            ip,
441            "IPv6 NAT64 local-use address",
442            Some("64:ff9b:1::/48"),
443        ));
444    }
445
446    // Direct Delegation AS112 Service (RFC 7534)
447    if segments[0] == 0x2620 && segments[1] == 0x004f && segments[2] == 0x8000 {
448        return Err(reserved(
449            ip,
450            "IPv6 Direct Delegation AS112 Service address",
451            Some("2620:4f:8000::/48"),
452        ));
453    }
454
455    Ok(())
456}
457
458/// Validates additional IANA IPv6 special-purpose ranges not covered by
459/// [`validate_ipv6_special_purpose`]: the RFC 9637 documentation range and
460/// the RFC 9602 Segment Routing range. Kept separate to keep both functions
461/// under the project's function-length limit.
462///
463/// `2002::/16` (6to4) is deliberately not blocked here either; see the
464/// comment in [`validate_ipv6`].
465fn validate_ipv6_special_purpose_extended(
466    ip: Ipv6Addr,
467    segments: [u16; 8],
468) -> Result<(), SsrfRejection> {
469    // Documentation range (RFC 9637)
470    if segments[0] == 0x3fff && (segments[1] & 0xF000) == 0 {
471        return Err(reserved(
472            ip,
473            "IPv6 documentation address",
474            Some("3fff::/20"),
475        ));
476    }
477
478    // Segment Routing (SRv6) SIDs (RFC 9602)
479    if segments[0] == 0x5f00 {
480        return Err(reserved(
481            ip,
482            "IPv6 segment routing address",
483            Some("5f00::/16"),
484        ));
485    }
486
487    Ok(())
488}
489
490/// Validates a domain name to prevent SSRF.
491fn validate_domain(domain: &str) -> Result<(), SsrfRejection> {
492    let domain_lower = domain.to_lowercase();
493    // One or more trailing root-label dots (RFC 1035 §3.1, e.g. `localhost.`,
494    // `localhost..`) resolve identically to the un-dotted form via every
495    // standard stub resolver, so they must be stripped before the blocklist
496    // checks below or they silently break the exact-match and `ends_with`
497    // comparisons.
498    let normalized = domain_lower.trim_end_matches('.');
499
500    if LOCALHOST_VARIANTS.contains(&normalized) {
501        return Err(blocked_host(domain, "Localhost domain"));
502    }
503
504    for tld in INTERNAL_TLDS {
505        if normalized.ends_with(tld) {
506            return Err(blocked_host(domain, "Internal domain TLD"));
507        }
508    }
509
510    if METADATA_DOMAINS.contains(&normalized) {
511        return Err(blocked_host(domain, "Cloud metadata domain"));
512    }
513
514    Ok(())
515}
516
517#[cfg(test)]
518mod tests {
519    use super::*;
520    use std::net::Ipv4Addr;
521
522    #[test]
523    fn test_validate_url_public_ok() {
524        assert!(validate_url("https://example.com/feed.xml").is_ok());
525    }
526
527    #[test]
528    fn test_validate_url_rejects_private_ip() {
529        assert!(validate_url("http://10.0.0.1/").is_err());
530    }
531
532    #[test]
533    #[cfg(feature = "http")]
534    fn test_validate_ip_addr_rejects_loopback() {
535        assert!(validate_ip_addr(IpAddr::V4(Ipv4Addr::LOCALHOST)).is_err());
536    }
537
538    #[test]
539    #[cfg(feature = "http")]
540    fn test_validate_ip_addr_rejects_metadata() {
541        assert!(validate_ip_addr(IpAddr::V4(Ipv4Addr::from_octets([169, 254, 169, 254]))).is_err());
542    }
543
544    #[test]
545    #[cfg(feature = "http")]
546    fn test_validate_ip_addr_accepts_public() {
547        assert!(validate_ip_addr(IpAddr::V4(Ipv4Addr::from_octets([8, 8, 8, 8]))).is_ok());
548    }
549
550    #[test]
551    #[cfg(feature = "http")]
552    fn test_validate_ip_addr_rejects_ipv6_unspecified() {
553        assert!(validate_ip_addr(IpAddr::V6(Ipv6Addr::UNSPECIFIED)).is_err());
554    }
555
556    #[test]
557    fn test_validate_url_rejects_ipv4_mapped_loopback() {
558        // ::ffff:127.0.0.1 is not caught by is_loopback()/is_unicast_link_local()
559        // on Ipv6Addr; it must be unwrapped via to_ipv4_mapped() and re-checked.
560        assert!(validate_url("http://[::ffff:127.0.0.1]/").is_err());
561    }
562
563    #[test]
564    fn test_validate_url_rejects_ipv4_mapped_private() {
565        assert!(validate_url("http://[::ffff:10.0.0.1]/").is_err());
566    }
567
568    #[test]
569    fn test_validate_url_allows_ipv4_mapped_public() {
570        assert!(validate_url("http://[::ffff:8.8.8.8]/").is_ok());
571    }
572
573    #[test]
574    fn test_validate_url_rejects_ipv4_compatible_loopback() {
575        // ::127.0.0.1 (deprecated IPv4-compatible form) is distinct from the
576        // literal ::1 that is_loopback() recognizes.
577        assert!(validate_url("http://[::127.0.0.1]/").is_err());
578    }
579
580    #[test]
581    fn test_validate_url_rejects_ipv4_compatible_metadata() {
582        assert!(validate_url("http://[::169.254.169.254]/").is_err());
583    }
584
585    #[test]
586    fn test_validate_url_allows_ipv4_compatible_public() {
587        assert!(validate_url("http://[::8.8.8.8]/").is_ok());
588    }
589
590    #[test]
591    fn test_validate_url_rejects_nat64_metadata() {
592        // 64:ff9b::a9fe:a9fe is the RFC 6052 NAT64 encoding of 169.254.169.254.
593        assert!(validate_url("http://[64:ff9b::a9fe:a9fe]/").is_err());
594    }
595
596    #[test]
597    fn test_validate_url_rejects_nat64_private() {
598        // 64:ff9b::a00:1 encodes 10.0.0.1.
599        assert!(validate_url("http://[64:ff9b::a00:1]/").is_err());
600    }
601
602    #[test]
603    fn test_validate_url_allows_nat64_public() {
604        // 64:ff9b::808:808 encodes 8.8.8.8.
605        assert!(validate_url("http://[64:ff9b::808:808]/").is_ok());
606    }
607
608    // --- #452: trailing-dot FQDN normalization ---
609
610    #[test]
611    fn test_validate_domain_rejects_trailing_dot_metadata_google() {
612        assert!(validate_domain("metadata.google.internal.").is_err());
613    }
614
615    #[test]
616    fn test_validate_domain_rejects_trailing_dot_localhost() {
617        assert!(validate_domain("localhost.").is_err());
618    }
619
620    #[test]
621    fn test_validate_domain_rejects_trailing_dot_metadata() {
622        assert!(validate_domain("metadata.").is_err());
623    }
624
625    #[test]
626    fn test_validate_domain_rejects_trailing_dot_internal_tld() {
627        assert!(validate_domain("server.local.").is_err());
628        assert!(validate_domain("server.internal.").is_err());
629    }
630
631    #[test]
632    fn test_validate_domain_allows_trailing_dot_public() {
633        assert!(validate_domain("example.com.").is_ok());
634    }
635
636    #[test]
637    fn test_validate_domain_rejects_multiple_trailing_dots() {
638        assert!(validate_domain("localhost..").is_err());
639        assert!(validate_domain("metadata.google.internal..").is_err());
640        assert!(validate_domain("server.internal..").is_err());
641    }
642
643    #[test]
644    fn test_validate_url_rejects_trailing_dot_metadata_google() {
645        assert!(validate_url("http://metadata.google.internal./").is_err());
646    }
647
648    // --- #453: additional IANA special-purpose IPv4 ranges ---
649
650    #[test]
651    fn test_validate_ipv4_rejects_multicast_boundaries() {
652        assert!(validate_ipv4(Ipv4Addr::from_octets([224, 0, 0, 0])).is_err());
653        assert!(validate_ipv4(Ipv4Addr::from_octets([239, 255, 255, 255])).is_err());
654        assert!(validate_ipv4(Ipv4Addr::from_octets([223, 255, 255, 255])).is_ok());
655    }
656
657    #[test]
658    fn test_validate_ipv4_rejects_reserved_boundaries() {
659        assert!(validate_ipv4(Ipv4Addr::from_octets([240, 0, 0, 0])).is_err());
660        assert!(validate_ipv4(Ipv4Addr::from_octets([255, 255, 255, 254])).is_err());
661    }
662
663    #[test]
664    fn test_validate_ipv4_rejects_ietf_protocol_assignment_boundaries() {
665        assert!(validate_ipv4(Ipv4Addr::from_octets([192, 0, 0, 0])).is_err());
666        assert!(validate_ipv4(Ipv4Addr::from_octets([192, 0, 0, 255])).is_err());
667        assert!(validate_ipv4(Ipv4Addr::from_octets([191, 255, 255, 255])).is_ok());
668        assert!(validate_ipv4(Ipv4Addr::from_octets([192, 0, 1, 0])).is_ok());
669    }
670
671    #[test]
672    fn test_validate_ipv4_rejects_6to4_relay_anycast_boundaries() {
673        assert!(validate_ipv4(Ipv4Addr::from_octets([192, 88, 99, 0])).is_err());
674        assert!(validate_ipv4(Ipv4Addr::from_octets([192, 88, 99, 255])).is_err());
675        assert!(validate_ipv4(Ipv4Addr::from_octets([192, 88, 98, 255])).is_ok());
676        assert!(validate_ipv4(Ipv4Addr::from_octets([192, 88, 100, 0])).is_ok());
677    }
678
679    #[test]
680    fn test_validate_ipv4_rejects_benchmarking_boundaries() {
681        assert!(validate_ipv4(Ipv4Addr::from_octets([198, 18, 0, 0])).is_err());
682        assert!(validate_ipv4(Ipv4Addr::from_octets([198, 19, 255, 255])).is_err());
683        assert!(validate_ipv4(Ipv4Addr::from_octets([198, 17, 255, 255])).is_ok());
684        assert!(validate_ipv4(Ipv4Addr::from_octets([198, 20, 0, 0])).is_ok());
685    }
686
687    // --- #453/#474: IANA special-purpose IPv6 ranges ---
688
689    #[test]
690    fn test_validate_ipv6_rejects_ietf_protocol_assignments_2001_23_boundaries() {
691        // #474: the whole 2001::/23 block is blocked in one check, so every
692        // sub-range previously enumerated individually (Teredo, ORCHIDv2,
693        // deprecated ORCHID, DRIP, PCP/TURN/DNS-SD anycast, benchmarking,
694        // AMT, AS112-v6) is covered here instead of by dedicated tests.
695        assert!(validate_ipv6(Ipv6Addr::from_segments([0x2001, 0, 0, 0, 0, 0, 0, 0])).is_err());
696        assert!(
697            validate_ipv6(Ipv6Addr::from_segments([
698                0x2001, 0x01ff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff
699            ]))
700            .is_err()
701        );
702        assert!(
703            validate_ipv6(Ipv6Addr::from_segments([
704                0x2000, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff
705            ]))
706            .is_ok()
707        );
708        assert!(validate_ipv6(Ipv6Addr::from_segments([0x2001, 0x0200, 0, 0, 0, 0, 0, 0])).is_ok());
709        // 2001:1:: itself (no anycast suffix) is unassigned within 2001::/23
710        // and must now be blocked, not just 2001:1::1/2/3 (see #474).
711        assert!(validate_ipv6(Ipv6Addr::from_segments([0x2001, 1, 0, 0, 0, 0, 0, 0])).is_err());
712        assert!(validate_ipv6(Ipv6Addr::from_segments([0x2001, 1, 0, 0, 0, 0, 0, 1])).is_err());
713        assert!(validate_ipv6(Ipv6Addr::from_segments([0x2001, 1, 0, 0, 0, 0, 0, 2])).is_err());
714        assert!(validate_ipv6(Ipv6Addr::from_segments([0x2001, 1, 0, 0, 0, 0, 0, 3])).is_err());
715        assert!(validate_ipv6(Ipv6Addr::from_segments([0x2001, 2, 0, 0, 0, 0, 0, 0])).is_err());
716        assert!(validate_ipv6(Ipv6Addr::from_segments([0x2001, 3, 0, 0, 0, 0, 0, 0])).is_err());
717        assert!(
718            validate_ipv6(Ipv6Addr::from_segments([0x2001, 4, 0x0112, 0, 0, 0, 0, 0])).is_err()
719        );
720        assert!(
721            validate_ipv6(Ipv6Addr::from_segments([0x2001, 0x0010, 0, 0, 0, 0, 0, 0])).is_err()
722        );
723        assert!(
724            validate_ipv6(Ipv6Addr::from_segments([0x2001, 0x0020, 0, 0, 0, 0, 0, 0])).is_err()
725        );
726        assert!(
727            validate_ipv6(Ipv6Addr::from_segments([0x2001, 0x0030, 0, 0, 0, 0, 0, 0])).is_err()
728        );
729    }
730
731    #[test]
732    fn test_validate_ipv6_rejects_documentation_boundaries() {
733        // 2001:db8::/32 is a separate top-level IANA allocation, not a
734        // sub-range of 2001::/23 above (segments[1] = 0x0db8 falls outside
735        // the block's 0x0000-0x01ff mask).
736        assert!(
737            validate_ipv6(Ipv6Addr::from_segments([0x2001, 0x0db8, 0, 0, 0, 0, 0, 0])).is_err()
738        );
739        assert!(
740            validate_ipv6(Ipv6Addr::from_segments([
741                0x2001, 0x0db8, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff
742            ]))
743            .is_err()
744        );
745        assert!(
746            validate_ipv6(Ipv6Addr::from_segments([
747                0x2001, 0x0db7, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff
748            ]))
749            .is_ok()
750        );
751        assert!(validate_ipv6(Ipv6Addr::from_segments([0x2001, 0x0db9, 0, 0, 0, 0, 0, 0])).is_ok());
752    }
753
754    #[test]
755    fn test_validate_ipv6_rejects_discard_only_boundaries() {
756        assert!(validate_ipv6(Ipv6Addr::from_segments([0x0100, 0, 0, 0, 0, 0, 0, 0])).is_err());
757        assert!(
758            validate_ipv6(Ipv6Addr::from_segments([
759                0x0100, 0, 0, 0, 0xffff, 0xffff, 0xffff, 0xffff
760            ]))
761            .is_err()
762        );
763        assert!(
764            validate_ipv6(Ipv6Addr::from_segments([
765                0x00ff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff
766            ]))
767            .is_ok()
768        );
769        // 0x0100:0:0:1::/64 is the RFC 9780 Dummy IPv6 Prefix (see #471),
770        // contiguous with the discard-only prefix above; blocked too.
771        assert!(validate_ipv6(Ipv6Addr::from_segments([0x0100, 0, 0, 1, 0, 0, 0, 0])).is_err());
772        assert!(validate_ipv6(Ipv6Addr::from_segments([0x0100, 0, 0, 2, 0, 0, 0, 0])).is_ok());
773    }
774
775    #[test]
776    fn test_validate_ipv6_rejects_nat64_local_use_boundaries() {
777        assert!(
778            validate_ipv6(Ipv6Addr::from_segments([0x0064, 0xff9b, 1, 0, 0, 0, 0, 0])).is_err()
779        );
780        assert!(
781            validate_ipv6(Ipv6Addr::from_segments([
782                0x0064, 0xff9b, 1, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff
783            ]))
784            .is_err()
785        );
786        assert!(
787            validate_ipv6(Ipv6Addr::from_segments([
788                0x0064, 0xff9b, 0, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff
789            ]))
790            .is_ok()
791        );
792        assert!(validate_ipv6(Ipv6Addr::from_segments([0x0064, 0xff9b, 2, 0, 0, 0, 0, 0])).is_ok());
793    }
794
795    #[test]
796    fn test_validate_ipv6_allows_6to4_deliberately_out_of_scope() {
797        // 2002::/16 (RFC 3056) is deliberately not blocked; see the comment
798        // in `validate_ipv6`. Pinned here as a regression guard.
799        assert!(validate_ipv6(Ipv6Addr::from_segments([0x2002, 0, 0, 0, 0, 0, 0, 0])).is_ok());
800        assert!(
801            validate_ipv6(Ipv6Addr::from_segments([
802                0x2002, 0x0a00, 0x0001, 0, 0, 0, 0, 0
803            ]))
804            .is_ok()
805        );
806    }
807
808    // --- #462: IANA AS112/AMT/PCP anycast sub-ranges ---
809
810    #[test]
811    fn test_validate_ipv4_rejects_as112_v4_boundaries() {
812        assert!(validate_ipv4(Ipv4Addr::from_octets([192, 31, 196, 0])).is_err());
813        assert!(validate_ipv4(Ipv4Addr::from_octets([192, 31, 196, 255])).is_err());
814        assert!(validate_ipv4(Ipv4Addr::from_octets([192, 31, 195, 255])).is_ok());
815        assert!(validate_ipv4(Ipv4Addr::from_octets([192, 31, 197, 0])).is_ok());
816    }
817
818    #[test]
819    fn test_validate_ipv4_rejects_amt_boundaries() {
820        assert!(validate_ipv4(Ipv4Addr::from_octets([192, 52, 193, 0])).is_err());
821        assert!(validate_ipv4(Ipv4Addr::from_octets([192, 52, 193, 255])).is_err());
822        assert!(validate_ipv4(Ipv4Addr::from_octets([192, 52, 192, 255])).is_ok());
823        assert!(validate_ipv4(Ipv4Addr::from_octets([192, 52, 194, 0])).is_ok());
824    }
825
826    #[test]
827    fn test_validate_ipv4_rejects_direct_delegation_as112_boundaries() {
828        assert!(validate_ipv4(Ipv4Addr::from_octets([192, 175, 48, 0])).is_err());
829        assert!(validate_ipv4(Ipv4Addr::from_octets([192, 175, 48, 255])).is_err());
830        assert!(validate_ipv4(Ipv4Addr::from_octets([192, 175, 47, 255])).is_ok());
831        assert!(validate_ipv4(Ipv4Addr::from_octets([192, 175, 49, 0])).is_ok());
832    }
833
834    // --- #471: stale assertions + remaining IANA IPv6 special-purpose gaps ---
835
836    #[test]
837    fn test_validate_ipv6_rejects_dummy_prefix_boundaries() {
838        assert!(validate_ipv6(Ipv6Addr::from_segments([0x0100, 0, 0, 1, 0, 0, 0, 0])).is_err());
839        assert!(
840            validate_ipv6(Ipv6Addr::from_segments([
841                0x0100, 0, 0, 1, 0xffff, 0xffff, 0xffff, 0xffff
842            ]))
843            .is_err()
844        );
845        assert!(validate_ipv6(Ipv6Addr::from_segments([0x0100, 0, 0, 2, 0, 0, 0, 0])).is_ok());
846    }
847
848    #[test]
849    fn test_validate_ipv6_rejects_documentation_3fff_boundaries() {
850        assert!(validate_ipv6(Ipv6Addr::from_segments([0x3fff, 0, 0, 0, 0, 0, 0, 0])).is_err());
851        assert!(
852            validate_ipv6(Ipv6Addr::from_segments([
853                0x3fff, 0x0fff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff
854            ]))
855            .is_err()
856        );
857        assert!(validate_ipv6(Ipv6Addr::from_segments([0x3fff, 0x1000, 0, 0, 0, 0, 0, 0])).is_ok());
858        assert!(validate_ipv6(Ipv6Addr::from_segments([0x3ffe, 0xffff, 0, 0, 0, 0, 0, 0])).is_ok());
859    }
860
861    #[test]
862    fn test_validate_ipv6_rejects_segment_routing_5f00_boundaries() {
863        assert!(validate_ipv6(Ipv6Addr::from_segments([0x5f00, 0, 0, 0, 0, 0, 0, 0])).is_err());
864        assert!(
865            validate_ipv6(Ipv6Addr::from_segments([
866                0x5f00, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff
867            ]))
868            .is_err()
869        );
870        assert!(validate_ipv6(Ipv6Addr::from_segments([0x5eff, 0xffff, 0, 0, 0, 0, 0, 0])).is_ok());
871        assert!(validate_ipv6(Ipv6Addr::from_segments([0x5f01, 0, 0, 0, 0, 0, 0, 0])).is_ok());
872    }
873
874    #[test]
875    fn test_validate_ipv6_rejects_direct_delegation_as112_boundaries() {
876        assert!(
877            validate_ipv6(Ipv6Addr::from_segments([
878                0x2620, 0x004f, 0x8000, 0, 0, 0, 0, 0
879            ]))
880            .is_err()
881        );
882        assert!(
883            validate_ipv6(Ipv6Addr::from_segments([
884                0x2620, 0x004f, 0x8000, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff
885            ]))
886            .is_err()
887        );
888        assert!(
889            validate_ipv6(Ipv6Addr::from_segments([
890                0x2620, 0x004f, 0x7fff, 0, 0, 0, 0, 0
891            ]))
892            .is_ok()
893        );
894        assert!(
895            validate_ipv6(Ipv6Addr::from_segments([
896                0x2620, 0x004f, 0x8001, 0, 0, 0, 0, 0
897            ]))
898            .is_ok()
899        );
900    }
901}