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
//! Record building utilities.
//!
//! These functions are optimized to minimize clones in the hot path:
//! - `build_url_record` clones ~15 small strings (unavoidable for `UrlRecord` fields)
//! - `build_persisted_url_record` takes ownership and **moves** large collections (`HashMaps`, Vecs)
//!   instead of cloning them, saving ~5-10KB of allocations per URL

use regex::Regex;
use std::collections::HashSet;

use crate::domain::root_domain;
use crate::fetch::cookies::extract_cookie_infos;
use crate::fetch::dns::{AdditionalDnsData, TlsDnsData};
use crate::fetch::external_scripts::collect_script_hosts;
use crate::fetch::response::{HtmlData, ResponseData};
use crate::storage::{PersistedUrlRecord, UrlRecord};

/// Extracts FQDNs and registrable domains from a Content-Security-Policy header value.
/// Parses directives like `default-src 'self' *.cdn.example.com; script-src https://analytics.com`
fn extract_csp_domains(csp: &str) -> Vec<(String, String, Option<String>)> {
    let mut results = Vec::new();
    let mut seen = HashSet::new();
    static CSP_DOMAIN_RE: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| {
        Regex::new(
            r"(?:https?://)?(\*\.)?([a-zA-Z0-9][-a-zA-Z0-9]*(?:\.[a-zA-Z0-9][-a-zA-Z0-9]*)+)",
        )
        .expect("CSP domain regex")
    });
    let domain_re = &*CSP_DOMAIN_RE;

    for directive_part in csp.split(';') {
        let parts: Vec<&str> = directive_part.trim().splitn(2, ' ').collect();
        let directive = (*parts.first().unwrap_or(&"")).to_string();
        let values = parts.get(1).unwrap_or(&"");

        for cap in domain_re.captures_iter(values) {
            if let Some(fqdn_match) = cap.get(2) {
                let fqdn = fqdn_match.as_str().to_lowercase();
                // Skip keywords that look like domains
                if fqdn == "self" || fqdn == "none" || fqdn == "unsafe-inline" {
                    continue;
                }
                let key = (directive.clone(), fqdn.clone());
                if seen.insert(key) {
                    let reg = root_domain(&fqdn);
                    results.push((directive.clone(), fqdn, reg));
                }
            }
        }
    }
    results
}

/// Builds a `UrlRecord` from extracted response data.
///
/// This function clones string fields from the input data. While this involves
/// ~15 small string allocations, these are necessary to create an independent
/// `UrlRecord`. The expensive HashMap/Vec data is handled by `build_persisted_url_record`
/// which takes ownership to avoid cloning.
pub(crate) fn build_url_record(
    resp_data: &ResponseData,
    html_data: &HtmlData,
    tls_dns_data: &TlsDnsData,
    additional_dns: &AdditionalDnsData,
    elapsed: f64,
    timestamp: i64,
    run_id: Option<&String>,
) -> UrlRecord {
    UrlRecord {
        initial_domain: resp_data.initial_domain.clone(),
        final_domain: resp_data.final_domain.clone(),
        initial_url: Some(resp_data.initial_url.clone()),
        final_url: Some(resp_data.final_url.clone()),
        ip_address: tls_dns_data.ip_address.clone().unwrap_or_default(),
        reverse_dns_name: tls_dns_data.reverse_dns_name.clone(),
        status: resp_data.status,
        status_desc: resp_data.status_desc.clone(),
        response_time: elapsed,
        title: html_data.title.clone(),
        // Normalize empty strings to None for consistency with database queries
        description: html_data
            .description
            .as_ref()
            .filter(|d| !d.is_empty())
            .cloned(),
        meta_robots: html_data.meta_robots.clone(),
        tls_version: tls_dns_data.tls_version,
        ssl_cert_subject: tls_dns_data.subject.clone(),
        ssl_cert_issuer: tls_dns_data.issuer.clone(),
        ssl_cert_valid_from: tls_dns_data.valid_from,
        ssl_cert_valid_to: tls_dns_data.valid_to,
        timestamp,
        nameservers: additional_dns.nameservers.clone(),
        txt_records: additional_dns.txt_records.clone(),
        mx_records: additional_dns.mx_records.clone(),
        spf_record: additional_dns.spf_record.clone(),
        dmarc_record: additional_dns.dmarc_record.clone(),
        cipher_suite: tls_dns_data.cipher_suite.clone(),
        key_algorithm: tls_dns_data.key_algorithm.clone(),
        run_id: run_id.cloned(),
        body_sha256: resp_data.body_sha256.clone(),
        body_truncated: resp_data.body_truncated,
        external_scripts_eligible: html_data.external_scripts_eligible,
        external_scripts_scanned: html_data.external_scripts_scanned,
        content_length: resp_data.content_length,
        http_version: resp_data.http_version.clone(),
        content_type: resp_data.content_type.clone(),
        canonical_url: html_data.canonical_url.clone(),
        cert_fingerprint_sha256: tls_dns_data.cert_fingerprint_sha256.clone(),
        cert_serial_number: tls_dns_data.cert_serial_number.clone(),
        cert_is_self_signed: tls_dns_data.cert_is_self_signed,
        cert_is_wildcard: tls_dns_data.cert_is_wildcard,
        cert_is_mismatched: None, // Computed later when host is available
        meta_refresh_url: html_data.meta_refresh_url.clone(),
        hsts_max_age: None,
        hsts_include_subdomains: None,
        hsts_preload: None,
        mta_sts_record: additional_dns.mta_sts_record.clone(),
        tls_rpt_record: additional_dns.tls_rpt_record.clone(),
        bimi_record: additional_dns.bimi_record.clone(),
        cdn_provider: None,
    }
}

