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
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
//! HTTP response extraction utilities.

use anyhow::{Error, Result};
use log::debug;
use std::sync::Arc;

use super::types::ResponseData;
use crate::domain::extract_domain;
use crate::fetch::request::{extract_http_headers, extract_security_headers};
use crate::fetch::stream::{stream_bytes_with_limit, OnLimit, StreamedBytes};
use crate::utils::sha256_hex;

/// Computes SHA-256 hash of the body, returning hex-encoded string.
fn compute_body_sha256(body: &str) -> Option<String> {
    if body.is_empty() {
        return None;
    }
    Some(sha256_hex(body.as_bytes()))
}

/// Formats HTTP version from reqwest's Version enum.
fn format_http_version(version: reqwest::Version) -> String {
    match version {
        reqwest::Version::HTTP_09 => "HTTP/0.9".to_string(),
        reqwest::Version::HTTP_10 => "HTTP/1.0".to_string(),
        reqwest::Version::HTTP_11 => "HTTP/1.1".to_string(),
        reqwest::Version::HTTP_2 => "HTTP/2".to_string(),
        reqwest::Version::HTTP_3 => "HTTP/3".to_string(),
        other => format!("{other:?}"),
    }
}

/// Page-body decode with HTML `<meta charset>` sniffing enabled.
fn decode_body_with_charset(bytes: &[u8], content_type: Option<&str>) -> String {
    crate::fetch::charset::decode_body(bytes, content_type, true)
}

/// Decode a streamed body and set the scan-completeness truncation flag.
///
/// Truncated prefixes are still secret-scanned; `body_truncated` tells analysts
/// that content past the cap was never seen.
fn decode_streamed_body(
    streamed: StreamedBytes,
    content_type: Option<&str>,
    final_domain: &str,
) -> (String, bool) {
    match streamed {
        StreamedBytes::Complete(bytes) => (decode_body_with_charset(&bytes, content_type), false),
        StreamedBytes::Truncated(bytes) => {
            debug!("Body exceeded limit for {final_domain}, parsing truncated prefix");
            (decode_body_with_charset(&bytes, content_type), true)
        }
    }
}

/// Returns true if the Content-Type (lowercased, with optional `;` parameters)
/// is one we want to scan for secrets and extract metadata from.
///
/// Goal: catch text-shaped payloads that may carry exposed credentials —
/// JS bundles, JSON config endpoints, PWA manifests — without dragging in
/// binary or media types where the secret-detection regex set is meaningless.
fn is_scannable_content_type(ct_lower: &str) -> bool {
    // Strip any parameters (`text/html; charset=utf-8` -> `text/html`).
    let mime = ct_lower.split(';').next().unwrap_or("").trim();
    // text/* (covers text/html, text/plain, text/javascript, text/xml, text/css, ...)
    if mime.starts_with("text/") {
        return true;
    }
    // Specific application/* types
    matches!(
        mime,
        "application/xhtml+xml"
            | "application/javascript"
            | "application/ecmascript"
            | "application/x-javascript"
            | "application/json"
            | "application/manifest+json"
            | "application/ld+json"
            | "application/xml"
            | "application/atom+xml"
            | "application/rss+xml"
            | "application/soap+xml"
    ) || mime.ends_with("+json")
        || mime.ends_with("+xml")
}

