crawlrs 0.2.0

crawlrs - Enterprise-grade web scraping and crawling platform built with Rust
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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! Unified SSRF Protection Module
//!
//! This module provides comprehensive SSRF (Server-Side Request Forgery) protection
//! with multiple defense layers:
//!
//! 1. **Static URL Validation**: Fast pre-check for obviously malicious URLs
//! 2. **DNS Resolution Validation**: Prevents DNS rebinding attacks
//! 3. **Redirect Validation**: Validates redirect targets during HTTP requests
//! 4. **TOCTOU Protection**: Time-of-check to time-of-use attack prevention
//!
//! ## Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────┐
//! │                    SSRF Protection Flow                     │
//! ├─────────────────────────────────────────────────────────────┤
//! │                                                             │
//! │  1. Static Validation (is_internal_url)                    │
//! │     - Check scheme (http/https only)                       │
//! │     - Check hostname patterns (localhost, etc.)            │
//! │     - Check IP ranges (private, loopback, etc.)            │
//! │                                                             │
//! │  2. DNS Resolution (validate_url_with_dns)                 │
//! │     - Resolve DNS with caching                             │
//! │     - Validate all resolved IPs                            │
//! │     - Detect DNS rebinding (mixed private/public)          │
//! │                                                             │
//! │  3. Redirect Validation (validate_redirect)                │
//! │     - Validate redirect target URL                         │
//! │     - Prevent redirect to internal addresses               │
//! │     - Track redirect chain depth                           │
//! │                                                             │
//! │  4. Connection Validation (validate_connection_ip)         │
//! │     - Verify actual connection IP matches validated IP     │
//! │     - TOCTOU protection                                     │
//! │                                                             │
//! └─────────────────────────────────────────────────────────────┘
//! ```

mod error;
mod redirect;
mod static_validator;
mod types;

pub use error::SsrfError;
pub use redirect::{RedirectPolicy, RedirectValidator};
pub use static_validator::is_internal_url;
pub use types::{SsrfConfig, SsrfValidationResult, ValidatedUrl};

use std::net::IpAddr;
use tokio::net::lookup_host;
use url::Url;

use crate::infrastructure::dns::DnsCacheService;
use std::sync::Arc;

/// Check if an IP address is a private/reserved address that should be blocked for SSRF protection.
///
/// This function covers:
/// - IPv4 private addresses (RFC 1918): 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16
/// - IPv4 loopback: 127.0.0.0/8
/// - IPv4 link-local: 169.254.0.0/16
/// - IPv4 multicast: 224.0.0.0/4
/// - IPv4 carrier-grade NAT: 100.64.0.0/10
/// - IPv4 broadcast: 0.0.0.0/8, 255.255.255.255
/// - IPv6 loopback: ::1/128
/// - IPv6 unique local (ULA): fc00::/7
/// - IPv6 link-local: fe80::/10
/// - IPv6 multicast: ff00::/8
/// - IPv6 unspecified: ::/128
/// - IPv6 documentation: 2001:db8::/32
pub fn is_private_ip(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(ipv4) => is_private_ipv4(ipv4),
        IpAddr::V6(ipv6) => is_private_ipv6(ipv6),
    }
}

/// 判定 IPv4 地址是否为私有/保留地址
///
/// (`is_private_ip` 的 V4 分支,逻辑与注释原样保留)
fn is_private_ipv4(ipv4: std::net::Ipv4Addr) -> bool {
    let octets = ipv4.octets();
    // 10.0.0.0/8
    octets[0] == 10
    // 172.16.0.0/12
    || (octets[0] == 172 && (16..=31).contains(&octets[1]))
    // 192.168.0.0/16
    || (octets[0] == 192 && octets[1] == 168)
    // Loopback 127.0.0.0/8
    || ipv4.is_loopback()
    // Link-local 169.254.0.0/16
    || ipv4.is_link_local()
    // Multicast 224.0.0.0/4
    || (224..=239).contains(&octets[0])
    // Carrier-Grade NAT 100.64.0.0/10
    || (octets[0] == 100 && (64..=127).contains(&octets[1]))
    // Broadcast 0.0.0.0/8
    || octets[0] == 0
    // 255.255.255.255
    || (octets[0] == 255 && octets[1] == 255 && octets[2] == 255 && octets[3] == 255)
}