/// Parameters for building a `PersistedUrlRecord`.
///
/// This struct **owns** the response, HTML, and TLS/DNS data to enable moving
/// large collections (`HashMaps`, Vecs) into the `PersistedUrlRecord` instead of cloning.
/// This eliminates ~5-10KB of heap allocations per URL in the hot path.
pub struct PersistedUrlRecordParams {
    /// The main URL record to persist
    pub record: UrlRecord,
    /// Response data (headers, status, etc.) - owned to move `HashMaps`
    pub resp_data: ResponseData,
    /// HTML parsing results - owned to move Vecs
    pub html_data: HtmlData,
    /// TLS and DNS data - owned to move `HashSet` and Vec
    pub tls_dns_data: TlsDnsData,
    /// Detected technologies
    pub technologies_vec: Vec<crate::fingerprint::DetectedTechnology>,
    /// Redirect chain (URL, HTTP status code) per hop
    pub redirect_chain: Vec<(String, u16)>,
    /// Partial failures (DNS/TLS errors that didn't prevent processing)
    pub partial_failures: Vec<(crate::error_handling::ErrorType, String)>,
    /// `GeoIP` lookup result (IP address and data)
    pub geoip_data: Option<(String, crate::geoip::GeoIpResult)>,
    /// WHOIS lookup result
    pub whois_data: Option<crate::whois::WhoisResult>,
    /// Timestamp for the record
    pub timestamp: i64,
    /// Run identifier
    pub run_id: Option<String>,
    /// Favicon data (Shodan-compatible hash + resolved URL)
    pub favicon: Option<crate::fetch::favicon::FaviconData>,
    /// Additional DNS data (CNAME, AAAA, CAA) for satellite table insertion
    pub additional_dns: crate::fetch::dns::AdditionalDnsData,
    /// security.txt / robots.txt captured during enrichment
    pub well_known: crate::fetch::well_known::WellKnownData,
}

