skyauth 0.1.0

High-assurance, formally verified OAuth 2.1 and RFC 9449 DPoP authentication engine for the AT Protocol (Bluesky)
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
//! Server-Side Request Forgery (SSRF) boundary filtering and DNS rebinding defense.
//!
//! This module provides strict, production-grade IP address filtering and socket
//! connection pinning to prevent SSRF and DNS rebinding attacks across all outbound
//! identity and discovery network requests in `atproto-oauth`.
//!
//! ## Threat Model & Defense Strategy
//!
//! 1. **Exhaustive IP Range Filtering**: Evaluates every resolved IP against RFC 1918,
//!    loopback (RFC 1122), link-local / cloud metadata (RFC 3927), CGNAT (RFC 6598),
//!    documentation prefixes (RFC 5737, RFC 3849), IPv6 ULA (RFC 4193), multicast,
//!    and unpacked IPv4-mapped IPv6 addresses (RFC 4291).
//! 2. **DNS Rebinding Prevention**: Resolves DNS records ahead-of-time, validates
//!    *all* returned addresses, and pins the HTTP socket connection to a verified IP.
//! 3. **Redirect Depth & Scope Bounding**: Intercepts HTTP redirects (301/302/307/308),
//!    validating target URLs and IPs at each hop with bounded depth.
//! 4. **Response Size Capping**: Limits stream reads to prevent memory exhaustion
//!    or decompression bombs.

use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use url::Url;

use crate::error::SsrfError;

/// Determines if an IPv4 address belongs to a restricted, private, or special-purpose range.
///
/// # Filtered Ranges (RFC Compliance):
/// - `0.0.0.0/8`: Current network / broadcast ("This host") (RFC 1122)
/// - `10.0.0.0/8`: Private-Use (RFC 1918)
/// - `100.64.0.0/10`: Shared Address Space / CGNAT (RFC 6598)
/// - `127.0.0.0/8`: Loopback (RFC 1122)
/// - `169.254.0.0/16`: Link-Local, includes AWS/GCP/Azure metadata `169.254.169.254` (RFC 3927)
/// - `172.16.0.0/12`: Private-Use (RFC 1918: `172.16.0.0` - `172.31.255.255`)
/// - `192.0.0.0/24`: IETF Protocol Assignments (RFC 6890)
/// - `192.0.2.0/24`: Documentation TEST-NET-1 (RFC 5737)
/// - `192.88.99.0/24`: 6to4 Relay Anycast (RFC 7526)
/// - `192.168.0.0/16`: Private-Use (RFC 1918)
/// - `198.18.0.0/15`: Benchmarking (RFC 2544: `198.18.0.0` - `198.19.255.255`)
/// - `198.51.100.0/24`: Documentation TEST-NET-2 (RFC 5737)
/// - `203.0.113.0/24`: Documentation TEST-NET-3 (RFC 5737)
/// - `224.0.0.0/4`: Multicast (RFC 5771)
/// - `240.0.0.0/4`: Reserved / Class E, includes limited broadcast `255.255.255.255` (RFC 1112)
#[must_use]
pub fn is_restricted_ipv4(ip: &Ipv4Addr) -> bool {
    let octets = ip.octets();
    // 0.0.0.0/8
    octets[0] == 0
    // 10.0.0.0/8
    || octets[0] == 10
    // 100.64.0.0/10 (100.64.0.0 - 100.127.255.255)
    || (octets[0] == 100 && (octets[1] & 0xC0) == 64)
    // 127.0.0.0/8
    || octets[0] == 127
    // 169.254.0.0/16 (includes 169.254.169.254 and 169.254.170.2)
    || (octets[0] == 169 && octets[1] == 254)
    // 172.16.0.0/12 (172.16.0.0 - 172.31.255.255)
    || (octets[0] == 172 && (16..=31).contains(&octets[1]))
    // 192.0.0.0/24
    || (octets[0] == 192 && octets[1] == 0 && octets[2] == 0)
    // 192.0.2.0/24
    || (octets[0] == 192 && octets[1] == 0 && octets[2] == 2)
    // 192.88.99.0/24
    || (octets[0] == 192 && octets[1] == 88 && octets[2] == 99)
    // 192.168.0.0/16
    || (octets[0] == 192 && octets[1] == 168)
    // 198.18.0.0/15 (198.18.0.0 - 198.19.255.255)
    || (octets[0] == 198 && (octets[1] == 18 || octets[1] == 19))
    // 198.51.100.0/24
    || (octets[0] == 198 && octets[1] == 51 && octets[2] == 100)
    // 203.0.113.0/24
    || (octets[0] == 203 && octets[1] == 0 && octets[2] == 113)
    // 224.0.0.0/4 (multicast)
    || (octets[0] >= 224 && octets[0] <= 239)
    // 240.0.0.0/4 (reserved / Class E, includes 255.255.255.255)
    || (octets[0] >= 240)
}

