domain-status 0.2.1

Concurrent URL status checker that captures comprehensive metadata in SQLite.
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
//! HTTP redirect chain resolution.
//!
//! This module handles following redirect chains manually to track the full path
//! from initial URL to final destination.

use anyhow::{Context, Error, Result};
use reqwest::Url;

use crate::fetch::request::RequestHeaders;
use crate::security::validate_url_safe;

/// True if the URL's host is loopback (127.0.0.0/8 or `::1`). Used in tests to allow httptest server URLs.
fn is_loopback_url(url_str: &str) -> bool {
    url::Url::parse(url_str)
        .ok()
        .and_then(|u| {
            u.host().map(|h| match h {
                url::Host::Ipv4(ip) => ip.is_loopback(),
                url::Host::Ipv6(ip) => ip.is_loopback(),
                url::Host::Domain(_) => false,
            })
        })
        .unwrap_or(false)
}

/// Validates a redirect target before following it.
///
/// Enforces two SSRF/downgrade guards:
///
/// 1. **No HTTPS → HTTP downgrade.** Once the chain started on `https`, any later `http`
///    hop (same host or not) is blocked. This prevents an attacker who controls the
///    redirect target from stripping TLS while the scanner still treats the chain as
///    "safe".
/// 2. **Re-run [`validate_url_safe`] on every hop.** The previous design skipped
///    validation when the new host equalled the current host, which let a same-host
///    HTTPS → HTTP downgrade through and would also miss any future enrichments to
///    `validate_url_safe` (e.g. DNS rebinding, scheme-specific policy, etc.).
///
/// `allow_loopback` is the runtime escape hatch for tests using
/// `httptest`/`wiremock` mock servers (which bind to `127.0.0.1` / `::1`). When
/// set, loopback targets bypass the SSRF check, but **not** the downgrade
/// check — the downgrade rule fires regardless. Production callers must always
/// pass `false`. Wired through from `Config::allow_localhost_for_tests`.
fn validate_redirect_target(
    new_url_str: &str,
    new_scheme: &str,
    chain_started_https: bool,
    allow_loopback: bool,
) -> Result<()> {
    if chain_started_https && new_scheme == "http" {
        return Err(anyhow::anyhow!(
            "Blocked HTTPS->HTTP downgrade redirect to {new_url_str}"
        ));
    }
    let skip_validation = allow_loopback && is_loopback_url(new_url_str);
    if !skip_validation {
        validate_url_safe(new_url_str)
            .with_context(|| format!("Unsafe redirect target rejected: {new_url_str}"))?;
    }
    Ok(())
}

/// Checks if an HTTP status code indicates a redirect.
///
/// Returns `true` for redirect status codes: 301, 302, 303, 307, 308.
/// These are the standard HTTP redirect status codes that should be followed.
///
/// # Arguments
///
/// * `status_code` - The HTTP status code to check
///
/// # Returns
///
/// `true` if the status code is a redirect, `false` otherwise.
fn is_redirect_status(status_code: u16) -> bool {
    matches!(status_code, 301 | 302 | 303 | 307 | 308)
}