/// Extracts and validates response data from an HTTP response.
///
/// # Arguments
///
/// * `response` - The HTTP response
/// * `original_url` - The original URL before redirects
/// * `_final_url_str` - The final URL after redirects
///
/// # Errors
///
/// Returns an error if domain extraction fails or response body cannot be read.
/// Returns `Ok(None)` if content-type is not scannable.
/// When body exceeds the size limit, returns `Ok(Some(ResponseData))` with the
/// truncated prefix (`body_truncated = true`) so secrets in the first
/// `MAX_RESPONSE_BODY_SIZE` bytes are still seen.
#[allow(clippy::too_many_lines)] // Extracts headers, body, domain, and security data from HTTP response in sequence
pub(crate) async fn extract_response_data(
    response: reqwest::Response,
    original_url: &str,
    _final_url_str: &str,
) -> Result<Option<ResponseData>, Error> {
    let final_url = response.url().to_string();
    debug!("Final url after redirects: {final_url}");

    let initial_domain = extract_domain(original_url)?;
    let final_domain = extract_domain(&final_url)?;
    debug!("Initial domain: {initial_domain}, Final domain: {final_domain}");

    let parsed_url = reqwest::Url::parse(&final_url)?;
    let host = parsed_url
        .host_str()
        .ok_or_else(|| anyhow::Error::msg("Failed to extract host"))?
        .to_string();

    let status = response.status();
    let status_desc = status
        .canonical_reason()
        .unwrap_or("Unknown Status Code")
        .to_string();

    // Extract headers and version before consuming response
    let headers = response.headers().clone();
    let http_version = Some(format_http_version(response.version()));

    // Extract Content-Type as standalone field
    let content_type = headers
        .get(reqwest::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .map(std::string::ToString::to_string);

    let security_headers = extract_security_headers(&headers);
    let http_headers = extract_http_headers(&headers);

    // Accept any text-shaped Content-Type for downstream secret detection +
    // metadata extraction. HTML-DOM extractors (title, meta, structured-data)
    // gracefully return empty on non-HTML bodies, so it's safe to run them on
    // JS/JSON/manifest payloads; the regex-based extractors (analytics IDs,
    // exposed secrets) genuinely benefit from being run there.
    //
    // Allowed (case-insensitive prefix match):
    //   text/*                            html, plain, css, csv, javascript, xml, ...
    //   application/xhtml+xml             XHTML
    //   application/javascript            JS bundles served correctly
    //   application/ecmascript            (rare) ECMAScript
    //   application/json + */*+json       config endpoints, manifests, JSON-LD
    //   application/manifest+json         PWA manifest
    //   application/xml                   XML feeds, soap, RSS
    //
    // Missing Content-Type: continue (servers sometimes omit it).
    if let Some(ct) = headers.get(reqwest::header::CONTENT_TYPE) {
        let ct_lc = ct.to_str().unwrap_or("").to_lowercase();
        if !is_scannable_content_type(&ct_lc) {
            log::debug!("Skipping {final_domain} - non-scannable content-type: {ct_lc}");
            return Ok(None);
        }
    } else {
        debug!("No Content-Type header for {final_domain}, continuing anyway");
    }

    // Check Content-Encoding header for debugging
    if let Some(encoding) = headers.get(reqwest::header::CONTENT_ENCODING) {
        debug!("Content-Encoding for {final_domain}: {encoding:?}");
    }

    // SECURITY: Stream body with running size check to prevent OOM attacks.
    // Unlike response.text().await which downloads the entire body into memory first,
    // this approach stops reading at MAX_RESPONSE_BODY_SIZE and keeps the prefix.
    let streamed = stream_bytes_with_limit(
        response,
        crate::config::MAX_RESPONSE_BODY_SIZE,
        OnLimit::Truncate,
        &final_domain,
    )
    .await;
    let (body, body_truncated) = match streamed {
        Ok(s) => decode_streamed_body(s, content_type.as_deref(), &final_domain),
        Err(e) => {
            log::warn!("Failed to read response body for {final_domain}: {e}");
            (String::new(), false)
        }
    };

    if body.is_empty() {
        // Preserve metadata (status, headers, TLS, DNS) like the 2MB-exceeded path.
        log::debug!("Empty response body for {final_domain}, recording metadata only");
        return Ok(Some(ResponseData {
            initial_url: original_url.to_string(),
            final_url,
            initial_domain,
            final_domain,
            host,
            status: status.as_u16(),
            status_desc,
            headers,
            security_headers,
            http_headers,
            body: Arc::<str>::from(""),
            body_sha256: None,
            body_truncated,
            content_length: None,
            http_version: http_version.clone(),
            content_type: content_type.clone(),
        }));
    }

    log::debug!("Body length for {final_domain}: {} bytes", body.len());

    // Check if title tag exists in raw HTML (for debugging)
    if body.contains("<title") || body.contains("<TITLE") {
        log::debug!("Title tag found in raw HTML for {final_domain}");
    } else {
        log::debug!("No title tag found in raw HTML for {final_domain}");
    }

    let body_sha256 = compute_body_sha256(&body);
    // Body is size-limited during streaming (typically < 10MB), length fits in i64
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    let content_length = Some(body.len() as i64);
    Ok(Some(ResponseData {
        initial_url: original_url.to_string(),
        final_url,
        initial_domain,
        final_domain,
        host,
        status: status.as_u16(),
        status_desc,
        headers,
        security_headers,
        http_headers,
        body: Arc::<str>::from(body),
        body_sha256,
        body_truncated,
        content_length,
        http_version,
        content_type,
    }))
}

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

    // === charset decoding (page wrapper over fetch::charset) ===

    #[test]
    fn test_decode_body_with_charset_uses_content_type_label() {
        // Windows-1252 byte 0x93 ("smart quote ") is INVALID utf-8 — lossy
        // decode would replace it with U+FFFD; charset-aware decode must
        // produce U+201C ().
        let bytes = b"\x93hello\x94";
        let decoded = decode_body_with_charset(bytes, Some("text/html; charset=windows-1252"));
        assert!(decoded.contains('\u{201C}'), "got {decoded:?}");
        assert!(!decoded.contains('\u{FFFD}'), "got {decoded:?}");
    }

    #[test]
    fn test_decode_body_with_charset_falls_back_to_meta_tag() {
        // No Content-Type charset, but HTML declares Windows-1252 in meta.
        let mut bytes = Vec::new();
        bytes.extend_from_slice(
            b"<html><head><meta charset=\"windows-1252\"><title>x</title></head><body>",
        );
        bytes.push(0x93);
        bytes.extend_from_slice(b"text");
        bytes.push(0x94);
        bytes.extend_from_slice(b"</body></html>");
        let decoded = decode_body_with_charset(&bytes, Some("text/html"));
        assert!(decoded.contains('\u{201C}'), "got {decoded:?}");
    }

    #[test]
    fn test_decode_body_with_charset_meta_http_equiv() {
        // <meta http-equiv="Content-Type" content="text/html; charset=…">
        let mut bytes = Vec::new();
        bytes.extend_from_slice(
            b"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\"></head><body>",
        );
        bytes.push(0x93);
        bytes.extend_from_slice(b"</body></html>");
        let decoded = decode_body_with_charset(&bytes, None);
        assert!(decoded.contains('\u{201C}'), "got {decoded:?}");
    }

    #[test]
    fn test_decode_body_with_charset_bom_utf16() {
        // UTF-16 LE BOM + "hi"
        let bytes: &[u8] = &[0xFF, 0xFE, b'h', 0x00, b'i', 0x00];
        let decoded = decode_body_with_charset(bytes, Some("text/html"));
        assert_eq!(decoded, "hi");
    }

    #[test]
    fn test_decode_body_with_charset_default_utf8() {
        let bytes = "hello world".as_bytes();
        let decoded = decode_body_with_charset(bytes, None);
        assert_eq!(decoded, "hello world");
    }

    #[test]
    fn test_decode_body_with_charset_unknown_label_falls_through() {
        // Bogus charset label (not in WHATWG): we must fall through, not panic.
        let bytes = "hello".as_bytes();
        let decoded = decode_body_with_charset(bytes, Some("text/html; charset=not-a-real-thing"));
        assert_eq!(decoded, "hello");
    }

    /// Regression: a Windows-1252-encoded API key wrapped in `'…'` would
    /// previously have been corrupted by `from_utf8_lossy` because
    /// 0x91 / 0x92 (smart quotes) are not valid UTF-8 lead bytes. With
    /// charset-aware decoding the 32 hex chars survive intact.
    #[test]
    fn test_decode_body_with_charset_preserves_secret_through_smart_quotes() {
        let mut bytes = Vec::new();
        bytes.extend_from_slice(b"var key = ");
        bytes.push(0x91);
        bytes.extend_from_slice(b"abcdef0123456789abcdef0123456789");
        bytes.push(0x92);
        bytes.extend_from_slice(b";");
        let decoded = decode_body_with_charset(&bytes, Some("text/html; charset=windows-1252"));
        assert!(decoded.contains("abcdef0123456789abcdef0123456789"));
    }

    // === content-type allowlist ===

    #[test]
    fn test_is_scannable_content_type_text_family() {
        assert!(is_scannable_content_type("text/html"));
        assert!(is_scannable_content_type("text/html; charset=utf-8"));
        assert!(is_scannable_content_type("text/plain"));
        assert!(is_scannable_content_type("text/javascript"));
        assert!(is_scannable_content_type("text/xml"));
        assert!(is_scannable_content_type("text/css"));
        assert!(is_scannable_content_type("text/csv"));
    }

    #[test]
    fn test_is_scannable_content_type_application_specific() {
        assert!(is_scannable_content_type("application/javascript"));
        assert!(is_scannable_content_type("application/x-javascript"));
        assert!(is_scannable_content_type("application/ecmascript"));
        assert!(is_scannable_content_type("application/xhtml+xml"));
        assert!(is_scannable_content_type("application/json"));
        assert!(is_scannable_content_type("application/manifest+json"));
        assert!(is_scannable_content_type("application/ld+json"));
        assert!(is_scannable_content_type("application/xml"));
        assert!(is_scannable_content_type("application/atom+xml"));
    }

    #[test]
    fn test_is_scannable_content_type_plus_suffix_match() {
        // RFC 6839 +json / +xml structured-syntax suffixes
        assert!(is_scannable_content_type("application/vnd.api+json"));
        assert!(is_scannable_content_type("application/hal+json"));
        assert!(is_scannable_content_type("application/problem+json"));
        assert!(is_scannable_content_type("application/vnd.opc.cmdb+xml"));
    }

    #[test]
    fn test_is_scannable_content_type_rejects_binary() {
        assert!(!is_scannable_content_type("image/png"));
        assert!(!is_scannable_content_type("image/jpeg"));
        assert!(!is_scannable_content_type("application/pdf"));
        assert!(!is_scannable_content_type("application/zip"));
        assert!(!is_scannable_content_type("application/octet-stream"));
        assert!(!is_scannable_content_type("video/mp4"));
        assert!(!is_scannable_content_type("audio/mpeg"));
        assert!(!is_scannable_content_type("font/woff2"));
    }

    #[test]
    fn test_is_scannable_content_type_handles_parameters() {
        // Goofy whitespace and parameter ordering must not break recognition
        assert!(is_scannable_content_type(
            "application/json   ;   charset=utf-8"
        ));
        assert!(is_scannable_content_type(
            "text/html; charset=windows-1252; boundary=foo"
        ));
    }

    #[tokio::test]
    async fn test_extract_response_data_success() {
        // Note: response.url() is an IP from the mock server; IP literals are valid domain keys.
        let server = Server::run();
        let server_url = server.url("/test").to_string();
        let test_url = "https://example.com/test";

        server.expect(
            Expectation::matching(request::method_path("GET", "/test")).respond_with(
                status_code(200)
                    .insert_header("Content-Type", "text/html; charset=utf-8")
                    .insert_header("Content-Security-Policy", "default-src 'self'")
                    .insert_header("Server", "nginx/1.18.0")
                    .body("<html><head><title>Test</title></head><body>Hello</body></html>"),
            ),
        );

        let client = reqwest::Client::new();
        let response = client.get(&server_url).send().await.unwrap();

        // Domain extraction now accepts IP literals as domain keys (needed for
        // wiremock). This test still exercises extract_response_data end-to-end.
        let result = extract_response_data(response, test_url, &server_url).await;

        // original_url is example.com; final_url from httptest is an IP — both extract.
        assert!(
            result.is_ok(),
            "extract_response_data should succeed with IP final URL, got: {result:?}"
        );
    }

    #[tokio::test]
    async fn test_extract_response_data_non_html_content_type() {
        let server = Server::run();
        let server_url = server.url("/test").to_string();
        let test_url = "https://example.com/test";

        server.expect(
            Expectation::matching(request::method_path("GET", "/test")).respond_with(
                status_code(200)
                    .insert_header("Content-Type", "application/json")
                    .body(r#"{"key": "value"}"#),
            ),
        );

        let client = reqwest::Client::new();
        let response = client.get(&server_url).send().await.unwrap();

        let result = extract_response_data(response, test_url, &server_url).await;
        let data = result
            .expect("application/json is scannable")
            .expect("should return Some ResponseData");
        assert_eq!(data.content_type.as_deref(), Some("application/json"));
        assert!(data.body.contains("key"));
    }

    #[tokio::test]
    async fn test_extract_response_data_missing_content_type() {
        let server = Server::run();
        let server_url = server.url("/test").to_string();
        let test_url = "https://example.com/test";

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

        let client = reqwest::Client::new();
        let response = client.get(&server_url).send().await.unwrap();

        // Missing Content-Type: treated as HTML-ish / proceeds or errors on empty policy — not IP domain.
        let result = extract_response_data(response, test_url, &server_url).await;
        // Accept either success (body treated as HTML) or a content-type related error.
        if let Err(e) = &result {
            let msg = e.to_string();
            assert!(
                !msg.contains("IP addresses do not have registrable domains"),
                "IP domain rejection should be gone, got: {msg}"
            );
        }
    }

    #[tokio::test]
    async fn test_extract_response_data_empty_body() {
        let server = Server::run();
        let server_url = server.url("/test").to_string();
        let test_url = "https://example.com/test";

        server.expect(
            Expectation::matching(request::method_path("GET", "/test")).respond_with(
                status_code(200)
                    .insert_header("Content-Type", "text/html")
                    .body(""),
            ),
        );

        let client = reqwest::Client::new();
        let response = client.get(&server_url).send().await.unwrap();

        let result = extract_response_data(response, test_url, &server_url).await;
        assert!(
            result.is_ok(),
            "empty HTML body with IP final URL should extract, got: {result:?}"
        );
    }

    #[test]
    fn test_extract_response_data_domain_extraction_logic() {
        // Test domain extraction logic separately (domain extraction is tested in domain/tests.rs)
        // This test verifies that extract_domain works with proper URLs

        let original_url = "https://example.com/page";
        let final_url = "https://example.org/page";

        // Verify domain extraction works (tested more thoroughly in domain/tests.rs)
        assert_eq!(extract_domain(original_url).unwrap(), "example.com");
        assert_eq!(extract_domain(final_url).unwrap(), "example.org");
    }

    #[tokio::test]
    async fn test_extract_response_data_security_headers_extraction() {
        // wiremock serves from an IP literal (valid domain key).
        // Header extraction is tested in fetch/request/tests.rs and through integration tests
        let server = Server::run();
        let server_url = server.url("/test").to_string();
        let test_url = "https://example.com/test";

        server.expect(
            Expectation::matching(request::method_path("GET", "/test")).respond_with(
                status_code(200)
                    .insert_header("Content-Type", "text/html")
                    .insert_header("Content-Security-Policy", "default-src 'self'")
                    .insert_header("Strict-Transport-Security", "max-age=31536000")
                    .body("<html><body>Test</body></html>"),
            ),
        );

        let client = reqwest::Client::new();
        let response = client.get(&server_url).send().await.unwrap();

        let result = extract_response_data(response, test_url, &server_url).await;
        assert!(
            result.is_ok(),
            "expected Ok after IP domain support, got: {result:?}"
        );
    }

    #[tokio::test]
    async fn test_extract_response_data_http_headers_extraction() {
        // wiremock serves from an IP literal (valid domain key).
        // Header extraction is tested in fetch/request/tests.rs and through integration tests
        let server = Server::run();
        let server_url = server.url("/test").to_string();
        let test_url = "https://example.com/test";

        server.expect(
            Expectation::matching(request::method_path("GET", "/test")).respond_with(
                status_code(200)
                    .insert_header("Content-Type", "text/html")
                    .insert_header("Server", "nginx/1.18.0")
                    .insert_header("X-Powered-By", "PHP/7.4")
                    .body("<html><body>Test</body></html>"),
            ),
        );

        let client = reqwest::Client::new();
        let response = client.get(&server_url).send().await.unwrap();

        let result = extract_response_data(response, test_url, &server_url).await;
        assert!(
            result.is_ok(),
            "expected Ok after IP domain support, got: {result:?}"
        );
    }

    #[tokio::test]
    async fn test_extract_response_data_status_code_extraction() {
        // wiremock serves from an IP literal (valid domain key).
        // Status code extraction is straightforward and tested through integration tests
        let server = Server::run();
        let server_url = server.url("/test").to_string();
        let test_url = "https://example.com/test";

        server.expect(
            Expectation::matching(request::method_path("GET", "/test")).respond_with(
                status_code(404)
                    .insert_header("Content-Type", "text/html")
                    .body("<html><body>Not Found</body></html>"),
            ),
        );

        let client = reqwest::Client::new();
        let response = client.get(&server_url).send().await.unwrap();

        let result = extract_response_data(response, test_url, &server_url).await;
        assert!(
            result.is_ok(),
            "expected Ok after IP domain support, got: {result:?}"
        );
    }

    #[test]
    fn test_content_type_filtering_logic() {
        // Test content-type filtering logic directly (unit test for the string matching)
        // This tests the critical logic: !ct.starts_with("text/html")

        // Valid HTML content types (should pass)
        let valid_types = vec![
            "text/html",
            "text/html; charset=utf-8",
            "text/html;charset=utf-8",
            "TEXT/HTML", // Case insensitive after to_lowercase()
            "text/html; charset=ISO-8859-1",
        ];

        for ct in valid_types {
            let ct_lower = ct.to_lowercase();
            assert!(
                ct_lower.starts_with("text/html"),
                "Content type '{}' should be recognized as HTML",
                ct
            );
        }

        // Invalid content types (should be filtered out)
        let invalid_types = vec![
            "application/json",
            "text/plain",
            "application/xml",
            "image/png",
            "text/css",
            "application/javascript",
        ];

        for ct in invalid_types {
            let ct_lower = ct.to_lowercase();
            assert!(
                !ct_lower.starts_with("text/html"),
                "Content type '{}' should NOT be recognized as HTML",
                ct
            );
        }
    }

    #[test]
    fn test_body_size_limit_logic() {
        // Test body size limit checking logic
        // MAX_RESPONSE_BODY_SIZE is 2MB (2 * 1024 * 1024 = 2,097,152 bytes)
        const MAX_SIZE: usize = 2 * 1024 * 1024;

        // Test boundary conditions
        assert_eq!(MAX_SIZE, 2_097_152, "MAX_RESPONSE_BODY_SIZE should be 2MB");

        // Body exactly at limit should pass
        let body_at_limit = "x".repeat(MAX_SIZE);
        assert_eq!(body_at_limit.len(), MAX_SIZE);
        assert!(body_at_limit.len() <= MAX_SIZE);

        // Body one byte over limit should fail
        let body_over_limit = "x".repeat(MAX_SIZE + 1);
        assert_eq!(body_over_limit.len(), MAX_SIZE + 1);
        assert!(body_over_limit.len() > MAX_SIZE);

        // Empty body streams as Complete(vec![]) and is handled by the caller
        assert_eq!("".len(), 0);
    }

    #[test]
    fn test_decode_streamed_body_sets_truncated_flag() {
        let complete = StreamedBytes::Complete(b"<html>ok</html>".to_vec());
        let (body, truncated) = decode_streamed_body(complete, Some("text/html"), "example.com");
        assert!(!truncated);
        assert!(body.contains("ok"));

        let over = StreamedBytes::Truncated(b"x".repeat(100));
        let (body2, truncated2) = decode_streamed_body(over, Some("text/html"), "example.com");
        assert!(
            truncated2,
            "Truncated stream must set body_truncated for FN awareness"
        );
        assert_eq!(body2.len(), 100);
    }

    #[tokio::test]
    async fn test_extract_response_data_content_type_case_insensitive() {
        // Test that content-type matching is case-insensitive
        // The code does: ct.to_lowercase() then checks starts_with("text/html")
        let server = Server::run();
        let server_url = server.url("/case").to_string();
        let test_url = "https://example.com/case";

        // Test uppercase content-type
        server.expect(
            Expectation::matching(request::method_path("GET", "/case")).respond_with(
                status_code(200)
                    .insert_header("Content-Type", "TEXT/HTML; CHARSET=UTF-8")
                    .body("<html><body>Test</body></html>"),
            ),
        );

        let client = reqwest::Client::new();
        let response = client.get(&server_url).send().await.unwrap();

        // IP literals are valid domain keys; assert extraction succeeds.
        let result = extract_response_data(response, test_url, &server_url).await;
        assert!(
            result.is_ok(),
            "expected Ok after IP domain support, got: {result:?}"
        );
    }

    #[tokio::test]
    async fn test_extract_response_data_malformed_content_type_header() {
        // Test handling of malformed content-type headers
        // The code uses: ct.to_str().unwrap_or("") - so invalid UTF-8 should be handled
        let server = Server::run();
        let server_url = server.url("/malformed").to_string();
        let test_url = "https://example.com/malformed";

        // Note: httptest may not support truly malformed headers, but we test the error handling
        server.expect(
            Expectation::matching(request::method_path("GET", "/malformed")).respond_with(
                status_code(200)
                    .insert_header("Content-Type", "text/html")
                    .body("<html><body>Test</body></html>"),
            ),
        );

        let client = reqwest::Client::new();
        let response = client.get(&server_url).send().await.unwrap();

        // IP literals are valid domain keys; assert extraction succeeds.
        let result = extract_response_data(response, test_url, &server_url).await;
        assert!(
            result.is_ok(),
            "expected Ok after IP domain support, got: {result:?}"
        );
    }

    #[tokio::test]
    async fn test_extract_response_data_body_read_failure_handled() {
        // Test that body read failures are handled gracefully
        // The code catches body read errors and uses empty string, then checks if empty
        let server = Server::run();
        let server_url = server.url("/body-error").to_string();
        let test_url = "https://example.com/body-error";

        // Return valid response - body read should succeed
        // Actual body read failures are hard to simulate with httptest,
        // but we verify the error handling path exists in the code
        server.expect(
            Expectation::matching(request::method_path("GET", "/body-error")).respond_with(
                status_code(200)
                    .insert_header("Content-Type", "text/html; charset=utf-8")
                    .body("<html><body>Test</body></html>"),
            ),
        );

        let client = reqwest::Client::new();
        let response = client.get(&server_url).send().await.unwrap();

        // IP literals are valid domain keys; assert extraction succeeds.
        let result = extract_response_data(response, test_url, &server_url).await;
        assert!(
            result.is_ok(),
            "expected Ok after IP domain support, got: {result:?}"
        );
    }

    #[test]
    fn test_content_type_with_charset_variations() {
        // Test various content-type formats with charset
        // This is critical because real servers use many variations
        let variations = vec![
            ("text/html; charset=utf-8", true),
            ("text/html;charset=utf-8", true),  // No space
            ("text/html; charset=UTF-8", true), // Uppercase charset
            ("text/html; charset=ISO-8859-1", true),
            ("text/html; charset=\"utf-8\"", true), // Quoted charset
            ("text/html; boundary=something", true), // Other parameters
            ("text/html", true),                    // No charset
            ("application/json; charset=utf-8", false), // JSON with charset
        ];

        for (content_type, should_pass) in variations {
            let ct_lower = content_type.to_lowercase();
            let is_html = ct_lower.starts_with("text/html");
            assert_eq!(
                is_html,
                should_pass,
                "Content type '{}' should {} be recognized as HTML",
                content_type,
                if should_pass { "" } else { "NOT" }
            );
        }
    }

    #[test]
    fn test_host_extraction_edge_cases() {
        // Test host extraction logic for various URL formats
        // This is critical - host extraction must work for all valid URLs

        // Test cases for host extraction
        let test_cases = vec![
            ("https://example.com/path", "example.com"),
            ("https://www.example.com/path", "www.example.com"),
            (
                "http://subdomain.example.com:8080/path",
                "subdomain.example.com",
            ),
            ("https://example.com:443/path", "example.com"),
        ];

        for (url, expected_host) in test_cases {
            let parsed = reqwest::Url::parse(url).unwrap();
            let host = parsed.host_str().unwrap();
            assert_eq!(
                host, expected_host,
                "Host extraction failed for URL: {}",
                url
            );
        }
    }

    #[test]
    fn test_host_extraction_failure_handling() {
        // Test that host extraction failures are handled correctly
        // This is critical - invalid URLs should return errors, not panic
        // Note: reqwest::Url::parse will succeed for most strings, but host_str() may return None
        // for URLs without a host (like "file:///path")
        let file_url = reqwest::Url::parse("file:///path/to/file").unwrap();
        // file:// URLs don't have a host_str() in the traditional sense
        // The code uses .ok_or_else() to handle None, which is correct
        let host_result = file_url.host_str();
        // For file:// URLs, host_str() returns None, which would trigger the error
        // This test verifies the error handling path exists
        assert!(
            host_result.is_none(),
            "file:// URLs should not have host_str()"
        );
    }

    #[tokio::test]
    async fn test_extract_response_data_body_read_error_handling_path() {
        // Test that body read error handling path exists in the code
        // The code catches body read errors and uses empty string, then checks if empty
        // This is critical - network errors shouldn't cause panics
        let server = Server::run();
        let server_url = server.url("/body-error-path").to_string();
        let test_url = "https://example.com/body-error-path";

        // Return valid response - body read should succeed
        // Actual body read failures are hard to simulate with httptest,
        // but we verify the error handling path exists in the code
        server.expect(
            Expectation::matching(request::method_path("GET", "/body-error-path")).respond_with(
                status_code(200)
                    .insert_header("Content-Type", "text/html; charset=utf-8")
                    .body("<html><body>Test</body></html>"),
            ),
        );

        let client = reqwest::Client::new();
        let response = client.get(&server_url).send().await.unwrap();

        // The code at line 75-87 handles body read failures by catching errors
        // and using empty string, then checking if empty (line 89-92)
        let result = extract_response_data(response, test_url, &server_url).await;
        assert!(
            result.is_ok(),
            "expected Ok after IP domain support, got: {result:?}"
        );
    }

    #[tokio::test]
    async fn test_extract_response_data_content_encoding_handled() {
        // Test that Content-Encoding header is logged for debugging
        // This is critical - compression detection helps with debugging
        let server = Server::run();
        let server_url = server.url("/compressed").to_string();
        let test_url = "https://example.com/compressed";

        // Return response with Content-Encoding header
        server.expect(
            Expectation::matching(request::method_path("GET", "/compressed")).respond_with(
                status_code(200)
                    .insert_header("Content-Type", "text/html; charset=utf-8")
                    .insert_header("Content-Encoding", "gzip")
                    .body("<html><body>Test</body></html>"),
            ),
        );

        let client = reqwest::Client::new();
        let response = client.get(&server_url).send().await.unwrap();

        // The code at line 70-72 logs Content-Encoding for debugging
        // reqwest automatically decompresses, so the body is already decompressed
        let result = extract_response_data(response, test_url, &server_url).await;
        assert!(
            result.is_ok(),
            "expected Ok after IP domain support, got: {result:?}"
        );
    }

    #[test]
    fn test_extract_response_data_status_code_reason_extraction() {
        // Test status code and reason extraction logic
        // This is critical - status codes must be extracted correctly
        use reqwest::StatusCode;

        // Test various status codes
        let test_cases = vec![
            (StatusCode::OK, "OK"),
            (StatusCode::NOT_FOUND, "Not Found"),
            (StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error"),
            (StatusCode::MOVED_PERMANENTLY, "Moved Permanently"),
            (StatusCode::FORBIDDEN, "Forbidden"),
        ];

        for (status, expected_reason) in test_cases {
            let reason = status
                .canonical_reason()
                .unwrap_or("Unknown Status Code")
                .to_string();
            // Verify canonical_reason returns expected value (or "Unknown Status Code" if None)
            assert!(
                reason == expected_reason || reason == "Unknown Status Code",
                "Status {} should have reason '{}' or 'Unknown Status Code', got '{}'",
                status.as_u16(),
                expected_reason,
                reason
            );
        }
    }

    #[test]
    fn test_extract_response_data_body_size_limit_enforcement() {
        // Test that body size limit is correctly enforced
        // This is critical - prevents memory exhaustion from large responses
        use crate::config::MAX_RESPONSE_BODY_SIZE;

        // Test boundary conditions
        let body_at_limit = "x".repeat(MAX_RESPONSE_BODY_SIZE);
        assert_eq!(body_at_limit.len(), MAX_RESPONSE_BODY_SIZE);
        assert!(body_at_limit.len() <= MAX_RESPONSE_BODY_SIZE);

        let body_over_limit = "x".repeat(MAX_RESPONSE_BODY_SIZE + 1);
        assert_eq!(body_over_limit.len(), MAX_RESPONSE_BODY_SIZE + 1);
        assert!(body_over_limit.len() > MAX_RESPONSE_BODY_SIZE);

        // Verify the limit is 2MB as documented
        assert_eq!(
            MAX_RESPONSE_BODY_SIZE,
            2 * 1024 * 1024,
            "MAX_RESPONSE_BODY_SIZE should be 2MB"
        );
    }

    #[test]
    fn test_extract_response_data_html_preview_logic() {
        // Test HTML preview extraction logic for debugging
        // This is critical - helps with debugging when title tags are missing
        use crate::config::MAX_HTML_PREVIEW_CHARS;

        // Test preview extraction
        let short_body = "<html><body>Short</body></html>";
        let preview_short: String = short_body.chars().take(MAX_HTML_PREVIEW_CHARS).collect();
        assert_eq!(preview_short, short_body);
        assert!(preview_short.len() <= MAX_HTML_PREVIEW_CHARS);

        // Test preview truncation for long bodies
        let long_body = "x".repeat(MAX_HTML_PREVIEW_CHARS * 2);
        let preview_long: String = long_body.chars().take(MAX_HTML_PREVIEW_CHARS).collect();
        assert_eq!(preview_long.len(), MAX_HTML_PREVIEW_CHARS);
        assert!(preview_long.len() < long_body.len());

        // Verify the limit is 500 chars as documented
        assert_eq!(
            MAX_HTML_PREVIEW_CHARS, 500,
            "MAX_HTML_PREVIEW_CHARS should be 500"
        );
    }

    #[tokio::test]
    async fn test_stream_body_with_limit_within_limit() {
        // Covered by fetch::stream unit tests; keep one integration check here.
        let server = Server::run();
        let server_url = server.url("/stream-small").to_string();

        let body_content = "Hello, World!";
        server.expect(
            Expectation::matching(request::method_path("GET", "/stream-small"))
                .respond_with(status_code(200).body(body_content)),
        );

        let client = reqwest::Client::new();
        let response = client.get(&server_url).send().await.unwrap();

        let result = stream_bytes_with_limit(response, 1024, OnLimit::Truncate, "test.com").await;

        match result.unwrap() {
            StreamedBytes::Complete(bytes) => {
                assert_eq!(String::from_utf8(bytes).unwrap(), body_content);
            }
            StreamedBytes::Truncated(_) => panic!("small body must not be truncated"),
        }
    }

    #[tokio::test]
    async fn test_stream_body_with_limit_exceeds_limit() {
        // Bodies exceeding the limit are truncated to exactly the limit and kept
        let server = Server::run();
        let server_url = server.url("/stream-large").to_string();

        // Create a body larger than our test limit
        let large_body = "x".repeat(2000);
        server.expect(
            Expectation::matching(request::method_path("GET", "/stream-large"))
                .respond_with(status_code(200).body(large_body)),
        );

        let client = reqwest::Client::new();
        let response = client.get(&server_url).send().await.unwrap();

        // Use a limit smaller than the body
        let result = stream_bytes_with_limit(response, 1000, OnLimit::Truncate, "test.com").await;

        match result.unwrap() {
            StreamedBytes::Truncated(bytes) => {
                assert_eq!(bytes.len(), 1000, "prefix must be exactly the cap");
                assert!(bytes.iter().all(|&b| b == b'x'));
            }
            StreamedBytes::Complete(_) => {
                panic!("oversized body must be reported as truncated")
            }
        }
    }

    #[tokio::test]
    async fn test_stream_body_with_limit_exactly_at_limit() {
        // Test that bodies exactly at the limit are accepted
        let server = Server::run();
        let server_url = server.url("/stream-exact").to_string();

        let exact_body = "x".repeat(1000);
        server.expect(
            Expectation::matching(request::method_path("GET", "/stream-exact"))
                .respond_with(status_code(200).body(exact_body.clone())),
        );

        let client = reqwest::Client::new();
        let response = client.get(&server_url).send().await.unwrap();

        let result = stream_bytes_with_limit(response, 1000, OnLimit::Truncate, "test.com").await;

        match result.unwrap() {
            StreamedBytes::Complete(bytes) => assert_eq!(bytes.len(), 1000),
            StreamedBytes::Truncated(_) => {
                panic!("body exactly at limit should be complete")
            }
        }
    }

    #[tokio::test]
    async fn test_stream_body_with_limit_empty_body() {
        // Test that empty bodies are handled correctly
        let server = Server::run();
        let server_url = server.url("/stream-empty").to_string();

        server.expect(
            Expectation::matching(request::method_path("GET", "/stream-empty"))
                .respond_with(status_code(200).body("")),
        );

        let client = reqwest::Client::new();
        let response = client.get(&server_url).send().await.unwrap();

        let result = stream_bytes_with_limit(response, 1000, OnLimit::Truncate, "test.com").await;

        match result.unwrap() {
            StreamedBytes::Complete(bytes) => assert!(bytes.is_empty()),
            StreamedBytes::Truncated(_) => panic!("empty body must not be truncated"),
        }
    }

    #[test]
    fn test_stream_body_prevents_oom_attack() {
        // Verify the streaming approach prevents OOM attacks by documenting the behavior:
        // - Old approach (response.text().await): Downloads entire body into memory BEFORE checking size
        // - New approach (stream_bytes_with_limit): Stops reading at the limit, keeps the prefix
        //
        // This test verifies the constants and logic are correctly set up for OOM protection
        use crate::config::MAX_RESPONSE_BODY_SIZE;

        // Verify the limit is reasonable (2MB)
        assert_eq!(MAX_RESPONSE_BODY_SIZE, 2 * 1024 * 1024);

        // The streaming approach guarantees:
        // 1. Memory usage is bounded by MAX_RESPONSE_BODY_SIZE + one chunk size (typically 64KB)
        // 2. Malicious infinite streams are aborted quickly
        // 3. No full download required before checking size
    }
}