irontide-session 1.0.1

BitTorrent session management: peers, torrents, and piece selection
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
//! URL security validation — SSRF mitigation, IDNA rejection, HTTPS enforcement.
//!
//! Provides centralized URL checking for tracker announces and web seed requests.
//! Guards against server-side request forgery by rejecting redirects from public
//! to private IP ranges, restricting localhost tracker paths, and optionally
//! rejecting internationalised domain names (IDNA).

use std::net::IpAddr;

use url::Url;

use crate::rate_limiter::is_local_network;

// ── Configuration ─────────────────────────────────────────────────────

/// URL security configuration extracted from [`Settings`](crate::Settings).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UrlSecurityConfig {
    /// Block requests to private/loopback IPs and restrict localhost tracker paths.
    pub ssrf_mitigation: bool,
    /// Allow internationalised (non-ASCII) domain names in URLs.
    pub allow_idna: bool,
    /// Require HTTPS for HTTP tracker announces (UDP trackers are unaffected).
    pub validate_https_trackers: bool,
}

impl Default for UrlSecurityConfig {
    fn default() -> Self {
        Self {
            ssrf_mitigation: true,
            allow_idna: false,
            validate_https_trackers: true,
        }
    }
}

impl From<&crate::settings::Settings> for UrlSecurityConfig {
    fn from(s: &crate::settings::Settings) -> Self {
        Self {
            ssrf_mitigation: s.ssrf_mitigation,
            allow_idna: s.allow_idna,
            validate_https_trackers: s.validate_https_trackers,
        }
    }
}

// ── Errors ────────────────────────────────────────────────────────────

/// Errors returned by URL validation functions.
#[derive(Debug, thiserror::Error)]
pub enum UrlGuardError {
    /// URL failed `url::Url::parse` or used an unsupported scheme.
    #[error("invalid URL: {0}")]
    InvalidUrl(String),

    /// A localhost tracker URL was missing the required `/announce` path —
    /// BEP 3 trackers must terminate at that path, and accepting bare-host
    /// URLs widens the SSRF surface unnecessarily.
    #[error("SSRF: localhost tracker must use /announce path, got: {0}")]
    LocalhostBadPath(String),

    /// A local-network web seed URL carried a query string. BEP 17/19 web
    /// seeds shouldn't need one, and allowing them opens an SSRF vector
    /// (smuggling commands via `?` to local services).
    #[error("local-network web seed URL must not contain a query string")]
    LocalNetworkQueryString,

    /// In-flight redirect from a public URL landed on a private IP — fired
    /// by the custom [`reqwest::redirect::Policy`] returned by
    /// [`build_redirect_policy`]. Distinct from [`Self::PrivateHostBlocked`],
    /// which is a *pre-flight* check on user-supplied URLs.
    #[error("SSRF: redirect from global URL to private/local IP {0} blocked")]
    RedirectToPrivateIp(IpAddr),

    /// An internationalised domain name was present and IDNA was disallowed by
    /// the active [`UrlSecurityConfig`].
    #[error("internationalised domain name (IDNA) rejected: {0}")]
    IdnaDomain(String),

    /// M218: a user-typed URL pointed at a private/loopback host. Stricter than
    /// [`Self::RedirectToPrivateIp`] (which only fires in-flight); this is the
    /// pre-flight check that rejects `http://localhost/`, `http://192.168.1.1/`,
    /// `http://0.0.0.0/`, `http://[::ffff:127.0.0.1]/`, etc. before the request
    /// leaves the process.
    #[error("SSRF: URL host {0} is on a private/local network")]
    PrivateHostBlocked(String),
}

// ── Private helpers ───────────────────────────────────────────────────

/// Extract an IP address from a URL whose host is an IP literal.
fn host_ip(url: &Url) -> Option<IpAddr> {
    match url.host()? {
        url::Host::Ipv4(ip) => Some(IpAddr::V4(ip)),
        url::Host::Ipv6(ip) => Some(IpAddr::V6(ip)),
        url::Host::Domain(_) => None,
    }
}

/// Returns `true` if the URL points to localhost (127.0.0.0/8, `::1`, or "localhost").
fn is_localhost(url: &Url) -> bool {
    match url.host() {
        Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
        Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
        Some(url::Host::Domain(d)) => d == "localhost",
        None => false,
    }
}