/// Resolves the redirect chain for a URL, following redirects up to a maximum number of hops.
///
/// # Arguments
///
/// * `start_url` - The initial URL to start from
/// * `max_hops` - Maximum number of redirect hops to follow (must be > 0)
/// * `client` - HTTP client with redirects disabled (for manual tracking)
///
/// # Returns
///
/// A tuple of (`final_url`, `redirect_chain`, `final_response`) where:
/// - `final_url` is the final URL after all redirects
/// - `redirect_chain` is a vector of all URLs in the chain (including final URL)
/// - `final_response` is the non-redirect response from the final URL (if available).
///   This allows the caller to skip a redundant second fetch. The response is `None` when
///   the loop exits early (max-hops reached, SSRF block, invalid Location header).
///
/// # Errors
///
/// Returns an error if HTTP requests fail, URL parsing fails, or `max_hops` is 0.
pub async fn resolve_redirect_chain(
    start_url: &str,
    max_hops: usize,
    client: &reqwest::Client,
    allow_loopback: bool,
) -> Result<(String, Vec<(String, u16)>, Option<reqwest::Response>), Error> {
    // Validate max_hops
    if max_hops == 0 {
        return Err(anyhow::anyhow!("max_hops must be > 0"));
    }

    // SSRF protection: validate initial URL before any request. IP literals (e.g. http://169.254.169.254)
    // bypass the HTTP client's DNS-based SafeResolver because reqwest connects directly without resolution.
    // `allow_loopback` is wired from `Config::allow_localhost_for_tests` so integration tests using
    // httptest's server.url() (e.g. http://[::1]:port or http://127.0.0.1:port) can run; production
    // callers always pass `false`.
    let skip_initial_validation = allow_loopback && is_loopback_url(start_url);
    if !skip_initial_validation {
        validate_url_safe(start_url)
            .with_context(|| format!("Unsafe initial URL rejected: {start_url}"))?;
    }

    // Capture whether the chain started on HTTPS so we can reject any later HTTP hop
    // (no TLS downgrade, even on same host). Parsing failure here is non-fatal — if
    // the start URL is malformed enough to fail Url::parse, validate_url_safe above
    // would already have rejected it (or this is a test-loopback bypass case).
    let chain_started_https = Url::parse(start_url)
        .map(|u| u.scheme() == "https")
        .unwrap_or(false);

    // Pre-allocate chain with capacity to avoid reallocations
    // Each entry is (url, http_status) where http_status is the status received for that URL
    let mut chain: Vec<(String, u16)> = Vec::with_capacity(max_hops + 1);
    let mut current = start_url.to_string();
    let mut last_fetched_url = start_url.to_string(); // Track the last URL we actually fetched
    let mut final_response: Option<reqwest::Response> = None; // Non-redirect response to return to caller (avoids double fetch)

    for hop_num in 0..max_hops {
        last_fetched_url.clone_from(&current); // This is the URL we're about to fetch

        // Add realistic browser headers to reduce bot detection during redirect resolution
        // This is critical because sites may serve different content (or block) based on headers
        // Note: We use GET instead of HEAD because:
        // 1. Some servers handle HEAD requests poorly (slower or reject them)
        // 2. The fallback overhead (HEAD -> GET) can add latency
        // 3. In practice, GET is often faster and more reliable for redirect resolution
        let resp = RequestHeaders::apply_to_request_builder(client.get(&current))
            .send()
            .await?;

        // Only follow redirects if the status code indicates a redirect AND there's a Location header
        let status = resp.status();
        let status_code = status.as_u16();

        // Record this URL and its status code in the chain
        chain.push((current.clone(), status_code));
        // Check if status is a redirect (301, 302, 303, 307, 308)
        if is_redirect_status(status_code) {
            if let Some(loc) = resp.headers().get(reqwest::header::LOCATION) {
                // Avoid unnecessary String allocation - parse directly from &str
                // If header value is not valid UTF-8, skip this redirect (unusual but possible)
                let loc_str = match loc.to_str() {
                    Ok(s) => s,
                    Err(e) => {
                        log::warn!(
                            "Location header for {current} contains invalid UTF-8: {e}. Skipping redirect."
                        );
                        // Break here: we've reached a non-redirect state (invalid redirect)
                        // last_fetched_url is the final URL we actually fetched
                        break;
                    }
                };
                let new_url = Url::parse(loc_str)
                    .or_else(|_| Url::parse(&current).and_then(|base| base.join(loc_str)))?;

                // SSRF + scheme-downgrade protection: re-validate every hop. The previous
                // design skipped validation for same-host redirects, which let HTTPS->HTTP
                // downgrades through (an attacker controlling the target server could strip
                // TLS while the scanner still treated the chain as "safe").
                let new_url_str = new_url.to_string();
                if let Err(e) = validate_redirect_target(
                    &new_url_str,
                    new_url.scheme(),
                    chain_started_https,
                    allow_loopback,
                ) {
                    log::warn!(
                        "Blocked unsafe redirect from {current} to {new_url_str}: {e}. Stopping redirect chain."
                    );
                    // Break here: we've reached an unsafe redirect
                    // last_fetched_url is the final URL we actually fetched
                    break;
                }

                // Check if we've reached max_hops - if so, don't follow the redirect
                // Return the last URL we actually fetched instead of the Location header URL
                if hop_num == max_hops - 1 {
                    log::warn!(
                        "Redirect chain for {start_url} exceeded max_hops ({max_hops}). Stopping at {last_fetched_url} (which returned redirect to {new_url})."
                    );
                    // Return the last URL we actually fetched, not the Location header URL
                    // This ensures we only return URLs that were actually fetched
                    break;
                }

                // Only allocate String when we actually need to update current
                current = new_url.to_string();
                continue;
            }
            // Redirect status but no Location header - this is unusual, log and break
            log::warn!("Redirect status {status_code} for {current} but no Location header");
            // Break here: we've reached a non-redirect state (invalid redirect)
            // last_fetched_url is the final URL we actually fetched
            break;
        }
        // Not a redirect, we've reached the final URL.
        // Save the response so the caller can reuse it (avoids a second fetch).
        final_response = Some(resp);
        break;
    }

    // Use last_fetched_url as the final URL (the last URL we actually fetched)
    // This ensures we never return a URL that wasn't actually fetched
    // The chain now always includes (url, status_code) after each fetch,
    // so last_fetched_url should already be the last entry's URL.
    // Guard against edge cases where the loop didn't push (e.g., max_hops=0 which is rejected above).
    if chain.last().map(|(url, _)| url) != Some(&last_fetched_url) {
        // Status 0 means we didn't get a response for this URL (shouldn't happen in practice)
        chain.push((last_fetched_url.clone(), 0));
    }
    let final_url = last_fetched_url; // Move instead of clone (optimization)

    Ok((final_url, chain, final_response))
}