/// 判定 IPv6 地址是否为私有/保留地址
///
/// (`is_private_ip` 的 V6 分支,逻辑与注释原样保留)
fn is_private_ipv6(ipv6: std::net::Ipv6Addr) -> bool {
    let segs = ipv6.segments();
    ipv6.is_loopback()
        || (segs[0] & 0xfe00) == 0xfc00 // fc00::/7 ULA
        || (segs[0] & 0xffc0) == 0xfe80 // fe80::/10 link-local
        || (segs[0] & 0xff00) == 0xff00 // ff00::/8 multicast
        || (segs[0] & 0xffc0) == 0xfec0 // fec0::/10 deprecated site-local
        || segs == [0, 0, 0, 0, 0, 0, 0, 0] // /128 unspecified
        || (segs[0] == 0x2001 && segs[1] == 0x0db8) // 2001:db8::/32 documentation
        // IPv4-mapped IPv6 (ffff:x.x.x.x) - use std lib (Rust 1.65+)
        || ipv6
            .to_ipv4_mapped()
            .map(is_private_ipv4)
            .unwrap_or(false)
        // IPv4-compatible IPv6 (x.x.x.x, RFC 4291 deprecated) - bypass risk
        // to_ipv4_mapped does NOT cover this form; must check explicitly.
        // Exclude ::/128 (unspecified) and ::1 (loopback) - already handled above.
        || (segs[0..6] == [0, 0, 0, 0, 0, 0]
            && (segs[6] != 0 || segs[7] != 0)
            && {
                let ipv4 = std::net::Ipv4Addr::new(
                    (segs[6] >> 8) as u8,
                    (segs[6] & 0xff) as u8,
                    (segs[7] >> 8) as u8,
                    (segs[7] & 0xff) as u8,
                );
                is_private_ipv4(ipv4)
            })
}

/// List of blocked hostnames that should never be accessed via SSRF.
///
/// This includes:
/// - Localhost variants
/// - Link-local addresses as strings
/// - Cloud provider metadata endpoints
pub fn get_blocked_hostnames() -> &'static [&'static str] {
    &[
        // Localhost variants
        "localhost",
        "localhost.localdomain",
        "ip6-localhost",
        "ip6-loopback",
        // Link-local addresses
        "0.0.0.0",
        "::1",
        "::",
        // Cloud provider metadata endpoints
        "169.254.169.254",             // AWS, Azure, GCP
        "metadata.google.internal",    // GCP
        "metadata.azure.com",          // Azure
        "metadata.msftidentity.com",   // Azure
        "metadata.nova.canonical.com", // OpenStack
        "metadata.packet.csi.com",     // Packet
    ]
}

/// Check if a hostname is in the blocked list.
///
/// This function checks exact hostname matches only. For IP address checks,
/// use `is_private_ip()` instead.
pub fn is_blocked_hostname(host: &str) -> bool {
    let host_lower = host.to_lowercase();
    let blocked = get_blocked_hostnames();

    if blocked.iter().any(|&b| host_lower == b) {
        return true;
    }

    // IPv6 host from url::Url::host_str comes wrapped in brackets (e.g. "[::1]").
    // Strip brackets before parsing to IpAddr, otherwise parse fails and IPv6
    // IP checks are silently skipped (SSRF bypass vector).
    let host_for_parse = host_lower
        .strip_prefix('[')
        .and_then(|h| h.strip_suffix(']'))
        .unwrap_or(&host_lower);

    if let Ok(ip) = host_for_parse.parse::<std::net::IpAddr>() {
        return is_private_ip(ip);
    }

    false
}

/// Direct DNS resolution helper (no cache). Used when oxcache-cache feature is disabled
/// or when SsrfValidator is constructed without a DNS cache.
async fn resolve_dns_direct(hostname: &str, port: u16) -> Result<Vec<IpAddr>, SsrfError> {
    let addr_str = format!("{}:{}", hostname, port);
    let addrs: Vec<IpAddr> = lookup_host(&addr_str)
        .await
        .map_err(|e| SsrfError::DnsResolutionFailed {
            hostname: hostname.to_string(),
            reason: e.to_string(),
        })?
        .map(|socket_addr| socket_addr.ip())
        .collect();
    Ok(addrs)
}