/// Determines if an IPv6 address belongs to a restricted, private, or special-purpose range.
///
/// # Filtered Ranges (RFC Compliance):
/// - `::/128`: Unspecified address (RFC 4291)
/// - `::1/128`: Loopback address (RFC 4291)
/// - `::ffff:0:0/96`: IPv4-mapped IPv6 (RFC 4291) — unpacked and re-evaluated via [`is_restricted_ipv4`]
/// - `::ffff:0:0:0/96`: IPv4-translated (RFC 6052)
/// - `64:ff9b::/96`: Well-Known IPv4/IPv6 translation prefix (RFC 6052)
/// - `2001:db8::/32`: Documentation prefix (RFC 3849)
/// - `fc00::/7`: Unique Local Address (ULA) (RFC 4193: `fc00::/8`, `fd00::/8`)
/// - `fe80::/10`: Link-Local Unicast (RFC 4291)
/// - `fec0::/10`: Deprecated Site-Local Unicast (RFC 3879)
/// - `ff00::/8`: Multicast (RFC 4291)
#[must_use]
pub fn is_restricted_ipv6(ip: &Ipv6Addr) -> bool {
    let seg = ip.segments();

    // ::/128
    ip.is_unspecified()
    // ::1/128
    || ip.is_loopback()
    // ::ffff:0:0/96 (IPv4-mapped IPv6)
    || if let Some(mapped) = ip.to_ipv4_mapped() {
        is_restricted_ipv4(&mapped)
    } else {
        false
    }
    // ::ffff:0:0:0/96 (IPv4-translated)
    || (seg[0] == 0 && seg[1] == 0 && seg[2] == 0 && seg[3] == 0 && seg[4] == 0xffff && seg[5] == 0)
    // 64:ff9b::/96
    || (seg[0] == 0x0064 && seg[1] == 0xff9b && seg[2] == 0 && seg[3] == 0 && seg[4] == 0 && seg[5] == 0)
    // 2001:db8::/32
    || (seg[0] == 0x2001 && seg[1] == 0x0db8)
    // fc00::/7
    || ((seg[0] & 0xfe00) == 0xfc00)
    // fe80::/10
    || ((seg[0] & 0xffc0) == 0xfe80)
    // fec0::/10
    || ((seg[0] & 0xffc0) == 0xfec0)
    // ff00::/8
    || ((seg[0] & 0xff00) == 0xff00)
}

/// Determines if an IP address (IPv4 or IPv6) belongs to a restricted/private range.
#[must_use]
pub fn is_restricted_ip(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(v4) => is_restricted_ipv4(&v4),
        IpAddr::V6(v6) => is_restricted_ipv6(&v6),
    }
}

/// Checks if a hostname matches any cloud metadata or internal hostnames.
#[must_use]
pub fn is_blocked_hostname(host: &str) -> bool {
    let lower = host.to_ascii_lowercase();
    let trimmed = lower.trim_end_matches('.');
    trimmed == "metadata.google.internal"
        || trimmed == "instance-data"
        || trimmed == "metadata.internal"
        || trimmed == "169.254.169.254"
        || trimmed.ends_with(".internal")
        || trimmed.ends_with(".local")
        || trimmed.ends_with(".localhost")
}

/// Configurable SSRF boundary filter for outbound HTTP and DNS requests.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct SsrfFilter {
    /// Whether insecure HTTP and loopback addresses (`127.0.0.1`, `::1`, `localhost`)
    /// are permitted for local integration testing. Defaults to `false` (strictly enforced).
    pub allow_insecure_localhost: bool,
}

impl SsrfFilter {
    /// Creates a new SSRF filter.
    #[must_use]
    pub const fn new(allow_insecure_localhost: bool) -> Self {
        Self {
            allow_insecure_localhost,
        }
    }

    /// Checks whether an IP address is restricted under the current filter configuration.
    #[must_use]
    pub fn is_ip_restricted(&self, ip: IpAddr) -> bool {
        if self.allow_insecure_localhost && ip.is_loopback() {
            return false;
        }
        is_restricted_ip(ip)
    }