#[cfg(test)]
mod tests {
    use super::*;
    use httptest::{matchers::*, responders::*, Expectation, Server};

    #[tokio::test]
    async fn test_resolve_redirect_chain_no_redirects() {
        let server = Server::run();
        server.expect(
            Expectation::matching(request::method_path("GET", "/"))
                .respond_with(status_code(200).body("OK")),
        );

        let client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .unwrap();

        let url = server.url("/").to_string();
        let (final_url, chain, _) = resolve_redirect_chain(&url, 10, &client, true)
            .await
            .unwrap();

        assert_eq!(final_url, url);
        assert_eq!(chain.len(), 1);
        assert_eq!(chain[0].0, url);
    }

    #[tokio::test]
    async fn test_resolve_redirect_chain_single_redirect() {
        let server = Server::run();
        let final_url = server.url("/final").to_string();

        server.expect(
            Expectation::matching(request::method_path("GET", "/")).respond_with(
                status_code(302)
                    .insert_header("Location", final_url.as_str())
                    .body("Redirect"),
            ),
        );
        server.expect(
            Expectation::matching(request::method_path("GET", "/final"))
                .respond_with(status_code(200).body("OK")),
        );

        let client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .unwrap();

        let start_url = server.url("/").to_string();
        let (result_final, chain, _) = resolve_redirect_chain(&start_url, 10, &client, true)
            .await
            .unwrap();

        assert_eq!(result_final, final_url);
        assert_eq!(chain.len(), 2);
        assert_eq!(chain[0].0, start_url);
        assert_eq!(chain[1].0, final_url);
    }

    #[tokio::test]
    async fn test_resolve_redirect_chain_max_hops() {
        let server = Server::run();
        let url1 = server.url("/1").to_string();
        let url2 = server.url("/2").to_string();

        server.expect(
            Expectation::matching(request::method_path("GET", "/")).respond_with(
                status_code(302)
                    .insert_header("Location", url1.as_str())
                    .body("Redirect"),
            ),
        );
        server.expect(
            Expectation::matching(request::method_path("GET", "/1")).respond_with(
                status_code(302)
                    .insert_header("Location", url2.as_str())
                    .body("Redirect"),
            ),
        );

        let client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .unwrap();

        let start_url = server.url("/").to_string();
        // Max hops = 2, so we do 2 iterations:
        // Iteration 0: Add start_url, request, redirect to url1, current = url1, last_fetched_url = start_url
        // Iteration 1: Add url1, request, redirect to url2, but we're at max_hops-1, so we break
        // Result: chain has 2 URLs (start_url, url1), final = url1 (the last URL we actually fetched)
        // We do NOT return url2 because we never fetched it - we hit the redirect limit
        let (result_final, chain, _) = resolve_redirect_chain(&start_url, 2, &client, true)
            .await
            .unwrap();

        assert_eq!(chain.len(), 2);
        assert_eq!(chain[0].0, start_url);
        assert_eq!(chain[1].0, url1);
        // Final URL should be url1 (last URL we actually fetched), not url2 (which we never fetched)
        assert_eq!(result_final, url1);
    }