/// Unified SSRF protection validator with DNS caching support.
///
/// This struct provides the main entry point for SSRF protection.
/// It combines static validation, DNS resolution, and redirect validation.
#[derive(Clone, Default)]
pub struct SsrfValidator {
    /// DNS cache for resolution results
    dns_cache: Option<Arc<DnsCacheService>>,
    /// Configuration options
    config: SsrfConfig,
}

impl SsrfValidator {
    /// Create a new SSRF validator without DNS caching.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a new SSRF validator with DNS caching support.
    pub fn with_dns_cache(dns_cache: Arc<DnsCacheService>) -> Self {
        Self {
            dns_cache: Some(dns_cache),
            config: SsrfConfig::default(),
        }
    }

    /// Create a new SSRF validator with custom configuration.
    pub fn with_config(config: SsrfConfig) -> Self {
        Self {
            dns_cache: None,
            config,
        }
    }

    /// Create a new SSRF validator with DNS cache and custom configuration.
    pub fn with_dns_cache_and_config(dns_cache: Arc<DnsCacheService>, config: SsrfConfig) -> Self {
        Self {
            dns_cache: Some(dns_cache),
            config,
        }
    }

    /// Perform full SSRF validation on a URL.
    ///
    /// This method performs:
    /// 1. Static URL validation (scheme, hostname patterns)
    /// 2. DNS resolution with IP validation
    /// 3. DNS rebinding detection
    ///
    /// # Arguments
    ///
    /// * `url_str` - The URL string to validate
    ///
    /// # Returns
    ///
    /// * `Ok(ValidatedUrl)` - The validated URL with resolved IPs
    /// * `Err(SsrfError)` - Validation failed
    ///
    /// # Example
    ///
    /// ```ignore
    /// use crate::infrastructure::security::ssrf::SsrfValidator;
    ///
    /// let validator = SsrfValidator::new;
    /// let result = validator.validate("https://example.com").await;
    /// assert!(result.is_ok);
    /// ```
    pub async fn validate(&self, url_str: &str) -> Result<ValidatedUrl, SsrfError> {
        // Step 1: URL length check
        if url_str.len() > self.config.max_url_length {
            return Err(SsrfError::UrlTooLong {
                max: self.config.max_url_length,
                actual: url_str.len(),
            });
        }

        // Step 2: Parse URL
        let url = Url::parse(url_str).map_err(|e| SsrfError::InvalidUrl {
            url: url_str.to_string(),
            reason: e.to_string(),
        })?;

        // Step 3: Scheme validation
        match url.scheme() {
            "http" | "https" => {}
            scheme => {
                return Err(SsrfError::InvalidScheme {
                    scheme: scheme.to_string(),
                });
            }
        }

        // Step 4: Extract host
        let host = url.host_str().ok_or_else(|| SsrfError::MissingHost {
            url: url_str.to_string(),
        })?;

        // 开关旁路(仅开发/测试):跳过主机黑名单与内网 IP 判定,仍解析 DNS
        // 以维持 ValidatedUrl / 引擎 DNS-pin 的形状。必须在 Step 5 主机黑名单
        // 之前——localhost 恰是本开关要放行的首要目标。
        if ssrf_protection_disabled() {
            let port = url.port_or_known_default().unwrap_or(80);
            let resolved_ips = self.resolve_host_permissive(host, port).await?;
            return Ok(ValidatedUrl {
                url: url_str.to_string(),
                parsed_url: url,
                resolved_ips,
                port,
            });
        }

        // Step 5: Static hostname check (before DNS resolution)
        if is_blocked_hostname(host) {
            return Err(SsrfError::BlockedHostname {
                hostname: host.to_string(),
            });
        }

        // Step 6: DNS resolution and IP validation
        let port = url.port_or_known_default().unwrap_or(80);
        let resolved_ips = self.resolve_and_validate_ips(host, port).await?;

        // Step 7: Create validated URL
        Ok(ValidatedUrl {
            url: url_str.to_string(),
            parsed_url: url,
            resolved_ips,
            port,
        })
    }