/// Returns `true` if the URL's host is a local/private network address.
fn is_local_host_url(url: &Url) -> bool {
    match host_ip(url) {
        Some(ip) => is_local_network(ip),
        None => {
            // Domain name — only "localhost" is considered local.
            matches!(url.host_str(), Some("localhost"))
        }
    }
}

/// Returns `true` if the URL contains a non-ASCII (internationalised) domain name.
///
/// The `url` crate may punycode-encode non-ASCII hostnames, so we check the
/// original host string for either non-ASCII characters or the punycode `xn--`
/// prefix in any label.
fn has_idna_domain(url: &Url) -> bool {
    match url.host_str() {
        Some(host) => {
            // Check for non-ASCII characters (direct Unicode representation).
            if !host.is_ascii() {
                return true;
            }
            // Check for punycode-encoded labels (url crate may convert to ASCII).
            host.split('.').any(|label| label.starts_with("xn--"))
        }
        None => false,
    }
}

// ── Public validation functions ───────────────────────────────────────

/// Validate a tracker announce URL.
///
/// - UDP trackers skip SSRF checks (they don't follow HTTP redirects) but
///   still undergo IDNA validation.
/// - HTTP/HTTPS trackers check IDNA + localhost path restrictions.
pub(crate) fn validate_tracker_url(
    url_str: &str,
    config: UrlSecurityConfig,
) -> Result<(), UrlGuardError> {
    let url = Url::parse(url_str).map_err(|e| UrlGuardError::InvalidUrl(e.to_string()))?;

    // IDNA check applies to all URL schemes.
    if !config.allow_idna && has_idna_domain(&url) {
        return Err(UrlGuardError::IdnaDomain(
            url.host_str().unwrap_or_default().to_string(),
        ));
    }

    // UDP trackers don't need SSRF checks — they can't follow redirects.
    if url.scheme() == "udp" {
        return Ok(());
    }

    // SSRF: localhost tracker URLs must have path ending in /announce.
    if config.ssrf_mitigation && is_localhost(&url) && !url.path().ends_with("/announce") {
        return Err(UrlGuardError::LocalhostBadPath(url.path().to_string()));
    }

    Ok(())
}

/// Validate a web seed (BEP 19 / BEP 17) URL.
///
/// - IDNA check.
/// - Local-network URLs must not have a query string (prevents info leakage).
pub(crate) fn validate_web_seed_url(
    url_str: &str,
    config: UrlSecurityConfig,
) -> Result<(), UrlGuardError> {
    let url = Url::parse(url_str).map_err(|e| UrlGuardError::InvalidUrl(e.to_string()))?;

    if !config.allow_idna && has_idna_domain(&url) {
        return Err(UrlGuardError::IdnaDomain(
            url.host_str().unwrap_or_default().to_string(),
        ));
    }

    if config.ssrf_mitigation && is_local_host_url(&url) && url.query().is_some() {
        return Err(UrlGuardError::LocalNetworkQueryString);
    }

    Ok(())
}

/// Validate an HTTP redirect target against SSRF policy.
///
/// Blocks redirects from a public (non-local) origin to a private/local IP.
#[allow(dead_code)] // Public API for callers to pre-check redirects; also tested in scenario tests.
pub(crate) fn validate_redirect(
    original_url: &Url,
    redirect_url: &Url,
    config: UrlSecurityConfig,
) -> Result<(), UrlGuardError> {
    if !config.ssrf_mitigation {
        return Ok(());
    }

    let orig_local = match host_ip(original_url) {
        Some(ip) => is_local_network(ip),
        None => is_localhost(original_url),
    };

    // Only block public -> private redirects; private -> private is fine.
    if orig_local {
        return Ok(());
    }

    let redirect_ip = host_ip(redirect_url);
    let redirect_local = match redirect_ip {
        Some(ip) => is_local_network(ip),
        None => is_localhost(redirect_url),
    };

    if redirect_local {
        let ip = redirect_ip.unwrap_or_else(|| "127.0.0.1".parse().unwrap());
        return Err(UrlGuardError::RedirectToPrivateIp(ip));
    }

    Ok(())
}