    /// Validates that an IP address is not restricted.
    ///
    /// # Errors
    /// Returns [`SsrfError::BlockedIp`] if the IP address is in a restricted range.
    pub fn validate_ip(&self, ip: IpAddr) -> Result<(), SsrfError> {
        if self.is_ip_restricted(ip) {
            Err(SsrfError::BlockedIp(ip.to_string()))
        } else {
            Ok(())
        }
    }

    /// Validates a URL against scheme, hostname, and SSRF restrictions.
    ///
    /// # Errors
    /// - Returns [`SsrfError::InsecureScheme`] if the scheme is not `https` (or `http` on localhost in test mode).
    /// - Returns [`SsrfError::BlockedHost`] if the hostname is a blocked internal/cloud metadata name.
    /// - Returns [`SsrfError::BlockedIp`] if the hostname is an IP literal in a restricted range.
    pub fn validate_url(&self, url: &Url) -> Result<(), SsrfError> {
        let scheme = url.scheme();
        let host = url
            .host_str()
            .ok_or_else(|| SsrfError::InvalidUrl("Missing hostname in URL".to_string()))?;

        if scheme != "https" {
            if scheme == "http" {
                if !self.allow_insecure_localhost {
                    return Err(SsrfError::InsecureScheme(url.to_string()));
                }
                let is_local =
                    host == "localhost" || host == "127.0.0.1" || host == "::1" || host == "[::1]";
                if !is_local {
                    return Err(SsrfError::InsecureScheme(url.to_string()));
                }
            } else {
                return Err(SsrfError::InsecureScheme(url.to_string()));
            }
        }

        if !self.allow_insecure_localhost && is_blocked_hostname(host) {
            return Err(SsrfError::BlockedHost(host.to_string()));
        }

        // If host is an IP literal, validate immediately
        if let Ok(ip) = host.parse::<IpAddr>() {
            self.validate_ip(ip)?;
        }

        Ok(())
    }

    /// Resolves the hostname in `url` to IP addresses, validates all resolved IPs against
    /// SSRF rules, and returns a validated [`SocketAddr`] along with the target host header.
    ///
    /// # Security Invariant
    /// If ANY resolved IP address for the hostname is restricted, the entire resolution
    /// fails immediately with [`SsrfError::BlockedIp`], neutralizing multi-homed DNS
    /// rebinding attacks.
    pub async fn resolve_and_pin(&self, url: &Url) -> Result<(SocketAddr, String), SsrfError> {
        self.validate_url(url)?;

        let host = url
            .host_str()
            .ok_or_else(|| SsrfError::InvalidUrl("Missing host in URL".to_string()))?;
        let port = url.port_or_known_default().unwrap_or(443);
        let host_header = if let Some(p) = url.port() {
            format!("{host}:{p}")
        } else {
            host.to_string()
        };

        // If host is an IP literal
        if let Ok(ip) = host.parse::<IpAddr>() {
            self.validate_ip(ip)?;
            return Ok((SocketAddr::new(ip, port), host_header));
        }

        // Asynchronous DNS resolution via tokio
        let lookup_target = format!("{host}:{port}");
        let mut addrs: Vec<SocketAddr> = tokio::net::lookup_host(&lookup_target)
            .await
            .map_err(|e| SsrfError::DnsResolutionFailed(format!("{host}: {e}")))?
            .collect();

        if addrs.is_empty() {
            return Err(SsrfError::DnsResolutionFailed(format!(
                "No DNS records returned for {host}"
            )));
        }

        // Validate EVERY returned address to prevent multi-IP rebinding
        for addr in &addrs {
            self.validate_ip(addr.ip())?;
        }

        // When insecure localhost is permitted (for tests/dev), prefer IPv4 (127.0.0.1)
        // since wiremock and local test servers typically bind to IPv4.
        if self.allow_insecure_localhost {
            addrs.sort_by_key(|a| if a.is_ipv4() { 0 } else { 1 });
        }

        Ok((addrs[0], host_header))
    }