    /// 仅解析 DNS 不做任何内网判定(`ssrf_protection_disabled` 旁路专用)。
    async fn resolve_host_permissive(
        &self,
        hostname: &str,
        port: u16,
    ) -> Result<Vec<IpAddr>, SsrfError> {
        self.resolve_hostname_ips(hostname, port).await
    }

    /// Resolve DNS and validate all returned IP addresses.
    ///
    /// This method implements DNS rebinding protection by:
    /// 1. Resolving all IP addresses for the hostname
    /// 2. Checking for mixed private/public IPs (DNS rebinding signature)
    /// 3. Rejecting if any private IP is found
    async fn resolve_and_validate_ips(
        &self,
        hostname: &str,
        port: u16,
    ) -> Result<Vec<IpAddr>, SsrfError> {
        // Use DNS cache if available (requires oxcache-cache feature)
        let ips = self.resolve_hostname_ips(hostname, port).await?;

        // Check if any IPs were resolved
        if ips.is_empty() {
            return Err(SsrfError::NoIpResolved {
                hostname: hostname.to_string(),
            });
        }

        check_resolved_ips_not_internal(hostname, &ips)?;

        // Log if multiple IPs resolved (potential DNS round-robin)
        if ips.len() > 1 {
            log::debug!(
                "DNS resolution returned {} IPs for hostname {}",
                ips.len(),
                hostname
            );
        }

        Ok(ips)
    }

    /// 仅解析 DNS(缓存可用走缓存,否则直连解析),不做任何内网判定
    async fn resolve_hostname_ips(
        &self,
        hostname: &str,
        port: u16,
    ) -> Result<Vec<IpAddr>, SsrfError> {
        if let Some(cache) = &self.dns_cache {
            cache
                .lookup_host(hostname, port)
                .await
                .map_err(|e| SsrfError::DnsResolutionFailed {
                    hostname: hostname.to_string(),
                    reason: e.to_string(),
                })
        } else {
            resolve_dns_direct(hostname, port).await
        }
    }

    /// Validate a redirect URL during HTTP request.
    ///
    /// This method should be called for each redirect to ensure
    /// the redirect target is not an internal address.
    pub fn validate_redirect(&self, redirect_url: &str) -> Result<(), SsrfError> {
        // Quick static check for redirect URL
        if is_internal_url(redirect_url) {
            return Err(SsrfError::RedirectToInternal {
                url: redirect_url.to_string(),
            });
        }
        Ok(())
    }

    /// Validate that the actual connection IP matches the validated IP.
    ///
    /// This provides TOCTOU (Time-of-check to time-of-use) protection
    /// by verifying the IP address at connection time.
    pub fn validate_connection_ip(&self, ip: IpAddr) -> Result<(), SsrfError> {
        if is_private_ip(ip) {
            return Err(SsrfError::PrivateIpAccess { ip: ip.to_string() });
        }
        Ok(())
    }

    /// Quick synchronous check if a URL is internal (without DNS resolution).
    ///
    /// Use this for fast pre-filtering before async validation.
    pub fn is_internal_url_sync(&self, url_str: &str) -> bool {
        is_internal_url(url_str)
    }
}

/// Convenience function for quick URL validation without DNS caching.
///
/// This function performs full SSRF validation including DNS resolution.
/// For repeated validations, use `SsrfValidator::with_dns_cache()` instead.
pub async fn validate_url(url_str: &str) -> Result<ValidatedUrl, SsrfError> {
    let validator = SsrfValidator::new();
    validator.validate(url_str).await
}