/// Builds a `PersistedUrlRecord` from all extracted data.
///
/// Takes ownership of params to **move** large collections instead of cloning:
/// - `security_headers` and `http_headers` `HashMaps` from `ResponseData`
/// - `oids` `HashSet` and `subject_alternative_names` Vec from `TlsDnsData`
/// - `analytics_ids`, `structured_data`, `social_media_links` from `HtmlData`
///
/// This saves ~5-10KB of heap allocations per URL compared to cloning.
///
/// # Arguments
///
/// * `params` - Parameters for building the persisted record (ownership transferred)
pub(crate) fn build_persisted_url_record(
    mut params: PersistedUrlRecordParams,
) -> PersistedUrlRecord {
    // Move OIDs HashSet instead of cloning (avoids HashSet allocation)
    let oids_set: std::collections::HashSet<String> =
        params.tls_dns_data.oids.take().unwrap_or_default();

    let partial_failure_records: Vec<crate::storage::models::UrlPartialFailureRecord> = params
        .partial_failures
        .into_iter()
        .map(|(error_type, error_message)| {
            crate::storage::models::UrlPartialFailureRecord {
                url_status_id: 0, // Will be set when record is inserted
                error_type,
                error_message,
                timestamp: params.timestamp,
                run_id: params.run_id.clone(),
            }
        })
        .collect();

    // Move SANs Vec instead of cloning (avoids Vec allocation)
    let sans_vec: Vec<String> = params
        .tls_dns_data
        .subject_alternative_names
        .take()
        .unwrap_or_default();

    // Move analytics_ids, structured_data, social_media_links, contact_links, exposed_secrets instead of cloning
    let analytics_ids = std::mem::take(&mut params.html_data.analytics_ids);
    let structured_data = std::mem::take(&mut params.html_data.structured_data);
    let social_media_links = std::mem::take(&mut params.html_data.social_media_links);
    let contact_links = std::mem::take(&mut params.html_data.contact_links);
    let exposed_secrets = std::mem::take(&mut params.html_data.exposed_secrets);

    // Move security_headers and http_headers HashMaps instead of cloning
    // These are the most expensive clones (~2-5KB each for typical responses)
    let security_headers = std::mem::take(&mut params.resp_data.security_headers);
    let http_headers = std::mem::take(&mut params.resp_data.http_headers);

    // Extract CSP domains from Content-Security-Policy header
    let csp_domains = security_headers
        .get("Content-Security-Policy")
        .map(|csp| extract_csp_domains(csp))
        .unwrap_or_default();

    // Extract cookie security info from Set-Cookie headers
    let cookies = extract_cookie_infos(&params.resp_data.headers);

    let script_hosts = collect_script_hosts(
        &params.resp_data.final_url,
        &params.html_data.script_sources,
    );

    // Persist parsed HSTS directives onto the fact row (raw header stays in satellite).
    if let Some(hsts_value) = security_headers
        .iter()
        .find(|(k, _)| k.eq_ignore_ascii_case("strict-transport-security"))
        .map(|(_, v)| v.as_str())
    {
        let d = crate::security::parse_hsts_directive(hsts_value);
        params.record.hsts_max_age = d.max_age.map(|v| i64::try_from(v).unwrap_or(i64::MAX));
        params.record.hsts_include_subdomains = Some(d.include_subdomains);
        params.record.hsts_preload = Some(d.preload);
    }

    params.record.cdn_provider = crate::fetch::cdn::detect_cdn_provider(
        &http_headers,
        &security_headers,
        params.additional_dns.cname_chain.as_deref(),
        params.additional_dns.nameservers.as_deref(),
    );

    // Compute cert_is_mismatched: check if host matches any SAN or CN.
    // Uses sans_vec (not tls_dns_data.subject_alternative_names which was already .take()'d).
    let domain = &params.resp_data.host;
    if !domain.is_empty() && params.tls_dns_data.tls_version.is_some() {
        let cn = params.tls_dns_data.subject.as_deref().unwrap_or("");
        let matches_san = sans_vec.iter().any(|san| {
            if let Some(wildcard_base) = san.strip_prefix("*.") {
                // RFC 6125: wildcard covers exactly one label level.
                // *.example.com matches foo.example.com but NOT foo.bar.example.com.
                domain == wildcard_base
                    || domain.strip_suffix(wildcard_base).is_some_and(|prefix| {
                        prefix.ends_with('.') && !prefix[..prefix.len() - 1].contains('.')
                    })
            } else {
                domain == san
            }
        });
        // Extract CN value from subject DN (e.g., "CN=example.com, O=Org")
        let matches_cn = cn
            .split(',')
            .filter_map(|part| part.trim().strip_prefix("CN="))
            .any(|cn_val| cn_val.trim() == domain);
        params.record.cert_is_mismatched = Some(!matches_san && !matches_cn);
    }

    PersistedUrlRecord {
        url_record: params.record,
        security_headers,
        http_headers,
        oids: oids_set,
        redirect_chain: params.redirect_chain,
        technologies: params.technologies_vec,
        subject_alternative_names: sans_vec,
        analytics_ids,
        geoip: params.geoip_data,
        structured_data: Some(structured_data),
        social_media_links,
        contact_links,
        exposed_secrets,
        whois: params.whois_data,
        partial_failures: partial_failure_records,
        favicon: params.favicon,
        cname_records: params.additional_dns.cname_chain,
        aaaa_records: params.additional_dns.aaaa_records,
        caa_records: params.additional_dns.caa_records,
        csp_domains,
        cookies,
        resource_hints: std::mem::take(&mut params.html_data.resource_hints),
        script_hosts,
        security_txt: params.well_known.security_txt,
        robots_txt: params.well_known.robots_txt,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error_handling::ErrorType;
    use crate::fetch::dns::{AdditionalDnsData, TlsDnsData};
    use crate::fetch::response::{HtmlData, ResponseData};
    use crate::geoip::GeoIpResult;
    use crate::parse::StructuredData;
    use crate::whois::WhoisResult;
    use chrono::NaiveDateTime;
    use proptest::prelude::*;
    use reqwest::header::HeaderMap;
    use std::collections::{HashMap, HashSet};

    fn create_test_response_data() -> ResponseData {
        let mut headers = HeaderMap::new();
        headers.insert(
            reqwest::header::CONTENT_SECURITY_POLICY,
            "default-src 'self'".parse().unwrap(),
        );
        ResponseData {
            initial_url: "https://example.com".to_string(),
            final_url: "https://example.com".to_string(),
            initial_domain: "example.com".to_string(),
            final_domain: "example.com".to_string(),
            host: "example.com".to_string(),
            status: 200,
            status_desc: "OK".to_string(),
            headers,
            security_headers: HashMap::new(),
            http_headers: HashMap::new(),
            body: std::sync::Arc::<str>::from("<html><head><title>Test</title></head></html>"),
            body_sha256: None,
            body_truncated: false,
            content_length: None,
            http_version: Some("HTTP/2".to_string()),
            content_type: Some("text/html".to_string()),
        }
    }

    fn create_test_html_data() -> HtmlData {
        HtmlData {
            title: "Test Page".to_string(),
            description: Some("Test description".to_string()),
            structured_data: StructuredData::default(),
            social_media_links: vec![],
            contact_links: vec![],
            exposed_secrets: vec![],
            analytics_ids: vec![],
            meta_tags: HashMap::new(),
            script_sources: vec![],
            script_tag_ids: HashSet::new(),
            inline_script_text: String::new(),
            external_scripts_eligible: 0,
            external_scripts_scanned: 0,
            favicon_url: None,
            canonical_url: None,
            meta_refresh_url: None,
            meta_robots: None,
            resource_hints: Vec::new(),
        }
    }

    fn create_test_tls_dns_data() -> TlsDnsData {
        TlsDnsData {
            tls_version: Some(crate::models::TlsVersion::Tls13),
            subject: Some("CN=example.com".to_string()),
            issuer: Some("CN=Let's Encrypt".to_string()),
            valid_from: Some(
                NaiveDateTime::parse_from_str("2024-01-01 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap(),
            ),
            valid_to: Some(
                NaiveDateTime::parse_from_str("2024-12-31 23:59:59", "%Y-%m-%d %H:%M:%S").unwrap(),
            ),
            oids: Some(HashSet::new()),
            cipher_suite: Some("TLS_AES_256_GCM_SHA384".to_string()),
            key_algorithm: Some(crate::models::KeyAlgorithm::RSA),
            subject_alternative_names: Some(vec!["example.com".to_string()]),
            ip_address: Some("192.0.2.1".to_string()),
            reverse_dns_name: Some("example.com".to_string()),
            cert_fingerprint_sha256: None,
            cert_serial_number: None,
            cert_is_self_signed: None,
            cert_is_wildcard: None,
        }
    }

    fn create_test_additional_dns_data() -> AdditionalDnsData {
        AdditionalDnsData {
            nameservers: Some("ns1.example.com,ns2.example.com".to_string()),
            txt_records: Some("v=spf1 include:_spf.google.com ~all".to_string()),
            mx_records: Some("10 mail.example.com".to_string()),
            spf_record: Some("v=spf1 include:_spf.google.com ~all".to_string()),
            dmarc_record: Some("v=DMARC1; p=none".to_string()),
            mta_sts_record: None,
            tls_rpt_record: None,
            bimi_record: None,
            cname_chain: None,
            aaaa_records: None,
            caa_records: None,
        }
    }

    #[test]
    fn test_build_url_record_basic() {
        let resp_data = create_test_response_data();
        let html_data = create_test_html_data();
        let tls_dns_data = create_test_tls_dns_data();
        let additional_dns = create_test_additional_dns_data();
        let run_id = Some("test-run-123".to_string());

        let record = build_url_record(
            &resp_data,
            &html_data,
            &tls_dns_data,
            &additional_dns,
            1.5,
            1234567890,
            run_id.as_ref(),
        );

        assert_eq!(record.initial_domain, "example.com");
        assert_eq!(record.final_domain, "example.com");
        assert_eq!(record.ip_address, "192.0.2.1");
        assert_eq!(record.status, 200);
        assert_eq!(record.title, "Test Page");
        assert_eq!(record.description, Some("Test description".to_string()));
        assert_eq!(record.tls_version, Some(crate::models::TlsVersion::Tls13));
        assert_eq!(record.run_id, run_id);
    }

    #[test]
    fn test_build_url_record_empty_strings_normalized() {
        let resp_data = create_test_response_data();
        let mut html_data = create_test_html_data();
        html_data.description = Some("".to_string());
        let tls_dns_data = create_test_tls_dns_data();
        let additional_dns = create_test_additional_dns_data();

        let record = build_url_record(
            &resp_data,
            &html_data,
            &tls_dns_data,
            &additional_dns,
            1.5,
            1234567890,
            None,
        );

        // Empty strings should be normalized to None
        assert_eq!(record.description, None);
    }

    #[test]
    fn test_build_url_record_none_fields() {
        let resp_data = create_test_response_data();
        let mut html_data = create_test_html_data();
        html_data.description = None;
        let tls_dns_data = create_test_tls_dns_data();
        let additional_dns = create_test_additional_dns_data();

        let record = build_url_record(
            &resp_data,
            &html_data,
            &tls_dns_data,
            &additional_dns,
            1.5,
            1234567890,
            None,
        );

        assert_eq!(record.description, None);
    }

    #[test]
    fn test_build_persisted_url_record_basic() {
        let resp_data = create_test_response_data();
        let html_data = create_test_html_data();
        let tls_dns_data = create_test_tls_dns_data();
        let additional_dns = create_test_additional_dns_data();
        let run_id = Some("test-run-123".to_string());

        let url_record = build_url_record(
            &resp_data,
            &html_data,
            &tls_dns_data,
            &additional_dns,
            1.5,
            1234567890,
            run_id.as_ref(),
        );

        let technologies = vec![
            crate::fingerprint::DetectedTechnology {
                name: "WordPress".to_string(),
                version: None,
                category: None,
                is_implied: false,
                detection_source: None,
            },
            crate::fingerprint::DetectedTechnology {
                name: "PHP".to_string(),
                version: None,
                category: None,
                is_implied: false,
                detection_source: None,
            },
        ];
        let redirect_chain = vec![("https://example.com".to_string(), 200)];
        let partial_failures = vec![(ErrorType::DnsNsLookupError, "DNS lookup failed".to_string())];
        let geoip_data = Some((
            "192.0.2.1".to_string(),
            GeoIpResult {
                country_code: Some("US".to_string()),
                country_name: Some("United States".to_string()),
                ..Default::default()
            },
        ));
        let whois_data = Some(WhoisResult {
            registrar: Some("Example Registrar".to_string()),
            ..Default::default()
        });

        let persisted_record = build_persisted_url_record(PersistedUrlRecordParams {
            record: url_record,
            resp_data,
            html_data,
            tls_dns_data,
            technologies_vec: technologies.clone(),
            redirect_chain,
            partial_failures,
            geoip_data,
            whois_data,
            timestamp: 1234567890,
            run_id,
            favicon: None,
            well_known: crate::fetch::well_known::WellKnownData::default(),
            additional_dns: create_test_additional_dns_data(),
        });

        assert_eq!(persisted_record.url_record.final_domain, "example.com");
        assert_eq!(persisted_record.technologies.len(), 2);
        assert!(persisted_record
            .technologies
            .iter()
            .any(|t| t.name == "PHP"));
        assert_eq!(persisted_record.redirect_chain.len(), 1);
        assert_eq!(persisted_record.partial_failures.len(), 1);
        assert!(persisted_record.geoip.is_some());
        assert!(persisted_record.whois.is_some());
    }

    #[test]
    fn test_build_persisted_url_record_empty_oids() {
        let resp_data = create_test_response_data();
        let html_data = create_test_html_data();
        let mut tls_dns_data = create_test_tls_dns_data();
        tls_dns_data.oids = None; // Test None OIDs
        let additional_dns = create_test_additional_dns_data();

        let url_record = build_url_record(
            &resp_data,
            &html_data,
            &tls_dns_data,
            &additional_dns,
            1.5,
            1234567890,
            None,
        );

        let persisted_record = build_persisted_url_record(PersistedUrlRecordParams {
            record: url_record,
            resp_data,
            html_data,
            tls_dns_data,
            technologies_vec: vec![],
            redirect_chain: vec![],
            partial_failures: vec![],
            geoip_data: None,
            whois_data: None,
            timestamp: 1234567890,
            run_id: None,
            favicon: None,
            well_known: crate::fetch::well_known::WellKnownData::default(),
            additional_dns: create_test_additional_dns_data(),
        });

        assert!(persisted_record.oids.is_empty());
    }

    #[test]
    fn test_build_persisted_url_record_empty_sans() {
        let resp_data = create_test_response_data();
        let html_data = create_test_html_data();
        let mut tls_dns_data = create_test_tls_dns_data();
        tls_dns_data.subject_alternative_names = None; // Test None SANs
        let additional_dns = create_test_additional_dns_data();

        let url_record = build_url_record(
            &resp_data,
            &html_data,
            &tls_dns_data,
            &additional_dns,
            1.5,
            1234567890,
            None,
        );

        let persisted_record = build_persisted_url_record(PersistedUrlRecordParams {
            record: url_record,
            resp_data,
            html_data,
            tls_dns_data,
            technologies_vec: vec![],
            redirect_chain: vec![],
            partial_failures: vec![],
            geoip_data: None,
            whois_data: None,
            timestamp: 1234567890,
            run_id: None,
            favicon: None,
            well_known: crate::fetch::well_known::WellKnownData::default(),
            additional_dns: create_test_additional_dns_data(),
        });

        assert!(persisted_record.subject_alternative_names.is_empty());
    }

    #[test]
    fn test_build_persisted_url_record_partial_failures() {
        let resp_data = create_test_response_data();
        let html_data = create_test_html_data();
        let tls_dns_data = create_test_tls_dns_data();
        let additional_dns = create_test_additional_dns_data();

        let url_record = build_url_record(
            &resp_data,
            &html_data,
            &tls_dns_data,
            &additional_dns,
            1.5,
            1234567890,
            None,
        );

        let partial_failures = vec![
            (ErrorType::DnsNsLookupError, "NS lookup failed".to_string()),
            (
                ErrorType::DnsTxtLookupError,
                "TXT lookup failed".to_string(),
            ),
        ];

        let persisted_record = build_persisted_url_record(PersistedUrlRecordParams {
            record: url_record,
            resp_data,
            html_data,
            tls_dns_data,
            technologies_vec: vec![],
            redirect_chain: vec![],
            partial_failures,
            geoip_data: None,
            whois_data: None,
            timestamp: 1234567890,
            run_id: None,
            favicon: None,
            well_known: crate::fetch::well_known::WellKnownData::default(),
            additional_dns: create_test_additional_dns_data(),
        });

        assert_eq!(persisted_record.partial_failures.len(), 2);
        assert_eq!(
            persisted_record.partial_failures[0].error_type,
            ErrorType::DnsNsLookupError
        );
        assert_eq!(
            persisted_record.partial_failures[1].error_type,
            ErrorType::DnsTxtLookupError
        );
    }

    #[test]
    fn test_build_url_record_whitespace_only_strings() {
        // Test that whitespace-only strings are NOT normalized to None
        // Only empty strings are normalized - whitespace is preserved
        let resp_data = create_test_response_data();
        let mut html_data = create_test_html_data();
        html_data.description = Some("\t\n".to_string()); // Whitespace only
        let tls_dns_data = create_test_tls_dns_data();
        let additional_dns = create_test_additional_dns_data();

        let record = build_url_record(
            &resp_data,
            &html_data,
            &tls_dns_data,
            &additional_dns,
            1.5,
            1234567890,
            None,
        );

        // Whitespace-only strings should be preserved (not normalized to None)
        // This is intentional - only truly empty strings are normalized
        // Description still normalizes empty but preserves whitespace-only.
        assert_eq!(record.description, Some("\t\n".to_string()));
    }

    #[test]
    fn test_build_persisted_url_record_duplicate_oids() {
        // Test that duplicate OIDs are deduplicated (HashSet behavior)
        let resp_data = create_test_response_data();
        let html_data = create_test_html_data();
        let mut tls_dns_data = create_test_tls_dns_data();
        let mut oids = HashSet::new();
        oids.insert("1.2.3.4".to_string());
        oids.insert("1.2.3.4".to_string()); // Duplicate
        oids.insert("5.6.7.8".to_string());
        tls_dns_data.oids = Some(oids);
        let additional_dns = create_test_additional_dns_data();

        let url_record = build_url_record(
            &resp_data,
            &html_data,
            &tls_dns_data,
            &additional_dns,
            1.5,
            1234567890,
            None,
        );

        let persisted_record = build_persisted_url_record(PersistedUrlRecordParams {
            record: url_record,
            resp_data,
            html_data,
            tls_dns_data,
            technologies_vec: vec![],
            redirect_chain: vec![],
            partial_failures: vec![],
            geoip_data: None,
            whois_data: None,
            timestamp: 1234567890,
            run_id: None,
            favicon: None,
            well_known: crate::fetch::well_known::WellKnownData::default(),
            additional_dns: create_test_additional_dns_data(),
        });

        // Duplicate OIDs should be deduplicated by HashSet
        assert_eq!(persisted_record.oids.len(), 2); // Only 2 unique OIDs
        assert!(persisted_record.oids.contains("1.2.3.4"));
        assert!(persisted_record.oids.contains("5.6.7.8"));
    }

    #[test]
    fn test_build_persisted_url_record_duplicate_sans() {
        // Test that duplicate SANs are preserved (Vec, not HashSet)
        let resp_data = create_test_response_data();
        let html_data = create_test_html_data();
        let mut tls_dns_data = create_test_tls_dns_data();
        tls_dns_data.subject_alternative_names = Some(vec![
            "example.com".to_string(),
            "www.example.com".to_string(),
            "example.com".to_string(), // Duplicate
        ]);
        let additional_dns = create_test_additional_dns_data();

        let url_record = build_url_record(
            &resp_data,
            &html_data,
            &tls_dns_data,
            &additional_dns,
            1.5,
            1234567890,
            None,
        );

        let persisted_record = build_persisted_url_record(PersistedUrlRecordParams {
            record: url_record,
            resp_data,
            html_data,
            tls_dns_data,
            technologies_vec: vec![],
            redirect_chain: vec![],
            partial_failures: vec![],
            geoip_data: None,
            whois_data: None,
            timestamp: 1234567890,
            run_id: None,
            favicon: None,
            well_known: crate::fetch::well_known::WellKnownData::default(),
            additional_dns: create_test_additional_dns_data(),
        });

        // SANs are Vec, so duplicates are preserved (this is intentional - matches cert data)
        assert_eq!(persisted_record.subject_alternative_names.len(), 3);
        assert_eq!(persisted_record.subject_alternative_names[0], "example.com");
        assert_eq!(persisted_record.subject_alternative_names[2], "example.com");
    }

    #[test]
    fn test_build_persisted_url_record_large_redirect_chain() {
        // Test that large redirect chains are handled correctly
        let resp_data = create_test_response_data();
        let html_data = create_test_html_data();
        let tls_dns_data = create_test_tls_dns_data();
        let additional_dns = create_test_additional_dns_data();

        let url_record = build_url_record(
            &resp_data,
            &html_data,
            &tls_dns_data,
            &additional_dns,
            1.5,
            1234567890,
            None,
        );

        // Create a large redirect chain (100 URLs)
        let redirect_chain: Vec<(String, u16)> = (0..100)
            .map(|i| (format!("https://example.com/redirect{}", i), 302))
            .collect();

        let persisted_record = build_persisted_url_record(PersistedUrlRecordParams {
            record: url_record,
            resp_data,
            html_data,
            tls_dns_data,
            technologies_vec: vec![],
            redirect_chain,
            partial_failures: vec![],
            geoip_data: None,
            whois_data: None,
            timestamp: 1234567890,
            run_id: None,
            favicon: None,
            well_known: crate::fetch::well_known::WellKnownData::default(),
            additional_dns: create_test_additional_dns_data(),
        });

        // Large redirect chain should be preserved
        assert_eq!(persisted_record.redirect_chain.len(), 100);
        assert_eq!(
            persisted_record.redirect_chain[0].0,
            "https://example.com/redirect0"
        );
        assert_eq!(
            persisted_record.redirect_chain[99].0,
            "https://example.com/redirect99"
        );
    }

    #[test]
    fn test_build_persisted_url_record_run_id_propagation() {
        // Test that run_id is correctly propagated to partial failure records
        let resp_data = create_test_response_data();
        let html_data = create_test_html_data();
        let tls_dns_data = create_test_tls_dns_data();
        let additional_dns = create_test_additional_dns_data();

        let url_record = build_url_record(
            &resp_data,
            &html_data,
            &tls_dns_data,
            &additional_dns,
            1.5,
            1234567890,
            None,
        );

        let run_id = Some("test-run-456".to_string());
        let partial_failures = vec![(ErrorType::DnsNsLookupError, "Test error".to_string())];

        let persisted_record = build_persisted_url_record(PersistedUrlRecordParams {
            record: url_record,
            resp_data,
            html_data,
            tls_dns_data,
            technologies_vec: vec![],
            redirect_chain: vec![],
            partial_failures,
            geoip_data: None,
            whois_data: None,
            timestamp: 1234567890,
            run_id: run_id.clone(),
            favicon: None,
            well_known: crate::fetch::well_known::WellKnownData::default(),
            additional_dns: create_test_additional_dns_data(),
        });

        // Run ID should be propagated to partial failure records
        assert_eq!(persisted_record.partial_failures.len(), 1);
        assert_eq!(persisted_record.partial_failures[0].run_id, run_id);
    }

    /// Kills: dropping `cdn.example.com`, keeping `'self'` / `none` /
    /// `unsafe-inline`, leaving a `*.` wildcard on the captured host, or
    /// skipping `to_lowercase` on the FQDN.
    #[rstest::rstest]
    #[case::happy(
        "default-src https://cdn.example.com; script-src 'self' https://*.example.net none 'unsafe-inline'",
        &[
            ("default-src", "cdn.example.com", Some("example.com")),
            ("script-src", "example.net", Some("example.net")),
        ]
    )]
    #[case::uppercased_host(
        "default-src HTTPS://CDN.EXAMPLE.COM",
        &[("default-src", "cdn.example.com", Some("example.com"))]
    )]
    fn extract_csp_domains_happy_path(
        #[case] csp: &str,
        #[case] expected: &[(&str, &str, Option<&str>)],
    ) {
        let got = extract_csp_domains(csp);
        let got: Vec<(&str, &str, Option<&str>)> = got
            .iter()
            .map(|(d, f, r)| (d.as_str(), f.as_str(), r.as_deref()))
            .collect();
        assert_eq!(got, expected);
    }

    /// Kills: panicking on empty / `;;;` / no-space / `javascript:` / `data:`,
    /// or inventing a host from those tokens.
    #[rstest::rstest]
    #[case::empty("")]
    #[case::semicolons(";;;")]
    #[case::no_space("default-srchttps://cdn.example.com")]
    #[case::javascript("javascript:")]
    #[case::data("data:")]
    fn extract_csp_domains_hostile_omits_hosts(#[case] csp: &str) {
        assert!(extract_csp_domains(csp).is_empty());
    }

    /// Kills: adding an IP filter that drops `192.0.2.1`, or panicking on it.
    #[test]
    fn extract_csp_domains_documentation_ip() {
        let got = extract_csp_domains("default-src http://192.0.2.1");
        assert_eq!(
            got,
            vec![(
                "default-src".to_string(),
                "192.0.2.1".to_string(),
                Some("2.1".to_string()),
            )]
        );
    }

    proptest! {
        /// Kills: `extract_csp_domains` panicking on arbitrary ASCII or returning
        /// a mixed-case FQDN.
        #[test]
        fn extract_csp_domains_random_ascii_never_panics(
            s in prop::collection::vec(0u8..=127, 0..128)
                .prop_map(|b| String::from_utf8(b).expect("ASCII"))
        ) {
            let rows = extract_csp_domains(&s);
            for (_, fqdn, _) in &rows {
                prop_assert_eq!(fqdn, &fqdn.to_lowercase());
            }
        }
    }
}