    /// Executes a safe HTTP GET request with SSRF validation, DNS pinning, redirect depth bounding,
    /// and response size limits.
    ///
    /// # Arguments
    /// - `url_str`: The target URL string.
    /// - `max_bytes`: Maximum allowed response body size in bytes.
    pub async fn safe_get(&self, url_str: &str, max_bytes: usize) -> Result<Vec<u8>, SsrfError> {
        let mut current_url = Url::parse(url_str)
            .map_err(|e| SsrfError::InvalidUrl(format!("Failed to parse URL '{url_str}': {e}")))?;

        let mut redirects_remaining = 3usize;

        loop {
            let (pinned_addr, host_header) = self.resolve_and_pin(&current_url).await?;

            let host_only = current_url.host_str().unwrap_or("localhost");
            let mut builder = reqwest::Client::builder()
                .redirect(reqwest::redirect::Policy::none())
                .connect_timeout(std::time::Duration::from_secs(5))
                .timeout(std::time::Duration::from_secs(10));

            if host_only.parse::<IpAddr>().is_err() {
                builder = builder.resolve(host_only, pinned_addr);
            }

            let client = builder
                .build()
                .map_err(|e| SsrfError::Http(e.to_string()))?;

            let resp = client
                .get(current_url.as_str())
                .header(reqwest::header::HOST, host_header)
                .header(reqwest::header::ACCEPT, "application/json, text/plain, */*")
                .send()
                .await
                .map_err(|e| SsrfError::Http(e.to_string()))?;

            let status = resp.status();
            if status.is_redirection() {
                if redirects_remaining == 0 {
                    return Err(SsrfError::TooManyRedirects);
                }
                redirects_remaining = redirects_remaining.saturating_sub(1);

                let location = resp
                    .headers()
                    .get(reqwest::header::LOCATION)
                    .ok_or_else(|| SsrfError::Http("Redirect missing Location header".to_string()))?
                    .to_str()
                    .map_err(|e| SsrfError::Http(format!("Invalid Location header: {e}")))?;

                let next_url = current_url.join(location).map_err(|e| {
                    SsrfError::InvalidUrl(format!("Invalid redirect location '{location}': {e}"))
                })?;

                current_url = next_url;
                continue;
            }

            if !status.is_success() {
                return Err(SsrfError::HttpStatus(
                    status.as_u16(),
                    format!("HTTP status {status} from {current_url}"),
                ));
            }

            let bytes = resp
                .bytes()
                .await
                .map_err(|e| SsrfError::Http(e.to_string()))?;

            if bytes.len() > max_bytes {
                return Err(SsrfError::ResponseTooLarge {
                    max_bytes,
                    actual_bytes: bytes.len(),
                });
            }

            return Ok(bytes.to_vec());
        }
    }

    /// Fetches JSON from a URL with full SSRF safety checks.
    ///
    /// # Arguments
    /// - `url_str`: The target URL string.
    /// - `max_bytes`: Maximum permitted response byte size.
    pub async fn safe_get_json<T: serde::de::DeserializeOwned>(
        &self,
        url_str: &str,
        max_bytes: usize,
    ) -> Result<T, SsrfError> {
        let bytes = self.safe_get(url_str, max_bytes).await?;
        serde_json::from_slice(&bytes).map_err(|e| SsrfError::Json(e.to_string()))
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, missing_docs)]
mod tests {
    use super::*;