/// SSRF 防护禁用开关(`CRAWLRS_DISABLE_SSRF_PROTECTION`)。
///
/// 仅供开发/测试环境调试本机依赖(如本机 LLM 端点)使用;置位后
/// [`SsrfValidator::validate`] 跳过主机黑名单与内网 IP 判定,重定向策略
/// 同步降级为普通跟随(`utils::http_client`)。进程内只告警一次;
/// 非 test/development 环境的启动期显著告警由 config_validator 负责。
pub(crate) fn ssrf_protection_disabled() -> bool {
    // 单元测试进程内多个用例会并发 set/remove 该环境变量;缓存会让
    // 先跑到的值污染后续用例(测试隔离缺陷)。test 构建每次读取,
    // 生产路径仍用 OnceLock 只读一次环境。
    #[cfg(test)]
    {
        // 与 config_validator 的 env 改写测试共用同一把锁,避免读取到
        // 其他用例临时 set_var 的瞬时值。
        let _guard = crate::common::test_support::ENV_MUTEX
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        std::env::var(crate::common::constants::env_vars::DISABLE_SSRF_PROTECTION).is_ok()
    }
    #[cfg(not(test))]
    {
        use std::sync::OnceLock;
        static DISABLED: OnceLock<bool> = OnceLock::new();
        *DISABLED.get_or_init(|| {
            let disabled =
                std::env::var(crate::common::constants::env_vars::DISABLE_SSRF_PROTECTION).is_ok();
            if disabled {
                log::warn!(
                    "{}",
                    crate::i18n::tr_log_args(
                        "ssrf-protection-disabled",
                        &[(
                            "env",
                            crate::common::constants::env_vars::DISABLE_SSRF_PROTECTION.to_string(),
                        )],
                    )
                );
            }
            disabled
        })
    }
}

/// DNS rebinding detection + private-IP rejection:
/// 1. mixed private/public IPs → `DnsRebindingDetected`(rebinding signature)
/// 2. any private IP → `PrivateIpAccess`
fn check_resolved_ips_not_internal(hostname: &str, ips: &[IpAddr]) -> Result<(), SsrfError> {
    // DNS rebinding detection: check for mixed private/public IPs
    let has_private = ips.iter().any(|ip| is_private_ip(*ip));
    let has_public = ips.iter().any(|ip| !is_private_ip(*ip));

    if has_private && has_public {
        log::warn!(
            "DNS rebinding attack detected: hostname {} resolved to mixed private/public IPs",
            hostname
        );
        return Err(SsrfError::DnsRebindingDetected {
            hostname: hostname.to_string(),
            ips: ips.iter().map(|ip| ip.to_string()).collect(),
        });
    }

    // Check all IPs are not private
    for ip in ips {
        if is_private_ip(*ip) {
            return Err(SsrfError::PrivateIpAccess { ip: ip.to_string() });
        }
    }

    Ok(())
}