/// M218: validate a user-typed URL before issuing an HTTP fetch.
///
/// Stricter than [`validate_web_seed_url`] (which only blocks query strings on
/// local URLs): for arbitrary user-supplied URLs there is no swarm context to
/// bound the risk, so *any* private/loopback host is rejected outright when
/// `ssrf_mitigation` is enabled. Also restricts the scheme to `http` / `https`
/// — `file://` is local file disclosure and other schemes have no useful
/// semantics for a `.torrent` fetch.
///
/// Returns `Ok(())` if the URL is safe to fetch under `config`. The check is
/// pre-flight; the in-flight redirect check is enforced separately by the
/// `reqwest` policy built by [`build_redirect_policy`].
///
/// # Errors
///
/// Returns [`UrlGuardError::InvalidUrl`] if `url_str` fails to parse or uses a
/// scheme other than `http` / `https`; [`UrlGuardError::IdnaDomain`] if IDNA is
/// disallowed and the host contains punycode; [`UrlGuardError::PrivateHostBlocked`]
/// if SSRF mitigation is on and the host resolves to a private/loopback
/// address (including `0.0.0.0`, `::`, and IPv4-mapped IPv6 loopback).
pub fn validate_user_url(
    url_str: &str,
    config: UrlSecurityConfig,
) -> Result<(), UrlGuardError> {
    let url = Url::parse(url_str).map_err(|e| UrlGuardError::InvalidUrl(e.to_string()))?;

    if !matches!(url.scheme(), "http" | "https") {
        return Err(UrlGuardError::InvalidUrl(format!(
            "unsupported scheme '{}'",
            url.scheme()
        )));
    }

    if !config.allow_idna && has_idna_domain(&url) {
        return Err(UrlGuardError::IdnaDomain(
            url.host_str().unwrap_or_default().to_string(),
        ));
    }

    if config.ssrf_mitigation && (is_localhost(&url) || is_local_host_url(&url)) {
        return Err(UrlGuardError::PrivateHostBlocked(
            url.host_str().unwrap_or_default().to_string(),
        ));
    }

    Ok(())
}

// ── HTTP helpers ──────────────────────────────────────────────────────

/// Build a reqwest redirect policy that blocks SSRF redirect attacks.
///
/// If SSRF mitigation is enabled, redirects from public to private IPs are
/// rejected. Otherwise a standard 10-hop redirect policy is used.
///
/// Returns a policy compatible with both `reqwest::Client` and
/// `reqwest::blocking::Client` (they share the same `redirect::Policy` type).
#[must_use]
pub fn build_redirect_policy(config: UrlSecurityConfig) -> reqwest::redirect::Policy {
    if !config.ssrf_mitigation {
        return reqwest::redirect::Policy::limited(10);
    }

    reqwest::redirect::Policy::custom(move |attempt| {
        if attempt.previous().len() >= 10 {
            return attempt.error(std::io::Error::other("too many redirects"));
        }

        let original = &attempt.previous()[0];
        let redirect = attempt.url();

        let orig_local = match original.host() {
            Some(url::Host::Ipv4(ip)) => is_local_network(IpAddr::V4(ip)),
            Some(url::Host::Ipv6(ip)) => is_local_network(IpAddr::V6(ip)),
            Some(url::Host::Domain(d)) => d == "localhost",
            None => false,
        };

        if !orig_local {
            let redirect_local = match redirect.host() {
                Some(url::Host::Ipv4(ip)) => is_local_network(IpAddr::V4(ip)),
                Some(url::Host::Ipv6(ip)) => is_local_network(IpAddr::V6(ip)),
                Some(url::Host::Domain(d)) => d == "localhost",
                None => false,
            };

            if redirect_local {
                return attempt.error(std::io::Error::other(
                    "redirect from public to private IP blocked (SSRF)",
                ));
            }
        }

        attempt.follow()
    })
}

/// Build a configured reqwest HTTP client with SSRF-safe redirect policy.
pub(crate) fn build_http_client(
    config: UrlSecurityConfig,
    proxy_url: Option<&str>,
    user_agent: &str,
) -> reqwest::Client {
    let mut builder = reqwest::Client::builder()
        .user_agent(user_agent)
        .redirect(build_redirect_policy(config))
        .timeout(std::time::Duration::from_secs(30))
        .connect_timeout(std::time::Duration::from_secs(10));

    if !config.validate_https_trackers {
        builder = builder.danger_accept_invalid_certs(true);
    }

    if let Some(proxy) = proxy_url
        && let Ok(p) = reqwest::Proxy::all(proxy)
    {
        builder = builder.proxy(p);
    }

    builder.build().expect("failed to build HTTP client")
}