    #[test]
    fn test_loopback_ipv4() {
        let filter = SsrfFilter::new(false);
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))));
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(127, 255, 255, 254))));

        let local_filter = SsrfFilter::new(true);
        assert!(!local_filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))));
    }

    #[test]
    fn test_rfc1918_private_ipv4() {
        let filter = SsrfFilter::new(false);
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))));
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(10, 255, 255, 255))));
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(172, 16, 0, 1))));
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(172, 31, 255, 255))));
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))));
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(192, 168, 255, 255))));

        // 172.32.0.1 is public
        assert!(!filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(172, 32, 0, 1))));
    }

    #[test]
    fn test_link_local_and_cloud_metadata() {
        let filter = SsrfFilter::new(false);
        // 169.254.169.254
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(169, 254, 169, 254))));
        // 169.254.170.2
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(169, 254, 170, 2))));
    }

    #[test]
    fn test_cgnat_shared_space() {
        let filter = SsrfFilter::new(false);
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(100, 64, 0, 1))));
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(100, 127, 255, 254))));
        // 100.63.255.255 is not CGNAT
        assert!(!filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(100, 63, 255, 255))));
    }

    #[test]
    fn test_documentation_and_benchmarking_ranges() {
        let filter = SsrfFilter::new(false);
        // TEST-NET-1 192.0.2.1
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1))));
        // TEST-NET-2 198.51.100.1
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1))));
        // TEST-NET-3 203.0.113.1
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 1))));
        // Benchmarking 198.18.0.1
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(198, 18, 0, 1))));
        // 6to4 Relay 192.88.99.1
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(192, 88, 99, 1))));
    }

    #[test]
    fn test_multicast_and_reserved_class_e() {
        let filter = SsrfFilter::new(false);
        // 0.0.0.0
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))));
        // 224.0.0.1 multicast
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(224, 0, 0, 1))));
        // 240.0.0.1 Class E
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(240, 0, 0, 1))));
        // 255.255.255.255
        assert!(filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(255, 255, 255, 255))));
    }

    #[test]
    fn test_ipv6_ranges() {
        let filter = SsrfFilter::new(false);
        // Loopback
        assert!(filter.is_ip_restricted(IpAddr::V6(Ipv6Addr::LOCALHOST)));
        // Unspecified
        assert!(filter.is_ip_restricted(IpAddr::V6(Ipv6Addr::UNSPECIFIED)));
        // ULA fc00::/7
        assert!(filter.is_ip_restricted(IpAddr::V6(Ipv6Addr::new(0xfc00, 0, 0, 0, 0, 0, 0, 1))));
        assert!(filter.is_ip_restricted(IpAddr::V6(Ipv6Addr::new(0xfd12, 0, 0, 0, 0, 0, 0, 1))));
        // Link-Local fe80::/10
        assert!(filter.is_ip_restricted(IpAddr::V6(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1))));
        // Documentation 2001:db8::/32
        assert!(
            filter.is_ip_restricted(IpAddr::V6(Ipv6Addr::new(0x2001, 0x0db8, 0, 0, 0, 0, 0, 1)))
        );
        // Multicast ff02::1
        assert!(filter.is_ip_restricted(IpAddr::V6(Ipv6Addr::new(0xff02, 0, 0, 0, 0, 0, 0, 1))));
    }

    #[test]
    fn test_ipv4_mapped_ipv6() {
        let filter = SsrfFilter::new(false);
        // ::ffff:127.0.0.1
        let mapped_loopback = IpAddr::V6(Ipv4Addr::new(127, 0, 0, 1).to_ipv6_mapped());
        assert!(filter.is_ip_restricted(mapped_loopback));

        // ::ffff:169.254.169.254
        let mapped_metadata = IpAddr::V6(Ipv4Addr::new(169, 254, 169, 254).to_ipv6_mapped());
        assert!(filter.is_ip_restricted(mapped_metadata));

        // ::ffff:10.0.0.1
        let mapped_private = IpAddr::V6(Ipv4Addr::new(10, 0, 0, 1).to_ipv6_mapped());
        assert!(filter.is_ip_restricted(mapped_private));

        // ::ffff:8.8.8.8 (public)
        let mapped_public = IpAddr::V6(Ipv4Addr::new(8, 8, 8, 8).to_ipv6_mapped());
        assert!(!filter.is_ip_restricted(mapped_public));
    }

    #[test]
    fn test_public_ips_allowed() {
        let filter = SsrfFilter::new(false);
        assert!(!filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1))));
        assert!(!filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8))));
        assert!(!filter.is_ip_restricted(IpAddr::V4(Ipv4Addr::new(93, 184, 216, 34))));
        assert!(!filter.is_ip_restricted(IpAddr::V6(Ipv6Addr::new(
            0x2606, 0x4700, 0x4700, 0, 0, 0, 0, 0x1111
        ))));
    }

    #[test]
    fn test_validate_url() {
        let filter = SsrfFilter::new(false);
        assert!(filter
            .validate_url(&Url::parse("https://bsky.social").unwrap())
            .is_ok());
        assert!(filter
            .validate_url(&Url::parse("http://bsky.social").unwrap())
            .is_err());
        assert!(filter
            .validate_url(&Url::parse("ftp://example.com").unwrap())
            .is_err());
        assert!(filter
            .validate_url(&Url::parse("https://127.0.0.1").unwrap())
            .is_err());
        assert!(filter
            .validate_url(&Url::parse("https://169.254.169.254").unwrap())
            .is_err());
        assert!(filter
            .validate_url(&Url::parse("https://metadata.google.internal").unwrap())
            .is_err());

        let local_filter = SsrfFilter::new(true);
        assert!(local_filter
            .validate_url(&Url::parse("http://localhost:8080").unwrap())
            .is_ok());
        assert!(local_filter
            .validate_url(&Url::parse("http://127.0.0.1:8080").unwrap())
            .is_ok());
        assert!(local_filter
            .validate_url(&Url::parse("http://10.0.0.1:8080").unwrap())
            .is_err());
    }
}