    #[tokio::test]
    async fn test_resolve_redirect_chain_max_hops_zero() {
        let client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .unwrap();

        let result = resolve_redirect_chain("https://example.com", 0, &client, true).await;
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("max_hops must be > 0"));
    }

    #[tokio::test]
    async fn test_resolve_redirect_chain_relative_location() {
        let server = Server::run();
        let final_url = server.url("/final").to_string();

        server.expect(
            Expectation::matching(request::method_path("GET", "/start")).respond_with(
                status_code(302)
                    .insert_header("Location", "/final") // Relative URL
                    .body("Redirect"),
            ),
        );
        server.expect(
            Expectation::matching(request::method_path("GET", "/final"))
                .respond_with(status_code(200).body("OK")),
        );

        let client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .unwrap();

        let start_url = server.url("/start").to_string();
        let (result_final, chain, _) = resolve_redirect_chain(&start_url, 10, &client, true)
            .await
            .unwrap();

        assert_eq!(result_final, final_url);
        assert_eq!(chain.len(), 2);
        assert_eq!(chain[0].0, start_url);
        assert_eq!(chain[1].0, final_url);
    }

    #[tokio::test]
    async fn test_resolve_redirect_chain_redirect_without_location() {
        let server = Server::run();

        server.expect(
            Expectation::matching(request::method_path("GET", "/"))
                .respond_with(status_code(302).body("Redirect but no Location")),
        );

        let client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .unwrap();

        let start_url = server.url("/").to_string();
        // Should break out of loop when redirect status but no Location header
        let (result_final, chain, _) = resolve_redirect_chain(&start_url, 10, &client, true)
            .await
            .unwrap();

        // Should include the start URL in chain, but not follow redirect
        assert_eq!(chain.len(), 1);
        assert_eq!(chain[0].0, start_url);
        assert_eq!(result_final, start_url);
    }

    #[tokio::test]
    async fn test_resolve_redirect_chain_different_redirect_codes() {
        let server = Server::run();
        let final_url = server.url("/final").to_string();

        // Test 301 (Moved Permanently)
        server.expect(
            Expectation::matching(request::method_path("GET", "/301")).respond_with(
                status_code(301)
                    .insert_header("Location", final_url.as_str())
                    .body("Moved"),
            ),
        );
        server.expect(
            Expectation::matching(request::method_path("GET", "/final"))
                .respond_with(status_code(200).body("OK")),
        );

        let client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .unwrap();

        let start_url = server.url("/301").to_string();
        let (result_final, chain, _) = resolve_redirect_chain(&start_url, 10, &client, true)
            .await
            .unwrap();

        assert_eq!(result_final, final_url);
        assert_eq!(chain.len(), 2);
    }

    #[tokio::test]
    async fn test_resolve_redirect_chain_invalid_utf8_location() {
        // Test handling of invalid UTF-8 in Location header
        // This tests the edge case where Location header contains invalid UTF-8
        let server = Server::run();

        server.expect(
            Expectation::matching(request::method_path("GET", "/"))
                .respond_with(status_code(302).body("Redirect")),
            // Note: httptest doesn't easily support invalid UTF-8 headers,
            // but we test the logic path that handles this case
        );

        let client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .unwrap();

        let start_url = server.url("/").to_string();
        // Should handle gracefully - if no Location header or invalid, should break loop
        let (result_final, chain, _) = resolve_redirect_chain(&start_url, 10, &client, true)
            .await
            .unwrap();

        // Should return the start URL since no valid redirect was found
        assert_eq!(chain.len(), 1);
        assert_eq!(result_final, start_url);
    }

    #[tokio::test]
    async fn test_resolve_redirect_chain_rejects_unsafe_initial_url() {
        // SSRF: initial URL must be validated before any request. IP literals bypass DNS/SafeResolver.
        let client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .unwrap();

        let result = resolve_redirect_chain("http://169.254.169.254", 10, &client, true).await;
        assert!(
            result.is_err(),
            "Initial link-local URL must be rejected before any request"
        );
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("169.254") || err.contains("Unsafe") || err.contains("private"),
            "Error should mention unsafe/private URL: {}",
            err
        );
    }

    #[tokio::test]
    async fn test_resolve_redirect_chain_network_error() {
        // Test handling of network errors during redirect resolution
        // Use an invalid URL that will fail to connect
        let client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .timeout(std::time::Duration::from_millis(100))
            .build()
            .unwrap();

        // Use a URL that will timeout or fail to connect
        let invalid_url = "http://192.0.2.0:9999/invalid"; // RFC 5737 test address, should fail
        let result = resolve_redirect_chain(invalid_url, 10, &client, true).await;

        // Should return an error (network failure)
        assert!(result.is_err(), "Network error should return error");
    }

    #[tokio::test]
    async fn test_resolve_redirect_chain_all_redirect_codes() {
        // Test all redirect status codes: 301, 302, 303, 307, 308
        // Test each code separately to avoid httptest expectation conflicts
        let codes = [301, 302, 303, 307, 308];

        for code in codes {
            let server = Server::run();
            let final_url = server.url("/final").to_string();

            server.expect(
                Expectation::matching(request::method_path("GET", "/start")).respond_with(
                    status_code(code)
                        .insert_header("Location", final_url.as_str())
                        .body("Redirect"),
                ),
            );
            server.expect(
                Expectation::matching(request::method_path("GET", "/final"))
                    .respond_with(status_code(200).body("OK")),
            );

            let client = reqwest::Client::builder()
                .redirect(reqwest::redirect::Policy::none())
                .build()
                .unwrap();

            let start_url = server.url("/start").to_string();
            let (result_final, chain, _) = resolve_redirect_chain(&start_url, 10, &client, true)
                .await
                .unwrap();

            assert_eq!(
                result_final, final_url,
                "Redirect code {} should work",
                code
            );
            assert_eq!(
                chain.len(),
                2,
                "Redirect code {} should have 2 URLs in chain",
                code
            );
        }
    }

    #[tokio::test]
    async fn test_resolve_redirect_chain_relative_location_edge_cases() {
        // Test relative location header (should resolve relative to current URL)
        let server = Server::run();
        let base_url = server.url("/base/path").to_string();
        // Relative "../final" from "/base/path" should resolve to "/final"
        let final_url = server.url("/final").to_string();

        // Test relative path (should resolve relative to current path)
        server.expect(
            Expectation::matching(request::method_path("GET", "/base/path")).respond_with(
                status_code(302)
                    .insert_header("Location", "../final") // Relative path
                    .body("Redirect"),
            ),
        );
        server.expect(
            Expectation::matching(request::method_path("GET", "/final"))
                .respond_with(status_code(200).body("OK")),
        );

        let client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .unwrap();

        let (result_final, chain, _) = resolve_redirect_chain(&base_url, 10, &client, true)
            .await
            .unwrap();

        assert_eq!(result_final, final_url);
        assert_eq!(chain.len(), 2);
    }

    #[tokio::test]
    async fn test_resolve_redirect_chain_blocks_private_ip() {
        // Test that redirects to private IPs are blocked (SSRF protection).
        // Uses an RFC 1918 IP (10.0.0.1) rather than 127.0.0.1, because 127.0.0.1 is
        // a loopback address and the cfg(test) bypass intentionally allows loopback
        // targets so httptest fixtures keep working. Loopback has a dedicated test
        // (test_resolve_redirect_chain_blocks_localhost) covering the "localhost"
        // domain path.
        let server = Server::run();
        let start_url = server.url("/").to_string();

        server.expect(
            Expectation::matching(request::method_path("GET", "/")).respond_with(
                status_code(302)
                    .insert_header("Location", "http://10.0.0.1:8080")
                    .body("Redirect to private IP"),
            ),
        );

        let client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .unwrap();

        let (result_final, chain, _) = resolve_redirect_chain(&start_url, 10, &client, true)
            .await
            .unwrap();

        // Should stop at the start URL, not follow redirect to private IP
        assert_eq!(result_final, start_url);
        assert_eq!(chain.len(), 1);
        assert_eq!(chain[0].0, start_url);
    }

    #[tokio::test]
    async fn test_resolve_redirect_chain_blocks_localhost() {
        // Test that redirects to localhost are blocked (SSRF protection)
        let server = Server::run();
        let start_url = server.url("/").to_string();

        server.expect(
            Expectation::matching(request::method_path("GET", "/")).respond_with(
                status_code(302)
                    .insert_header("Location", "http://localhost:8080")
                    .body("Redirect to localhost"),
            ),
        );

        let client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .unwrap();

        let (result_final, chain, _) = resolve_redirect_chain(&start_url, 10, &client, true)
            .await
            .unwrap();

        // Should stop at the start URL, not follow redirect to localhost
        assert_eq!(result_final, start_url);
        assert_eq!(chain.len(), 1);
    }

    #[tokio::test]
    async fn test_resolve_redirect_chain_blocks_unsafe_scheme() {
        // Test that redirects to unsafe schemes (file://, etc.) are blocked
        let server = Server::run();
        let start_url = server.url("/").to_string();

        server.expect(
            Expectation::matching(request::method_path("GET", "/")).respond_with(
                status_code(302)
                    .insert_header("Location", "file:///etc/passwd")
                    .body("Redirect to file://"),
            ),
        );

        let client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .unwrap();

        let (result_final, chain, _) = resolve_redirect_chain(&start_url, 10, &client, true)
            .await
            .unwrap();

        // Should stop at the start URL, not follow redirect to file://
        assert_eq!(result_final, start_url);
        assert_eq!(chain.len(), 1);
    }

    #[tokio::test]
    async fn test_resolve_redirect_chain_allows_public_urls() {
        // Test that redirects to public URLs are allowed
        let server = Server::run();
        let start_url = server.url("/").to_string();
        let final_url = server.url("/final").to_string();

        server.expect(
            Expectation::matching(request::method_path("GET", "/")).respond_with(
                status_code(302)
                    .insert_header("Location", final_url.as_str())
                    .body("Redirect"),
            ),
        );
        server.expect(
            Expectation::matching(request::method_path("GET", "/final"))
                .respond_with(status_code(200).body("OK")),
        );

        let client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .unwrap();

        let (result_final, chain, _) = resolve_redirect_chain(&start_url, 10, &client, true)
            .await
            .unwrap();

        // Should follow redirect to public URL
        assert_eq!(result_final, final_url);
        assert_eq!(chain.len(), 2);
    }

    #[tokio::test]
    async fn test_resolve_redirect_chain_circular_redirect() {
        // Test circular redirect: A -> B -> A (should stop at max_hops, not loop infinitely)
        let server = Server::run();
        let url_a = server.url("/a").to_string();
        let url_b = server.url("/b").to_string();

        // A redirects to B (will be called multiple times in circular redirect)
        server.expect(
            Expectation::matching(request::method_path("GET", "/a"))
                .times(3) // A will be fetched: initial, then after B->A redirects (twice more)
                .respond_with(
                    status_code(302)
                        .insert_header("Location", url_b.as_str())
                        .body("Redirect to B"),
                ),
        );

        // B redirects back to A (circular) - will be called twice
        server.expect(
            Expectation::matching(request::method_path("GET", "/b"))
                .times(2) // B will be fetched twice: A->B, then A->B again
                .respond_with(
                    status_code(302)
                        .insert_header("Location", url_a.as_str())
                        .body("Redirect to A"),
                ),
        );

        let client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .unwrap();

        // With max_hops=5, should stop after 5 hops (A -> B -> A -> B -> A)
        let (result_final, chain, _) = resolve_redirect_chain(&url_a, 5, &client, true)
            .await
            .unwrap();

        // Should stop at max_hops, not loop infinitely
        // Chain should contain: [A, B, A, B, A] (5 hops)
        assert_eq!(chain.len(), 5);
        // Final URL should be the last URL we actually fetched (A, since we stop at max_hops)
        assert_eq!(result_final, url_a);
    }

    #[tokio::test]
    async fn test_resolve_redirect_chain_max_hops_one() {
        // Test edge case: max_hops = 1 (should fetch start URL, not follow any redirects)
        let server = Server::run();
        let start_url = server.url("/").to_string();
        let redirect_url = server.url("/redirect").to_string();

        server.expect(
            Expectation::matching(request::method_path("GET", "/")).respond_with(
                status_code(302)
                    .insert_header("Location", redirect_url.as_str())
                    .body("Redirect"),
            ),
        );

        let client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .unwrap();

        let (result_final, chain, _) = resolve_redirect_chain(&start_url, 1, &client, true)
            .await
            .unwrap();

        // With max_hops=1, should only fetch start URL, not follow redirect
        assert_eq!(chain.len(), 1);
        assert_eq!(result_final, start_url);
        // Should NOT include redirect_url in chain
        assert!(!chain.iter().any(|(url, _)| url == &redirect_url));
    }

    // --- validate_redirect_target unit tests ------------------------------------------------
    //
    // These exercise the two SSRF/downgrade guards directly (deterministic; no httptest
    // server needed). The redirect-chain integration tests above prove the helper is wired
    // into the loop.

    #[test]
    fn test_validate_redirect_target_blocks_https_to_http_downgrade() {
        // Chain started on HTTPS; an http hop must be rejected even on a "safe" public host.
        let err = validate_redirect_target("http://example.com/login", "http", true, false)
            .expect_err("https chain must reject http hop");
        let msg = err.to_string();
        assert!(
            msg.contains("downgrade"),
            "expected downgrade message, got: {msg}"
        );
    }

    #[test]
    fn test_validate_redirect_target_blocks_https_to_http_same_host_downgrade() {
        // Same hostname; the previous design skipped validation here. Confirm we still
        // reject the downgrade.
        validate_redirect_target("http://example.com/", "http", true, false)
            .expect_err("same-host https->http downgrade must be rejected");
    }

    #[test]
    fn test_validate_redirect_target_allows_https_to_https() {
        validate_redirect_target("https://example.com/next", "https", true, false)
            .expect("https->https hop must be allowed");
    }

    #[test]
    fn test_validate_redirect_target_allows_http_to_http_when_chain_started_http() {
        validate_redirect_target("http://example.com/next", "http", false, false)
            .expect("http chain may continue on http");
    }

    #[test]
    fn test_validate_redirect_target_blocks_private_ip_target() {
        // Same host as the start (e.g. DNS rebinding window) is no longer a free pass:
        // a private/link-local IP literal in the redirect Location is rejected on every hop.
        // Note: we deliberately don't include loopback IPs (127.0.0.1, ::1) here because
        // the test-loopback bypass intentionally allows them so httptest fixtures keep
        // working. Production behaviour for non-loopback private IPs is what matters.
        for url in [
            "http://10.0.0.1/",
            "http://192.168.1.1/",
            "http://169.254.169.254/", // cloud metadata
            "http://172.16.0.1/",
        ] {
            let err = match validate_redirect_target(url, "http", false, false) {
                Ok(()) => panic!("private IP {url} must be rejected"),
                Err(e) => e,
            };
            assert!(
                !err.to_string().contains("downgrade"),
                "expected SSRF rejection for {url}, got downgrade message: {err}"
            );
        }
    }

    #[test]
    fn test_validate_redirect_target_blocks_unsafe_scheme() {
        // file:// must be rejected even when chain didn't start on https.
        // (The loopback-test bypass only fires on http(s) loopback URLs.)
        validate_redirect_target("file:///etc/passwd", "file", false, false)
            .expect_err("file:// must be rejected by validate_url_safe");
    }

    // Removed: a previous test claimed to exercise the invalid-UTF-8 Location
    // path, but as the comments admitted, httptest sanitizes such headers, so it
    // really only exercised "302 with a valid relative Location" — which is
    // already covered by `test_resolve_redirect_chain_relative_location`. The
    // invalid-UTF-8 break in `resolve_redirect_chain` is exercised at the
    // header-decode level by `reqwest`'s own header tests.
}