// ── Tests ─────────────────────────────────────────────────────────────

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

    fn ssrf_config() -> UrlSecurityConfig {
        UrlSecurityConfig {
            ssrf_mitigation: true,
            allow_idna: false,
            validate_https_trackers: true,
        }
    }

    fn permissive_config() -> UrlSecurityConfig {
        UrlSecurityConfig {
            ssrf_mitigation: false,
            allow_idna: true,
            validate_https_trackers: false,
        }
    }

    // ── Config defaults ──

    #[test]
    fn url_security_config_defaults() {
        let cfg = UrlSecurityConfig::default();
        assert!(cfg.ssrf_mitigation);
        assert!(!cfg.allow_idna);
        assert!(cfg.validate_https_trackers);
    }

    // ── Helper functions ──

    #[test]
    fn host_ip_extraction() {
        let url = Url::parse("http://192.168.1.1:8080/path").unwrap();
        assert_eq!(host_ip(&url), Some("192.168.1.1".parse().unwrap()));

        let url = Url::parse("http://[::1]:8080/path").unwrap();
        assert_eq!(host_ip(&url), Some("::1".parse().unwrap()));

        let url = Url::parse("http://example.com/path").unwrap();
        assert_eq!(host_ip(&url), None);
    }

    #[test]
    fn localhost_detection() {
        assert!(is_localhost(
            &Url::parse("http://127.0.0.1/announce").unwrap()
        ));
        assert!(is_localhost(
            &Url::parse("http://127.0.0.5:8080/announce").unwrap()
        ));
        assert!(is_localhost(&Url::parse("http://[::1]/announce").unwrap()));
        assert!(is_localhost(
            &Url::parse("http://localhost/announce").unwrap()
        ));
        assert!(!is_localhost(
            &Url::parse("http://10.0.0.1/announce").unwrap()
        ));
        assert!(!is_localhost(
            &Url::parse("http://example.com/announce").unwrap()
        ));
    }

    #[test]
    fn idna_domain_detection() {
        // The url crate punycode-encodes non-ASCII domains, so we check for xn-- labels.
        let url = Url::parse("http://xn--nxasmq6b.example.com/path").unwrap();
        assert!(has_idna_domain(&url));

        // Plain ASCII domain should not be flagged.
        let url = Url::parse("http://tracker.example.com/announce").unwrap();
        assert!(!has_idna_domain(&url));

        // IP-literal host: no domain, no IDNA.
        let url = Url::parse("http://192.168.1.1/path").unwrap();
        assert!(!has_idna_domain(&url));
    }

    // ── Tracker URL validation ──

    #[test]
    fn tracker_url_valid_public_http() {
        let cfg = ssrf_config();
        assert!(validate_tracker_url("http://tracker.example.com/announce", cfg).is_ok());
        assert!(validate_tracker_url("https://tracker.example.com/announce", cfg).is_ok());
    }

    #[test]
    fn tracker_url_valid_udp() {
        let cfg = ssrf_config();
        assert!(validate_tracker_url("udp://tracker.example.com:6969/announce", cfg).is_ok());
    }

    #[test]
    fn tracker_url_udp_localhost_allowed() {
        // UDP trackers skip SSRF checks entirely.
        let cfg = ssrf_config();
        assert!(validate_tracker_url("udp://127.0.0.1:6969/announce", cfg).is_ok());
        assert!(validate_tracker_url("udp://127.0.0.1:6969/bad/path", cfg).is_ok());
    }

    #[test]
    fn tracker_url_localhost_good_path() {
        let cfg = ssrf_config();
        assert!(validate_tracker_url("http://127.0.0.1:8080/announce", cfg).is_ok());
        assert!(validate_tracker_url("http://localhost/announce", cfg).is_ok());
        assert!(validate_tracker_url("http://127.0.0.1/custom/announce", cfg).is_ok());
    }

    #[test]
    fn tracker_url_localhost_bad_path() {
        let cfg = ssrf_config();
        assert!(matches!(
            validate_tracker_url("http://127.0.0.1:8080/api/admin", cfg),
            Err(UrlGuardError::LocalhostBadPath(_))
        ));
        assert!(matches!(
            validate_tracker_url("http://localhost/", cfg),
            Err(UrlGuardError::LocalhostBadPath(_))
        ));
    }

    #[test]
    fn tracker_url_localhost_ssrf_disabled() {
        let mut cfg = ssrf_config();
        cfg.ssrf_mitigation = false;
        // With SSRF disabled, bad paths on localhost are allowed.
        assert!(validate_tracker_url("http://127.0.0.1:8080/api/admin", cfg).is_ok());
    }

    #[test]
    fn tracker_url_invalid() {
        let cfg = ssrf_config();
        assert!(matches!(
            validate_tracker_url("not a url", cfg),
            Err(UrlGuardError::InvalidUrl(_))
        ));
    }

    #[test]
    fn tracker_url_idna_rejected() {
        let cfg = ssrf_config();
        // Use a punycode-encoded domain since url crate normalises.
        assert!(matches!(
            validate_tracker_url("http://xn--nxasmq6b.example.com/announce", cfg),
            Err(UrlGuardError::IdnaDomain(_))
        ));
    }

    #[test]
    fn tracker_url_idna_allowed() {
        let cfg = permissive_config();
        assert!(validate_tracker_url("http://xn--nxasmq6b.example.com/announce", cfg).is_ok());
    }

    // ── Web seed URL validation ──

    #[test]
    fn web_seed_url_valid_public() {
        let cfg = ssrf_config();
        assert!(validate_web_seed_url("http://cdn.example.com/files/", cfg).is_ok());
        assert!(validate_web_seed_url("https://cdn.example.com/files/?token=abc", cfg).is_ok());
    }

    #[test]
    fn web_seed_url_local_no_query() {
        let cfg = ssrf_config();
        assert!(validate_web_seed_url("http://192.168.1.100/files/", cfg).is_ok());
        assert!(validate_web_seed_url("http://10.0.0.1/data/", cfg).is_ok());
    }

    #[test]
    fn web_seed_url_local_with_query() {
        let cfg = ssrf_config();
        assert!(matches!(
            validate_web_seed_url("http://192.168.1.100/files/?secret=abc", cfg),
            Err(UrlGuardError::LocalNetworkQueryString)
        ));
        assert!(matches!(
            validate_web_seed_url("http://localhost/files/?key=val", cfg),
            Err(UrlGuardError::LocalNetworkQueryString)
        ));
    }

    #[test]
    fn web_seed_url_local_query_ssrf_disabled() {
        let mut cfg = ssrf_config();
        cfg.ssrf_mitigation = false;
        assert!(validate_web_seed_url("http://192.168.1.100/files/?secret=abc", cfg).is_ok());
    }

    #[test]
    fn web_seed_url_idna_rejected() {
        let cfg = ssrf_config();
        assert!(matches!(
            validate_web_seed_url("http://xn--nxasmq6b.example.com/files/", cfg),
            Err(UrlGuardError::IdnaDomain(_))
        ));
    }

    // ── Redirect validation ──

    #[test]
    fn redirect_public_to_public() {
        let cfg = ssrf_config();
        let orig = Url::parse("http://tracker.example.com/announce").unwrap();
        let redir = Url::parse("http://other.example.com/announce").unwrap();
        assert!(validate_redirect(&orig, &redir, cfg).is_ok());
    }

    #[test]
    fn redirect_public_to_private_blocked() {
        let cfg = ssrf_config();
        let orig = Url::parse("http://tracker.example.com/announce").unwrap();
        let redir = Url::parse("http://192.168.1.1/announce").unwrap();
        assert!(matches!(
            validate_redirect(&orig, &redir, cfg),
            Err(UrlGuardError::RedirectToPrivateIp(_))
        ));
    }

    #[test]
    fn redirect_public_to_localhost_blocked() {
        let cfg = ssrf_config();
        let orig = Url::parse("http://tracker.example.com/announce").unwrap();
        let redir = Url::parse("http://127.0.0.1/announce").unwrap();
        assert!(matches!(
            validate_redirect(&orig, &redir, cfg),
            Err(UrlGuardError::RedirectToPrivateIp(_))
        ));

        let redir_v6 = Url::parse("http://[::1]/announce").unwrap();
        assert!(matches!(
            validate_redirect(&orig, &redir_v6, cfg),
            Err(UrlGuardError::RedirectToPrivateIp(_))
        ));
    }

    #[test]
    fn redirect_public_to_localhost_domain_blocked() {
        let cfg = ssrf_config();
        let orig = Url::parse("http://tracker.example.com/announce").unwrap();
        let redir = Url::parse("http://localhost/announce").unwrap();
        assert!(matches!(
            validate_redirect(&orig, &redir, cfg),
            Err(UrlGuardError::RedirectToPrivateIp(_))
        ));
    }

    #[test]
    fn redirect_private_to_private_allowed() {
        let cfg = ssrf_config();
        let orig = Url::parse("http://192.168.1.1/announce").unwrap();
        let redir = Url::parse("http://10.0.0.1/announce").unwrap();
        assert!(validate_redirect(&orig, &redir, cfg).is_ok());
    }

    #[test]
    fn redirect_private_to_public_allowed() {
        let cfg = ssrf_config();
        let orig = Url::parse("http://192.168.1.1/announce").unwrap();
        let redir = Url::parse("http://tracker.example.com/announce").unwrap();
        assert!(validate_redirect(&orig, &redir, cfg).is_ok());
    }

    #[test]
    fn redirect_ssrf_disabled() {
        let mut cfg = ssrf_config();
        cfg.ssrf_mitigation = false;
        let orig = Url::parse("http://tracker.example.com/announce").unwrap();
        let redir = Url::parse("http://192.168.1.1/announce").unwrap();
        assert!(validate_redirect(&orig, &redir, cfg).is_ok());
    }

    // ── HTTP client builder ──

    #[test]
    fn build_client_default_config() {
        let cfg = ssrf_config();
        let client = build_http_client(cfg, None, "Torrent/0.60.0");
        // Just verify it builds without panicking.
        drop(client);
    }

    #[test]
    fn build_client_with_proxy() {
        let cfg = ssrf_config();
        let client =
            build_http_client(cfg, Some("http://proxy.example.com:8080"), "Torrent/0.60.0");
        drop(client);
    }

    #[test]
    fn build_client_invalid_proxy_fallback() {
        let cfg = ssrf_config();
        // Invalid proxy URL — should still build a client (proxy is silently skipped).
        let client = build_http_client(cfg, Some("not a url"), "Torrent/0.60.0");
        drop(client);
    }

    #[test]
    fn build_client_permissive_config() {
        let cfg = permissive_config();
        let client = build_http_client(cfg, None, "Torrent/0.60.0");
        drop(client);
    }

    #[test]
    fn build_redirect_policy_ssrf_enabled() {
        let cfg = ssrf_config();
        let _policy = build_redirect_policy(cfg);
    }

    #[test]
    fn build_redirect_policy_ssrf_disabled() {
        let mut cfg = ssrf_config();
        cfg.ssrf_mitigation = false;
        let _policy = build_redirect_policy(cfg);
    }

    // ── M218: validate_user_url tests ──

    #[test]
    fn validate_user_url_rejects_localhost() {
        let cfg = ssrf_config();
        assert!(matches!(
            validate_user_url("http://localhost/file.torrent", cfg),
            Err(UrlGuardError::PrivateHostBlocked(_))
        ));
    }

    #[test]
    fn validate_user_url_rejects_loopback_ip() {
        let cfg = ssrf_config();
        assert!(matches!(
            validate_user_url("http://127.0.0.1/x", cfg),
            Err(UrlGuardError::PrivateHostBlocked(_))
        ));
        assert!(matches!(
            validate_user_url("http://[::1]/x", cfg),
            Err(UrlGuardError::PrivateHostBlocked(_))
        ));
    }

    #[test]
    fn validate_user_url_rejects_rfc1918() {
        let cfg = ssrf_config();
        for host in ["http://192.168.1.1/x", "http://10.0.0.5/x", "http://172.16.0.1/x"] {
            assert!(
                matches!(validate_user_url(host, cfg), Err(UrlGuardError::PrivateHostBlocked(_))),
                "expected PrivateHostBlocked for {host}",
            );
        }
    }

    #[test]
    fn validate_user_url_rejects_unspecified_and_mapped() {
        // M218 OV: must also catch 0.0.0.0 and ::ffff:127.0.0.1 (the
        // is_local_network gaps fixed in this milestone).
        let cfg = ssrf_config();
        for host in [
            "http://0.0.0.0/x",
            "http://[::]/x",
            "http://[::ffff:127.0.0.1]/x",
            "http://[::ffff:192.168.1.1]/x",
        ] {
            assert!(
                matches!(validate_user_url(host, cfg), Err(UrlGuardError::PrivateHostBlocked(_))),
                "expected PrivateHostBlocked for {host}",
            );
        }
    }

    #[test]
    fn validate_user_url_allows_public_https() {
        let cfg = ssrf_config();
        assert!(validate_user_url("https://example.com/foo.torrent", cfg).is_ok());
        assert!(validate_user_url("http://8.8.8.8/x.torrent", cfg).is_ok());
    }

    #[test]
    fn validate_user_url_rejects_unsupported_scheme() {
        let cfg = ssrf_config();
        for url in [
            "file:///etc/passwd",
            "ftp://example.com/x",
            "gopher://example.com/0",
            "data:application/octet-stream;base64,ZA==",
        ] {
            assert!(
                matches!(validate_user_url(url, cfg), Err(UrlGuardError::InvalidUrl(_))),
                "expected InvalidUrl for {url}",
            );
        }
    }

    #[test]
    fn validate_user_url_rejects_idna_when_disallowed() {
        let cfg = ssrf_config();
        assert!(matches!(
            validate_user_url("http://example.中国/x", cfg),
            Err(UrlGuardError::IdnaDomain(_))
        ));
        let permissive = permissive_config();
        // With permissive config, IDNA passes but private check is also off,
        // so an IDNA + public host should succeed.
        assert!(validate_user_url("http://example.中国/x", permissive).is_ok());
    }

    #[test]
    fn validate_user_url_rejects_malformed_url() {
        let cfg = ssrf_config();
        assert!(matches!(
            validate_user_url("not a url", cfg),
            Err(UrlGuardError::InvalidUrl(_))
        ));
    }

    // ── Integration / scenario tests ──

    #[test]
    fn scenario_malicious_torrent_ssrf_via_tracker() {
        let cfg = ssrf_config();
        let err =
            validate_tracker_url("http://127.0.0.1:9090/api/admin/delete-all", cfg).unwrap_err();
        assert!(matches!(err, UrlGuardError::LocalhostBadPath(_)));
        assert!(validate_tracker_url("http://127.0.0.1:9090/announce", cfg).is_ok());
    }

    #[test]
    fn scenario_malicious_torrent_ssrf_via_web_seed() {
        let cfg = ssrf_config();
        let err = validate_web_seed_url("http://192.168.1.1/api?action=reboot", cfg).unwrap_err();
        assert!(matches!(err, UrlGuardError::LocalNetworkQueryString));
    }

    #[test]
    fn scenario_redirect_ssrf() {
        let cfg = ssrf_config();
        let orig = Url::parse("http://evil-tracker.example.com/announce").unwrap();
        let redir = Url::parse("http://169.254.169.254/metadata/v1/").unwrap();
        let err = validate_redirect(&orig, &redir, cfg).unwrap_err();
        assert!(matches!(err, UrlGuardError::RedirectToPrivateIp(_)));
    }

    #[test]
    fn scenario_legitimate_local_tracker() {
        let cfg = ssrf_config();
        assert!(validate_tracker_url("http://192.168.1.100:6969/announce", cfg).is_ok());
        assert!(validate_tracker_url("http://[fe80::1]:6969/announce", cfg).is_ok());
    }

    #[test]
    fn scenario_homograph_attack() {
        let cfg = ssrf_config();
        // Cyrillic 'а' (U+0430) looks identical to Latin 'a'.
        // The url crate punycode-encodes non-ASCII hostnames, so test with the
        // pre-encoded form. With allow_idna: false the xn-- label is rejected,
        // preventing homograph-based tracker substitution attacks.
        assert!(matches!(
            validate_tracker_url("http://xn--nxasmq6b.evil.com/announce", cfg),
            Err(UrlGuardError::IdnaDomain(_))
        ));
    }

    #[test]
    fn scenario_all_protections_disabled() {
        let cfg = UrlSecurityConfig {
            ssrf_mitigation: false,
            allow_idna: true,
            validate_https_trackers: true,
        };
        assert!(validate_tracker_url("http://127.0.0.1:9090/admin", cfg).is_ok());
        assert!(validate_web_seed_url("http://10.0.0.1/data?cmd=exec", cfg).is_ok());
        let orig = Url::parse("http://tracker.example.com/announce").unwrap();
        let redir = Url::parse("http://127.0.0.1/admin").unwrap();
        assert!(validate_redirect(&orig, &redir, cfg).is_ok());
    }
}