/// Validate a domain against a blacklist.
///
/// # Arguments
///
/// * `url_str` - The URL string to validate
/// * `blacklist` - List of blocked domains
///
/// # Returns
///
/// * `Ok()` - Domain is not in blacklist
/// * `Err(SsrfError)` - Domain is in blacklist
pub fn validate_domain_blacklist(url_str: &str, blacklist: &[String]) -> Result<(), SsrfError> {
    let url = Url::parse(url_str).map_err(|e| SsrfError::InvalidUrl {
        url: url_str.to_string(),
        reason: e.to_string(),
    })?;

    let host = url.host_str().ok_or_else(|| SsrfError::MissingHost {
        url: url_str.to_string(),
    })?;

    for domain in blacklist {
        if host == domain || host.ends_with(&format!(".{}", domain)) {
            return Err(SsrfError::BlockedHostname {
                hostname: host.to_string(),
            });
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::types::MAX_URL_LENGTH;
    use super::*;

    #[test]
    fn test_is_internal_url_localhost() {
        assert!(is_internal_url("http://localhost"));
        assert!(is_internal_url("http://localhost:8080"));
        assert!(is_internal_url("http://127.0.0.1"));
        assert!(is_internal_url("http://127.0.0.1:3000"));
    }

    #[test]
    fn test_is_internal_url_private_ipv4() {
        // 10.0.0.0/8
        assert!(is_internal_url("http://10.0.0.1"));
        assert!(is_internal_url("http://10.255.255.255"));

        // 172.16.0.0/12
        assert!(is_internal_url("http://172.16.0.1"));
        assert!(is_internal_url("http://172.31.255.255"));

        // 192.168.0.0/16
        assert!(is_internal_url("http://192.168.0.1"));
        assert!(is_internal_url("http://192.168.255.255"));

        // Not in private range
        assert!(!is_internal_url("http://172.15.0.1"));
        assert!(!is_internal_url("http://172.32.0.1"));
    }

    #[test]
    fn test_is_internal_url_link_local() {
        assert!(is_internal_url("http://169.254.0.1"));
        assert!(is_internal_url("http://169.254.255.255"));
    }

    #[test]
    fn test_is_internal_url_ipv6() {
        // Loopback
        assert!(is_internal_url("http://[::1]"));
        assert!(is_internal_url("http://[::1]:8080"));

        // Link-local
        assert!(is_internal_url("http://[fe80::1]"));
        assert!(is_internal_url("http://[febf::1]"));

        // Unique local
        assert!(is_internal_url("http://[fc00::1]"));
        assert!(is_internal_url("http://[fd00::1]"));
    }

    #[test]
    fn test_is_internal_url_external() {
        assert!(!is_internal_url("http://8.8.8.8"));
        assert!(!is_internal_url("http://1.1.1.1"));
        assert!(!is_internal_url("http://google.com"));
        assert!(!is_internal_url("https://www.example.com"));
    }

    #[test]
    fn test_is_internal_url_invalid_scheme() {
        assert!(is_internal_url("file:///etc/passwd"));
        assert!(is_internal_url("ftp://example.com"));
        assert!(is_internal_url("gopher://localhost"));
    }

    #[test]
    fn test_validate_domain_blacklist() {
        let blacklist = vec!["example.com".to_string(), "malicious.net".to_string()];

        // Exact match
        assert!(validate_domain_blacklist("http://example.com", &blacklist).is_err());
        assert!(validate_domain_blacklist("http://malicious.net/path", &blacklist).is_err());

        // Subdomain match
        assert!(validate_domain_blacklist("http://sub.example.com", &blacklist).is_err());
        assert!(validate_domain_blacklist("http://api.malicious.net", &blacklist).is_err());

        // Not in blacklist
        assert!(validate_domain_blacklist("http://google.com", &blacklist).is_ok());
        assert!(validate_domain_blacklist("http://example.org", &blacklist).is_ok());

        // Partial match should not block
        assert!(validate_domain_blacklist("http://myexample.com", &blacklist).is_ok());
    }

    #[tokio::test]
    async fn test_validate_url_ssrf() {
        let validator = SsrfValidator::new();

        // Localhost variants should be blocked
        assert!(validator.validate("http://localhost").await.is_err());
        assert!(validator
            .validate("http://localhost.localdomain")
            .await
            .is_err());
        assert!(validator.validate("http://127.0.0.1").await.is_err());
        assert!(validator.validate("http://0.0.0.0").await.is_err());

        // Private IPs should be blocked
        assert!(validator.validate("http://10.0.0.1").await.is_err());
        assert!(validator.validate("http://192.168.1.1").await.is_err());
        assert!(validator.validate("http://172.16.0.1").await.is_err());

        // Cloud metadata endpoints should be blocked
        assert!(validator.validate("http://169.254.169.254").await.is_err());
        assert!(validator
            .validate("http://metadata.google.internal")
            .await
            .is_err());

        // Invalid schemes should be blocked
        assert!(validator.validate("file:///etc/passwd").await.is_err());
        assert!(validator.validate("ftp://example.com").await.is_err());
        assert!(validator.validate("gopher://localhost").await.is_err());
    }

    #[tokio::test]
    async fn test_validate_url_too_long() {
        let validator = SsrfValidator::new();
        let long_url = format!("http://example.com/{}", "a".repeat(3000));
        let result = validator.validate(&long_url).await;
        assert!(matches!(result, Err(SsrfError::UrlTooLong { .. })));
    }

    #[test]
    fn test_ssrf_validator_default() {
        let validator = SsrfValidator::default();
        assert!(validator.dns_cache.is_none());
        assert_eq!(validator.config.max_url_length, MAX_URL_LENGTH);
    }

    #[test]
    fn test_ssrf_validator_with_config() {
        let config = SsrfConfig::new().with_max_url_length(512);
        let validator = SsrfValidator::with_config(config);
        assert!(validator.dns_cache.is_none());
        assert_eq!(validator.config.max_url_length, 512);
    }

    #[test]
    fn test_validate_connection_ip_private() {
        let validator = SsrfValidator::new();
        // Private IPs should be blocked
        assert!(validator
            .validate_connection_ip("10.0.0.1".parse().unwrap())
            .is_err());
        assert!(validator
            .validate_connection_ip("192.168.1.1".parse().unwrap())
            .is_err());
        assert!(validator
            .validate_connection_ip("127.0.0.1".parse().unwrap())
            .is_err());
        assert!(validator
            .validate_connection_ip("169.254.169.254".parse().unwrap())
            .is_err());
        assert!(validator
            .validate_connection_ip("::1".parse().unwrap())
            .is_err());
    }

    #[test]
    fn test_validate_connection_ip_public() {
        let validator = SsrfValidator::new();
        // Public IPs should be allowed
        assert!(validator
            .validate_connection_ip("8.8.8.8".parse().unwrap())
            .is_ok());
        assert!(validator
            .validate_connection_ip("1.1.1.1".parse().unwrap())
            .is_ok());
    }

    #[test]
    fn test_is_internal_url_sync_method() {
        let validator = SsrfValidator::new();
        assert!(validator.is_internal_url_sync("http://localhost"));
        assert!(validator.is_internal_url_sync("http://10.0.0.1"));
        assert!(validator.is_internal_url_sync("http://192.168.1.1"));
        assert!(!validator.is_internal_url_sync("http://example.com"));
        assert!(!validator.is_internal_url_sync("https://8.8.8.8"));
    }

    #[test]
    fn test_validate_redirect_method_blocks_internal() {
        let validator = SsrfValidator::new();
        assert!(validator.validate_redirect("http://localhost").is_err());
        assert!(validator.validate_redirect("http://192.168.1.1").is_err());
        assert!(validator.validate_redirect("http://10.0.0.1").is_err());
    }

    #[test]
    fn test_validate_redirect_method_allows_external() {
        let validator = SsrfValidator::new();
        assert!(validator.validate_redirect("http://example.com").is_ok());
        assert!(validator.validate_redirect("https://google.com").is_ok());
    }

    #[tokio::test]
    async fn test_validate_url_convenience_function() {
        // Internal URLs should be blocked
        assert!(validate_url("http://localhost").await.is_err());
        assert!(validate_url("http://10.0.0.1").await.is_err());
        assert!(validate_url("file:///etc/passwd").await.is_err());
        // URL too long
        let long_url = format!("http://example.com/{}", "a".repeat(3000));
        assert!(validate_url(&long_url).await.is_err());
    }

    #[tokio::test]
    async fn test_validate_invalid_url_format() {
        let validator = SsrfValidator::new();
        // Unparsable URL should fail with InvalidUrl
        let result = validator.validate("http://[invalid").await;
        assert!(result.is_err());
        assert!(matches!(result, Err(SsrfError::InvalidUrl { .. })));
    }

    #[test]
    fn test_validate_domain_blacklist_invalid_url() {
        let result = validate_domain_blacklist("not-a-valid-url", &[]);
        assert!(result.is_err());
        assert!(matches!(result, Err(SsrfError::InvalidUrl { .. })));
    }

    #[test]
    fn test_validate_domain_blacklist_missing_host() {
        // mailto: URLs parse but have no host component
        let result = validate_domain_blacklist("mailto:foo@bar.com", &[]);
        assert!(result.is_err());
        assert!(matches!(result, Err(SsrfError::MissingHost { .. })));
    }

    // Constructor tests with DNS cache

    async fn make_dns_cache() -> Arc<DnsCacheService> {
        let cache: Arc<crate::infrastructure::oxcache::DnsCache> = Arc::new(
            oxcache::Cache::builder()
                .capacity(100)
                .ttl(std::time::Duration::from_secs(300))
                .build()
                .await
                .expect("Failed to build oxcache for test"),
        );
        Arc::new(DnsCacheService::new(cache, 300).expect("failed to create DnsCacheService"))
    }

    #[tokio::test]
    async fn test_with_dns_cache_constructor() {
        let dns_cache = make_dns_cache().await;
        let validator = SsrfValidator::with_dns_cache(dns_cache);
        assert!(validator.dns_cache.is_some());
        assert_eq!(validator.config.max_url_length, MAX_URL_LENGTH);
    }

    #[tokio::test]
    async fn test_with_dns_cache_and_config_constructor() {
        let dns_cache = make_dns_cache().await;
        let config = SsrfConfig::new().with_max_url_length(512);
        let validator = SsrfValidator::with_dns_cache_and_config(dns_cache, config);
        assert!(validator.dns_cache.is_some());
        assert_eq!(validator.config.max_url_length, 512);
    }

    #[tokio::test]
    async fn test_validate_with_dns_cache_blocks_internal() {
        let dns_cache = make_dns_cache().await;
        let validator = SsrfValidator::with_dns_cache(dns_cache);

        // Internal URLs should still be blocked even with DNS cache
        assert!(validator.validate("http://localhost").await.is_err());
        assert!(validator.validate("http://127.0.0.1").await.is_err());
        assert!(validator.validate("http://10.0.0.1").await.is_err());
        assert!(validator.validate("file:///etc/passwd").await.is_err());
    }

    #[tokio::test]
    async fn test_validate_with_dns_cache_url_too_long() {
        let dns_cache = make_dns_cache().await;
        let validator = SsrfValidator::with_dns_cache(dns_cache);
        let long_url = format!("http://example.com/{}", "a".repeat(3000));
        let result = validator.validate(&long_url).await;
        assert!(matches!(result, Err(SsrfError::UrlTooLong { .. })));
    }

    #[tokio::test]
    async fn test_validate_with_dns_cache_invalid_url() {
        let dns_cache = make_dns_cache().await;
        let validator = SsrfValidator::with_dns_cache(dns_cache);
        let result = validator.validate("http://[invalid").await;
        assert!(result.is_err());
        assert!(matches!(result, Err(SsrfError::InvalidUrl { .. })));
    }

    #[tokio::test]
    async fn test_validate_with_dns_cache_invalid_scheme() {
        let dns_cache = make_dns_cache().await;
        let validator = SsrfValidator::with_dns_cache(dns_cache);
        let result = validator.validate("ftp://example.com").await;
        assert!(result.is_err());
        assert!(matches!(result, Err(SsrfError::InvalidScheme { .. })));
    }

    #[tokio::test]
    async fn test_validate_with_dns_cache_blocked_hostname() {
        let dns_cache = make_dns_cache().await;
        let validator = SsrfValidator::with_dns_cache(dns_cache);
        // metadata.google.internal is in the blocked hostname list
        let result = validator.validate("http://metadata.google.internal").await;
        assert!(result.is_err());
        assert!(matches!(result, Err(SsrfError::BlockedHostname { .. })));
    }

    #[tokio::test]
    async fn test_validate_with_dns_cache_and_config_blocks_internal() {
        let dns_cache = make_dns_cache().await;
        let config = SsrfConfig::new().with_max_url_length(1024);
        let validator = SsrfValidator::with_dns_cache_and_config(dns_cache, config);
        assert!(validator.validate("http://10.0.0.1").await.is_err());
        assert!(validator.validate("http://192.168.1.1").await.is_err());
    }

    #[tokio::test]
    async fn test_validate_missing_host_with_dns_cache() {
        let dns_cache = make_dns_cache().await;
        let validator = SsrfValidator::with_dns_cache(dns_cache);
        // "http://" has no host
        let result = validator.validate("http://").await;
        assert!(result.is_err());
        // Could be InvalidUrl or MissingHost depending on Url::parse behavior
    }

    #[test]
    fn test_ssrf_validator_clone() {
        let validator = SsrfValidator::new();
        let cloned = validator.clone();
        assert_eq!(
            validator.config.max_url_length,
            cloned.config.max_url_length
        );
    }
}