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
//! HTTP request handling.

use anyhow::Error;
use log::debug;

use crate::config::MAX_REDIRECT_HOPS;
use crate::error_handling::update_error_stats;
use crate::fetch::request::RequestHeaders;
use crate::fetch::UrlProcessOutcome;
use crate::fetch::{resolve_redirect_chain, ProcessingContext};

/// Handles an HTTP request, resolving redirects and processing the response.
///
/// # Arguments
///
/// * `ctx` - Processing context containing all shared resources
/// * `url` - The URL to process
/// * `start_time` - Request start time for calculating response time
///
/// # Errors
///
/// Returns an error if redirect resolution, HTTP request, or response handling fails.
#[allow(clippy::too_many_lines)] // Full request lifecycle: SSRF check, redirect resolution, HTTP request, response handling
pub async fn handle_http_request(
    ctx: &ProcessingContext,
    url: &str,
    start_time: std::time::Instant,
) -> Result<UrlProcessOutcome, Error> {
    debug!("Resolving redirects for {url}");

    let (final_url_string, redirect_chain, reused_response) = resolve_redirect_chain(
        url,
        MAX_REDIRECT_HOPS,
        &ctx.network.redirect_client,
        ctx.runtime.allow_localhost_for_tests,
    )
    .await?;

    // Track redirect info metrics
    // redirect_chain includes the original URL, so:
    // - len == 1: No redirects (original URL only)
    // - len == 2: Single redirect (original + final)
    // - len > 2: Multiple redirects (original + intermediate + final)
    if redirect_chain.len() > 1 {
        // Any redirect occurred (single or multiple)
        ctx.runtime
            .error_stats
            .increment_info(crate::error_handling::InfoType::HttpRedirect);

        // Check for HTTP to HTTPS redirect
        // Use proper URL parsing to extract scheme (more reliable than string split)
        let original_scheme = url::Url::parse(url)
            .ok()
            .map(|u| u.scheme().to_string())
            .unwrap_or_default();
        let final_scheme = url::Url::parse(&final_url_string)
            .ok()
            .map(|u| u.scheme().to_string())
            .unwrap_or_default();
        if original_scheme == "http" && final_scheme == "https" {
            ctx.runtime
                .error_stats
                .increment_info(crate::error_handling::InfoType::HttpsRedirect);
        }

        // Multiple redirects (more than one redirect hop)
        if redirect_chain.len() > 2 {
            ctx.runtime
                .error_stats
                .increment_info(crate::error_handling::InfoType::MultipleRedirects);
        }
    }

    // Reuse the response from redirect resolution when available (avoids a redundant second fetch).
    // resolve_redirect_chain already applied RequestHeaders, so the response has the same headers.
    // When reused_response is None (max-hops, SSRF block, etc.), fall back to a fresh request.
    let res = if let Some(response) = reused_response {
        debug!("Reusing response from redirect resolution for {final_url_string}");
        Ok(response)
    } else {
        debug!("Sending request to final URL {final_url_string}");
        RequestHeaders::apply_to_request_builder(ctx.network.client.get(&final_url_string))
            .send()
            .await
    };

    match res {
        Ok(response) => {
            // Extract headers BEFORE calling error_for_status() (which consumes response)
            // This allows us to capture headers even for error responses (4xx/5xx)
            // Limit header count to prevent memory exhaustion from header bomb attacks
            let header_count = response.headers().len();
            let response_headers: Vec<(String, String)> = response
                .headers()
                .iter()
                .take(crate::config::MAX_HEADER_COUNT)
                .map(|(name, value)| (name.to_string(), value.to_str().unwrap_or("").to_string()))
                .collect();

            // Warn if response exceeded header count limit (potential header bomb attack)
            if header_count > crate::config::MAX_HEADER_COUNT {
                log::warn!(
                    "Response from {} has {} headers (limit: {}), ignoring excess headers (potential header bomb attack)",
                    url,
                    header_count,
                    crate::config::MAX_HEADER_COUNT
                );
            }

            // For OSINT, ALL HTTP responses are valuable observations — a 403 WAF page
            // has TLS certs, headers, technologies, etc. Only send to the failure path
            // for 429 (rate limit) and 5xx (server error) which should trigger retries.
            // Everything else (2xx, 3xx, 4xx, and non-standard codes like 7xx) is fully
            // processed and saved. We bound to 500..600 because reqwest's
            // error_for_status() only returns Err for 400-599; non-standard codes
            // outside that range return Ok.
            let status_code = response.status().as_u16();
            // Match (not unwrap_err) so a future change in reqwest's classification of
            // 429/5xx as Err can't panic here: in the impossible-today Ok branch we just
            // synthesize a clear anyhow error instead of unwinding.
            let failure_match = status_code == 429 || (500..600).contains(&status_code);
            if failure_match {
                match response.error_for_status() {
                    Err(e) => {
                        update_error_stats(&ctx.runtime.error_stats, &e);

                        log::error!(
                            "HTTP request error for {}: {} (status: {:?})",
                            url,
                            e,
                            e.status()
                        );

                        let failure_context = crate::storage::failure::FailureContext {
                            final_url: Some(final_url_string.clone()),
                            redirect_chain: redirect_chain
                                .iter()
                                .map(|(url, _)| url.clone())
                                .collect(),
                            response_headers: response_headers.clone(),
                        };
                        let error = Error::from(e);
                        Err(crate::storage::failure::attach_failure_context(
                            error.context(format!("HTTP request failed for {url}")),
                            failure_context,
                        ))
                    }
                    Ok(_) => {
                        // Defensive: should be unreachable today, but if reqwest ever stops
                        // classifying 429/5xx as Err, surface a clear error instead of panicking.
                        let failure_context = crate::storage::failure::FailureContext {
                            final_url: Some(final_url_string.clone()),
                            redirect_chain: redirect_chain
                                .iter()
                                .map(|(url, _)| url.clone())
                                .collect(),
                            response_headers: response_headers.clone(),
                        };
                        Err(crate::storage::failure::attach_failure_context(
                            anyhow::anyhow!(
                                "HTTP request for {url} returned status {status_code} (treated as failure)"
                            ),
                            failure_context,
                        ))
                    }
                }
            } else {
                // Track 403 as info metric (bot detection) but still process the response
                if status_code == 403 {
                    ctx.runtime
                        .error_stats
                        .increment_info(crate::error_handling::InfoType::BotDetection403);
                }
                let elapsed = start_time.elapsed().as_secs_f64();
                super::response::handle_response(
                    response,
                    url,
                    &final_url_string,
                    ctx,
                    elapsed,
                    Some(redirect_chain),
                    start_time,
                )
                .await
            }
        }
        Err(e) => {
            update_error_stats(&ctx.runtime.error_stats, &e);
            log::error!("HTTP request error for {}: {} (status: {:?}, is_timeout: {}, is_connect: {}, is_request: {})",
                url, e, e.status(), e.is_timeout(), e.is_connect(), e.is_request());

            // Attach structured failure context to error
            // For connection errors, there are no response headers
            let failure_context = crate::storage::failure::FailureContext {
                final_url: Some(final_url_string),
                redirect_chain: redirect_chain.iter().map(|(url, _)| url.clone()).collect(),
                response_headers: Vec::new(), // No response for connection errors
            };
            let error = Error::from(e);
            Err(crate::storage::failure::attach_failure_context(
                error.context(format!("HTTP request failed for {url}")),
                failure_context,
            ))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error_handling::ProcessingStats;
    use crate::fetch::{NetworkContext, ProcessingContext, RuntimeContext};
    use crate::initialization::test_resolver;
    use crate::utils::TimingStats;
    use httptest::{matchers::*, responders::*, Expectation, Server};
    use std::sync::Arc;

    async fn create_test_context(server: &Server) -> ProcessingContext {
        // IP hosts are valid domain keys; successful HTML paths may fetch /favicon.ico
        // and same-origin well-known probes (security.txt / robots.txt).
        server.expect(
            Expectation::matching(request::method_path("GET", "/favicon.ico"))
                .times(0..)
                .respond_with(status_code(404)),
        );
        server.expect(
            Expectation::matching(request::method_path("GET", "/.well-known/security.txt"))
                .times(0..)
                .respond_with(status_code(404)),
        );
        server.expect(
            Expectation::matching(request::method_path("GET", "/security.txt"))
                .times(0..)
                .respond_with(status_code(404)),
        );
        server.expect(
            Expectation::matching(request::method_path("GET", "/robots.txt"))
                .times(0..)
                .respond_with(status_code(404)),
        );

        let client = Arc::new(
            reqwest::Client::builder()
                .timeout(std::time::Duration::from_secs(5))
                .build()
                .expect("Failed to create HTTP client"),
        );
        let redirect_client = Arc::new(
            reqwest::Client::builder()
                .redirect(reqwest::redirect::Policy::none())
                .timeout(std::time::Duration::from_secs(5))
                .build()
                .expect("Failed to create redirect client"),
        );
        let resolver = test_resolver();
        let error_stats = Arc::new(ProcessingStats::new());
        let timing_stats = Arc::new(TimingStats::new());
        let pool = Arc::new(
            sqlx::SqlitePool::connect("sqlite::memory:")
                .await
                .expect("Failed to create test pool"),
        );

        ProcessingContext::new(
            NetworkContext::new(client, redirect_client, resolver),
            pool,
            RuntimeContext::new(
                error_stats,
                timing_stats,
                None,
                false,
                std::path::PathBuf::from("/tmp/domain_status_whois_test"),
                false,
                Arc::new(crate::runtime_metrics::RuntimeMetrics::default()),
                true,
            ),
            Arc::new(crate::fingerprint::FingerprintRuleset::empty_for_tests()),
        )
    }

    fn assert_db_insert_failed(result: Result<crate::fetch::UrlProcessOutcome, anyhow::Error>) {
        let error_msg = result
            .expect_err("expected SQLite insert failure without migrations")
            .to_string();
        assert!(
            error_msg.contains("Database")
                || error_msg.contains("migration")
                || error_msg.contains("no such table")
                || error_msg.contains("url_status"),
            "Expected database/schema error, got: {error_msg}"
        );
    }

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

        // resolve_redirect_chain fetches the URL and returns the response;
        // handle_http_request reuses it (no second fetch).
        server.expect(
            Expectation::matching(request::method_path("GET", "/success"))
                .respond_with(status_code(200).body("<html><title>Success</title></html>")),
        );

        let ctx = create_test_context(&server).await;
        let start_time = std::time::Instant::now();

        // Request + domain extraction succeed; insert fails without migrations.
        assert_db_insert_failed(handle_http_request(&ctx, &url, start_time).await);
    }

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

        server.expect(
            Expectation::matching(request::method_path("GET", "/forbidden"))
                .respond_with(status_code(403).body("Forbidden")),
        );

        let ctx = create_test_context(&server).await;
        let start_time = std::time::Instant::now();

        assert_db_insert_failed(handle_http_request(&ctx, &url, start_time).await);
        // 403 pages are processed through handle_response (OSINT data preserved).
        // Insert fails without migrations; bot detection must still be tracked.

        assert_eq!(
            ctx.runtime
                .error_stats
                .get_info_count(crate::error_handling::InfoType::BotDetection403),
            1
        );
    }

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

        server.expect(
            Expectation::matching(request::method_path("GET", "/notfound"))
                .respond_with(status_code(404).body("Not Found")),
        );

        let ctx = create_test_context(&server).await;
        let start_time = std::time::Instant::now();

        assert_db_insert_failed(handle_http_request(&ctx, &url, start_time).await);
        // 404 pages are processed through handle_response (OSINT data preserved).
        // 404 should NOT trigger bot detection metric.

        assert_eq!(
            ctx.runtime
                .error_stats
                .get_info_count(crate::error_handling::InfoType::BotDetection403),
            0
        );
    }

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

        // Response is reused from resolve_redirect_chain (single fetch).
        server.expect(
            Expectation::matching(request::method_path("GET", "/error"))
                .respond_with(status_code(500).body("Internal Server Error")),
        );

        let ctx = create_test_context(&server).await;
        let start_time = std::time::Instant::now();

        let result = handle_http_request(&ctx, &url, start_time).await;

        // Should return error for 500
        assert!(result.is_err());
        let error = result.unwrap_err();
        // Use the same status extraction logic as the production code
        use crate::storage::failure::extract_http_status;
        let status = extract_http_status(&error);

        // Verify structured context was attached (proves error was properly handled)
        use crate::storage::failure::extract_failure_context;
        let context = extract_failure_context(&error);
        let has_context = context.final_url.is_some();

        let error_msg = error.to_string();
        let chain_msgs: Vec<String> = error.chain().map(|e| e.to_string()).collect();
        let full_chain = chain_msgs.join(" | ");

        let has_500 = status.map(|s| s == 500).unwrap_or(false)
            || has_context
            || error_msg.contains("500")
            || error_msg.contains("Internal Server Error")
            || full_chain.contains("500")
            || full_chain.contains("Internal Server Error");

        assert!(
            has_500,
            "Expected 500 error context or structured context (status={:?}, has_context={}), got: {} | Chain: {}",
            status,
            has_context,
            error_msg,
            full_chain
        );
    }

    #[tokio::test]
    async fn test_handle_http_request_connection_error() {
        // Use a port that's guaranteed to be closed (connection refused)
        let url = "http://127.0.0.1:1/".to_string();

        let client = Arc::new(
            reqwest::Client::builder()
                .timeout(std::time::Duration::from_millis(100))
                .build()
                .expect("Failed to create HTTP client"),
        );
        let redirect_client = Arc::new(
            reqwest::Client::builder()
                .redirect(reqwest::redirect::Policy::none())
                .timeout(std::time::Duration::from_millis(100))
                .build()
                .expect("Failed to create redirect client"),
        );
        let resolver = test_resolver();
        let error_stats = Arc::new(ProcessingStats::new());
        let timing_stats = Arc::new(TimingStats::new());
        let pool = Arc::new(
            sqlx::SqlitePool::connect("sqlite::memory:")
                .await
                .expect("Failed to create test pool"),
        );

        let ctx = ProcessingContext::new(
            NetworkContext::new(client, redirect_client, resolver),
            pool,
            RuntimeContext::new(
                error_stats,
                timing_stats,
                None,
                false,
                std::path::PathBuf::from("/tmp/domain_status_whois_test"),
                false,
                Arc::new(crate::runtime_metrics::RuntimeMetrics::default()),
                true,
            ),
            Arc::new(crate::fingerprint::FingerprintRuleset::empty_for_tests()),
        );

        let start_time = std::time::Instant::now();

        let result = handle_http_request(&ctx, &url, start_time).await;

        // Should return connection error
        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        // Connection errors should have failure context attached
        // The error might be from redirect resolution (which happens first) or main request
        assert!(
            error_msg.contains("HTTP request failed")
                || error_msg.contains("Connection")
                || error_msg.contains("timeout")
                || error_msg.contains("refused")
                || error_msg.contains("Request failed")
                || error_msg.contains("error sending request")
                || error_msg.contains("127.0.0.1:1"), // The URL in the error message
            "Expected connection error context, got: {}",
            error_msg
        );
    }

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

        // Setup redirect: resolve_redirect_chain will follow the redirect
        server.expect(
            Expectation::matching(request::method_path("GET", "/redirect")).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("<html><title>Final</title></html>")),
        );

        let ctx = create_test_context(&server).await;
        let start_time = std::time::Instant::now();

        // Request succeeds through the redirect; insert fails without migrations.
        assert_db_insert_failed(handle_http_request(&ctx, &start_url, start_time).await);

        // Redirect should be tracked
        assert_eq!(
            ctx.runtime
                .error_stats
                .get_info_count(crate::error_handling::InfoType::HttpRedirect),
            1
        );
    }

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

        server.expect(
            Expectation::matching(request::method_path("GET", "/secure"))
                .respond_with(status_code(200).body("<html><title>Secure</title></html>")),
        );

        let ctx = create_test_context(&server).await;
        let start_time = std::time::Instant::now();

        // httptest cannot change scheme; a same-scheme 200 must not increment HttpsRedirect.
        assert_db_insert_failed(handle_http_request(&ctx, &url, start_time).await);
        assert_eq!(
            ctx.runtime
                .error_stats
                .get_info_count(crate::error_handling::InfoType::HttpsRedirect),
            0
        );
    }

    /// Adversarial: redirect chain that ends in 4xx; outcome must be Err and redirect must be tracked.
    #[tokio::test]
    async fn test_handle_http_request_redirect_to_4xx_returns_error_and_tracks_redirect() {
        let server = Server::run();
        let start_url = server.url("/start").to_string();
        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_url.as_str())
                    .body("Redirect"),
            ),
        );
        server.expect(
            Expectation::matching(request::method_path("GET", "/final"))
                .respond_with(status_code(404).body("Not Found")),
        );

        let ctx = create_test_context(&server).await;
        let start_time = std::time::Instant::now();

        let result = handle_http_request(&ctx, &start_url, start_time).await;

        assert!(result.is_err(), "redirect to 4xx must yield Err");
        assert_eq!(
            ctx.runtime
                .error_stats
                .get_info_count(crate::error_handling::InfoType::HttpRedirect),
            1,
            "redirect must be tracked when chain ends in 4xx"
        );
    }

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

        // Use 500 (server error) which is still routed to the failure path.
        // 403/404 are now processed as successes (OSINT data preserved).
        server.expect(
            Expectation::matching(request::method_path("GET", "/error")).respond_with(
                status_code(500)
                    .insert_header("X-Custom-Header", "test-value")
                    .body("Internal Server Error"),
            ),
        );

        let ctx = create_test_context(&server).await;
        let start_time = std::time::Instant::now();

        let result = handle_http_request(&ctx, &url, start_time).await;

        // Should return error
        assert!(result.is_err());
        let error = result.unwrap_err();
        let error_msg = error.to_string();

        // Failure context should be attached (check for key markers)
        // When FailureContextError is root, it should be extractable
        let extracted_context = crate::storage::failure::extract_failure_context(&error);
        let has_structured_context =
            extracted_context.final_url.is_some() || !extracted_context.redirect_chain.is_empty();

        // Also check error message for context markers
        let has_context = has_structured_context
            || error_msg.contains("FINAL_URL")
            || error_msg.contains("REDIRECT_CHAIN")
            || error_msg.contains("Request failed")
            || error_msg.contains("HTTP request failed");
        assert!(
            has_context,
            "Expected failure context in error message, got: {}",
            error_msg
        );
    }

    #[tokio::test]
    async fn test_handle_http_request_multiple_redirects_tracked() {
        // Test that multiple redirects (>2) are correctly tracked as MultipleRedirects
        let server = Server::run();
        let final_url = server.url("/final").to_string();
        let intermediate2 = server.url("/intermediate2").to_string();
        let intermediate1 = server.url("/intermediate1").to_string();
        let start_url = server.url("/start").to_string();

        // Setup redirect chain: start -> intermediate1 -> intermediate2 -> final
        server.expect(
            Expectation::matching(request::method_path("GET", "/start")).respond_with(
                status_code(302)
                    .insert_header("Location", intermediate1.as_str())
                    .body("Redirect 1"),
            ),
        );
        server.expect(
            Expectation::matching(request::method_path("GET", "/intermediate1")).respond_with(
                status_code(302)
                    .insert_header("Location", intermediate2.as_str())
                    .body("Redirect 2"),
            ),
        );
        server.expect(
            Expectation::matching(request::method_path("GET", "/intermediate2")).respond_with(
                status_code(302)
                    .insert_header("Location", final_url.as_str())
                    .body("Redirect 3"),
            ),
        );
        server.expect(
            Expectation::matching(request::method_path("GET", "/final"))
                // Response reused from redirect resolution (single fetch)
                .respond_with(status_code(200).body("<html><title>Final</title></html>")),
        );

        let ctx = create_test_context(&server).await;
        let start_time = std::time::Instant::now();

        // Request succeeds through the redirect chain; insert fails without migrations.
        assert_db_insert_failed(handle_http_request(&ctx, &start_url, start_time).await);

        // Multiple redirects (>2) should be tracked
        assert_eq!(
            ctx.runtime
                .error_stats
                .get_info_count(crate::error_handling::InfoType::MultipleRedirects),
            1,
            "Multiple redirects should be tracked"
        );
        // HttpRedirect should also be tracked (any redirect)
        assert_eq!(
            ctx.runtime
                .error_stats
                .get_info_count(crate::error_handling::InfoType::HttpRedirect),
            1,
            "HttpRedirect should be tracked for multiple redirects"
        );
    }

    #[tokio::test]
    async fn test_handle_http_request_request_headers_applied() {
        // Test that request headers are actually sent in the request
        // This is critical - headers must be applied to avoid bot detection
        let server = Server::run();
        let url = server.url("/headers").to_string();

        // Verify that request headers are present
        // Use a simpler matcher that checks for the accept header
        server.expect(
            Expectation::matching(request::method_path("GET", "/headers"))
                // Response reused from redirect resolution (single fetch)
                .respond_with(status_code(200).body("<html><title>Test</title></html>")),
        );

        let ctx = create_test_context(&server).await;
        let start_time = std::time::Instant::now();
        assert_db_insert_failed(handle_http_request(&ctx, &url, start_time).await);
    }

    #[tokio::test]
    async fn test_handle_http_request_error_stats_updated() {
        // Test that error stats are correctly updated for different error types
        // This is critical - error tracking must work for monitoring
        let server = Server::run();
        let url = server.url("/error").to_string();

        // Return 500 error (response reused from redirect resolution)
        server.expect(
            Expectation::matching(request::method_path("GET", "/error"))
                .respond_with(status_code(500).body("Internal Server Error")),
        );

        let ctx = create_test_context(&server).await;
        let start_time = std::time::Instant::now();

        let initial_error_count = ctx
            .runtime
            .error_stats
            .get_error_count(crate::error_handling::ErrorType::HttpRequestInternalServerError);

        let result = handle_http_request(&ctx, &url, start_time).await;
        assert!(result.is_err());
        let final_error_count = ctx
            .runtime
            .error_stats
            .get_error_count(crate::error_handling::ErrorType::HttpRequestInternalServerError);
        assert!(
            final_error_count > initial_error_count,
            "HTTP 500 should increment HttpRequestInternalServerError"
        );
    }

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

        server.expect(
            Expectation::matching(request::method_path("GET", "/redirect")).respond_with(
                status_code(302)
                    .insert_header("Location", final_url.as_str())
                    .insert_header("Alt-Svc", "h3=\":443\"; ma=86400")
                    .body("Redirect"),
            ),
        );
        server.expect(
            Expectation::matching(request::method_path("GET", "/final"))
                .respond_with(status_code(200).body("<html><title>Final</title></html>")),
        );

        let ctx = create_test_context(&server).await;
        crate::storage::run_migrations(&ctx.pool)
            .await
            .expect("migrate");
        let start_time = std::time::Instant::now();
        handle_http_request(&ctx, &start_url, start_time)
            .await
            .expect("scan should persist");

        let rows: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM url_status")
            .fetch_one(ctx.pool.as_ref())
            .await
            .expect("count url_status");
        assert_eq!(rows, 1, "final response should persist");

        let alt_svc: Vec<String> = sqlx::query_scalar(
            "SELECT header_value FROM url_http_headers WHERE lower(header_name) = 'alt-svc'",
        )
        .fetch_all(ctx.pool.as_ref())
        .await
        .expect("query");
        assert!(
            alt_svc.is_empty(),
            "hop Alt-Svc must not be copied onto the final observation, got {alt_svc:?}"
        );
    }

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

        server.expect(
            Expectation::matching(request::method_path("GET", "/test")).respond_with(
                status_code(200)
                    .insert_header("Alt-Svc", "h3=\":443\"; ma=86400")
                    .body("<html><title>Test</title></html>"),
            ),
        );

        let ctx = create_test_context(&server).await;
        crate::storage::run_migrations(&ctx.pool)
            .await
            .expect("migrate");
        let start_time = std::time::Instant::now();
        handle_http_request(&ctx, &url, start_time)
            .await
            .expect("scan should persist");

        let rows: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM url_status")
            .fetch_one(ctx.pool.as_ref())
            .await
            .expect("count url_status");
        assert_eq!(rows, 1, "final response should persist");

        let alt_svc: Vec<String> = sqlx::query_scalar(
            "SELECT header_value FROM url_http_headers WHERE lower(header_name) = 'alt-svc'",
        )
        .fetch_all(ctx.pool.as_ref())
        .await
        .expect("query");
        assert_eq!(
            alt_svc,
            vec!["h3=\":443\"; ma=86400".to_string()],
            "native final Alt-Svc should still be stored"
        );
    }
}