pq-map 0.2.3

Domain service and cryptography discovery from Certificate Transparency and DNS
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
use std::collections::BTreeMap;
use std::net::IpAddr;

use chrono::{DateTime, Local, Utc};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Origins(u8);

impl Origins {
    pub const NONE: Self = Self(0);
    pub const CT: Self = Self(1);
    pub const DNS: Self = Self(2);
    pub const APEX: Self = Self(4);

    pub fn insert(&mut self, other: Self) {
        self.0 |= other.0;
    }

    pub fn contains(self, other: Self) -> bool {
        self.0 & other.0 != 0
    }

    fn labels(self) -> Vec<&'static str> {
        let mut out = Vec::new();
        if self.contains(Self::CT) {
            out.push("ct");
        }
        if self.contains(Self::DNS) {
            out.push("dns");
        }
        if self.contains(Self::APEX) {
            out.push("apex");
        }
        out
    }
}

impl Serialize for Origins {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_seq(self.labels())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MatchKind {
    Exact,
    Wildcard,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "source")]
pub enum ProbeStatus {
    Ok,
    DnsFailure,
    TcpRefused,
    TcpUnreachable,
    Timeout { secs: u64 },
    TlsHandshakeFailed,
    ConnectedNoCert,
    Unknown { reason: String },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChainEntry {
    pub depth: u32,
    pub certificate_id: u64,
    pub common_name: Option<String>,
    pub ski: Option<String>,
    pub aki: Option<String>,
    pub not_before: Option<DateTime<Utc>>,
    pub not_after: Option<DateTime<Utc>>,
    pub key_algorithm: Option<String>,
    pub key_size: Option<i64>,
    pub signature_key_algorithm: Option<String>,
    pub signature_hash_algorithm: Option<String>,
    pub issuer_ca_name: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Certificate {
    pub serial: String,
    pub in_ct: bool,
    pub served_live: bool,
    pub currently_valid: bool,
    pub ct_ids: Vec<u64>,
    pub common_name: Option<String>,
    pub identities: Vec<String>,
    pub not_before: Option<DateTime<Utc>>,
    pub not_after: Option<DateTime<Utc>>,
    pub pubkey_alg: Option<String>,
    pub sig_alg: Option<String>,
    pub issuer: Option<String>,
    pub key_algorithm: Option<String>,
    pub key_size: Option<i64>,
    pub sig_key_algorithm: Option<String>,
    pub sig_hash_algorithm: Option<String>,
    pub cert_signature: Option<String>,
    #[serde(default)]
    pub chain: Vec<ChainEntry>,
}

#[derive(Debug, Clone, Serialize)]
pub struct CertRef {
    pub serial: String,
    pub kind: MatchKind,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "snake_case", tag = "source")]
pub enum DnsRef {
    Srv { service: String },
    Https,
}

/// DNS response status for the A/AAAA lookup of a host (RFC 1035 rcodes).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DnsStatus {
    /// NOERROR with address records.
    Ok,
    /// NOERROR, name exists, but no A/AAAA records (NODATA).
    NoData,
    /// NXDOMAIN — the name does not exist.
    NxDomain,
    ServFail,
    Refused,
    /// Resolver gave up within its timeout budget.
    Timeout,
    /// Any other response code or transport failure.
    Other,
}

impl DnsStatus {
    pub fn label(&self) -> &'static str {
        match self {
            Self::Ok => "resolves",
            Self::NoData => "no data",
            Self::NxDomain => "nxdomain",
            Self::ServFail => "servfail",
            Self::Refused => "refused",
            Self::Timeout => "timeout",
            Self::Other => "unknown",
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServedCert {
    pub serial: String,
    pub common_name: Option<String>,
    pub identities: Vec<String>,
    pub pubkey_alg: Option<String>,
    pub sig_alg: Option<String>,
    pub issuer: Option<String>,
    pub not_before: Option<DateTime<Utc>>,
    pub not_after: Option<DateTime<Utc>>,
    /// Signature algorithms of the served chain, leaf first.
    pub chain_sigs: Vec<String>,
    pub pubkey_curve: Option<String>,
    pub cert_signature: Option<String>,
}

/// Crypto negotiated during the live handshake.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Negotiated {
    pub tls_version: Option<String>,
    pub kx_group: Option<String>,
    pub cipher: Option<String>,
}

impl ServedCert {
    pub fn into_certificate(self) -> Certificate {
        let currently_valid =
            crate::discover::ct::currently_valid(self.not_before, self.not_after, Utc::now());
        Certificate {
            serial: self.serial,
            in_ct: false,
            served_live: true,
            currently_valid,
            ct_ids: Vec::new(),
            common_name: self.common_name,
            identities: self.identities,
            not_before: self.not_before,
            not_after: self.not_after,
            pubkey_alg: self.pubkey_alg,
            sig_alg: self.sig_alg,
            issuer: self.issuer,
            key_algorithm: None,
            key_size: None,
            sig_key_algorithm: None,
            sig_hash_algorithm: None,
            cert_signature: self.cert_signature,
            chain: Vec::new(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Endpoint {
    pub status: ProbeStatus,
    pub ip: Option<IpAddr>,
    pub served: Option<ServedCert>,
    pub served_not_in_ct: bool,
    pub negotiated: Option<Negotiated>,
    pub observed_at: Option<DateTime<Utc>>,
}

impl Endpoint {
    pub fn failed(status: ProbeStatus) -> Self {
        Self {
            status,
            ip: None,
            served: None,
            served_not_in_ct: false,
            negotiated: None,
            observed_at: None,
        }
    }
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct Host {
    pub name: String,
    pub origins: Origins,
    pub resolves: Option<bool>,
    pub dns_status: Option<DnsStatus>,
    pub ct_refs: Vec<CertRef>,
    pub dns_refs: Vec<DnsRef>,
    pub endpoint: Option<Endpoint>,
    pub ports: Vec<PortScan>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ScanState {
    Open,
    Closed,
    Filtered,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PortScan {
    pub port: u16,
    pub state: ScanState,
    pub served: Option<ServedCert>,
    pub negotiated: Option<Negotiated>,
    pub observed_at: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, Serialize)]
pub struct SrvRecord {
    pub service: String,
    pub fqdn: String,
    pub priority: u32,
    pub weight: u32,
    pub port: u16,
    pub target: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct MxRecord {
    pub priority: u32,
    pub target: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct HttpsRecord {
    pub rr_type: String,
    pub priority: u16,
    pub target: String,
    pub params: String,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Provenance {
    Fresh,
    Cached { age_secs: u64 },
    Stale { age_secs: Option<u64> },
}

fn hash_norm(raw: &str) -> String {
    raw.trim().to_ascii_uppercase().replace('-', "")
}

pub fn alg_class_of(raw: &str) -> String {
    let lower = raw.trim().to_ascii_lowercase();
    if lower.contains("ed25519") {
        "Ed25519".to_string()
    } else if lower.contains("ed448") {
        "Ed448".to_string()
    } else if lower.starts_with("ml-dsa") || lower.contains("mldsa") {
        raw.trim().to_string()
    } else if lower.contains("ecdsa") || lower.contains("ecpublickey") || lower == "ec" {
        "ECDSA".to_string()
    } else if lower.contains("rsa") {
        "RSA".to_string()
    } else {
        raw.trim().to_string()
    }
}

pub fn curve_from_key_size(size: i64) -> Option<&'static str> {
    match size {
        256 => Some("P256"),
        384 => Some("P384"),
        521 => Some("P521"),
        _ => None,
    }
}

pub fn cert_key_name(
    alg: Option<&str>,
    key_size: Option<i64>,
    curve: Option<&str>,
) -> Option<String> {
    let class = alg_class_of(alg?);
    if class == "ECDSA" {
        let bits = key_size.or_else(|| {
            curve.and_then(|c| c.trim().trim_start_matches(['P', 'p', '-']).parse().ok())
        });
        return Some(match bits {
            Some(b) => format!("EC-{b}"),
            None => "EC".to_string(),
        });
    }
    Some(match key_size {
        Some(b) => format!("{class}-{b}"),
        None => class,
    })
}

pub fn cert_signature_name(class: &str, hash: Option<&str>, curve: Option<&str>) -> Option<String> {
    let class = alg_class_of(class);
    match class.as_str() {
        "RSA" => Some(match hash.map(hash_norm) {
            Some(h) => format!("RSA-{h}"),
            None => "RSA".to_string(),
        }),
        "ECDSA" => Some(match curve {
            Some(c) => format!("ECDSA-{c}"),
            None => "ECDSA".to_string(),
        }),
        other => Some(other.to_string()),
    }
}

pub fn cert_signature_from_db(
    key_algorithm: Option<&str>,
    key_size: Option<i64>,
    sig_key_algorithm: Option<&str>,
    sig_hash_algorithm: Option<&str>,
) -> Option<String> {
    let class = sig_key_algorithm.or(key_algorithm)?;
    let curve = if alg_class_of(class) == "ECDSA" {
        key_size.and_then(curve_from_key_size)
    } else {
        None
    };
    cert_signature_name(class, sig_hash_algorithm, curve)
}

pub fn port_service(port: u16) -> &'static str {
    match port {
        25 | 587 => "SMTP",
        465 => "SMTPS",
        993 => "IMAPS",
        995 => "POP3S",
        636 => "LDAPS",
        5061 => "SIPS",
        8883 => "MQTTS",
        5222 => "XMPP",
        5223 => "XMPPS",
        _ => "TLS",
    }
}

pub fn symmetric_name(cipher: &str) -> Option<String> {
    let upper = cipher.to_ascii_uppercase();
    if upper.contains("CHACHA20") {
        return Some("CHACHA20-POLY1305".to_string());
    }
    let bits = if upper.contains("AES_128") {
        "AES128"
    } else if upper.contains("AES_256") {
        "AES256"
    } else {
        return None;
    };
    let mode = if upper.contains("GCM") {
        "GCM"
    } else if upper.contains("CBC") {
        "CBC"
    } else {
        return None;
    };
    Some(format!("{bits}-{mode}"))
}

#[derive(Debug, Clone, Copy, Default, Serialize)]
pub struct CtStats {
    /// Number of raw crt.sh log entries in the snapshot.
    pub rows: usize,
    /// Log entries currently valid (not_before <= now <= not_after).
    pub valid: usize,
    /// Log entries that are not valid yet.
    pub future: usize,
}

#[derive(Debug, Serialize)]
pub struct DomainState {
    pub domain: String,
    pub checked_at: DateTime<Local>,
    pub provenance: Provenance,
    pub ct_stats: CtStats,
    pub certs: BTreeMap<String, Certificate>,
    pub hosts: BTreeMap<String, Host>,
    pub srv: Vec<SrvRecord>,
    pub https: Vec<HttpsRecord>,
    pub mx: Vec<MxRecord>,
}

impl DomainState {
    pub fn host_names(&self) -> Vec<String> {
        self.hosts.keys().cloned().collect()
    }
}

#[cfg(test)]
pub fn fixture() -> DomainState {
    use chrono::TimeZone;

    let now = Utc::now();
    let nb = now - chrono::Duration::days(30);
    let na = now + chrono::Duration::days(30);
    let observed = Utc.with_ymd_and_hms(2026, 9, 21, 12, 0, 0).unwrap();

    let mut certs = BTreeMap::new();
    certs.insert(
        "aa11".to_string(),
        Certificate {
            serial: "aa11".to_string(),
            in_ct: true,
            served_live: true,
            currently_valid: true,
            ct_ids: vec![9612296601],
            common_name: Some("www.example.com".to_string()),
            identities: vec!["example.com".to_string(), "www.example.com".to_string()],
            not_before: Some(nb),
            not_after: Some(na),
            pubkey_alg: Some("RSA".to_string()),
            sig_alg: Some("SHA256/RSA".to_string()),
            issuer: Some("CN=DigiCert TLS RSA SHA256 2020 CA-1".to_string()),
            key_algorithm: Some("RSA".to_string()),
            key_size: Some(2048),
            sig_key_algorithm: Some("RSA".to_string()),
            sig_hash_algorithm: Some("SHA-256".to_string()),
            cert_signature: Some("RSA-SHA256".to_string()),
            chain: vec![
                ChainEntry {
                    depth: 0,
                    certificate_id: 9612296601,
                    common_name: Some("www.example.com".to_string()),
                    ski: Some("aabb".to_string()),
                    aki: None,
                    not_before: Some(nb),
                    not_after: Some(na),
                    key_algorithm: Some("RSA".to_string()),
                    key_size: Some(2048),
                    signature_key_algorithm: Some("RSA".to_string()),
                    signature_hash_algorithm: Some("SHA-256".to_string()),
                    issuer_ca_name: Some("CN=DigiCert TLS RSA SHA256 2020 CA-1".to_string()),
                },
                ChainEntry {
                    depth: 1,
                    certificate_id: 90000000001,
                    common_name: Some("DigiCert TLS RSA SHA256 2020 CA-1".to_string()),
                    ski: Some("bbcc".to_string()),
                    aki: Some("aabb".to_string()),
                    not_before: Some(nb),
                    not_after: Some(na),
                    key_algorithm: Some("RSA".to_string()),
                    key_size: Some(2048),
                    signature_key_algorithm: Some("RSA".to_string()),
                    signature_hash_algorithm: Some("SHA-256".to_string()),
                    issuer_ca_name: Some("CN=DigiCert Global Root CA".to_string()),
                },
                ChainEntry {
                    depth: 2,
                    certificate_id: 90000000002,
                    common_name: Some("DigiCert Global Root CA".to_string()),
                    ski: Some("ccdd".to_string()),
                    aki: Some("bbcc".to_string()),
                    not_before: Some(nb),
                    not_after: Some(na),
                    key_algorithm: Some("RSA".to_string()),
                    key_size: Some(2048),
                    signature_key_algorithm: Some("RSA".to_string()),
                    signature_hash_algorithm: Some("SHA-256".to_string()),
                    issuer_ca_name: Some("CN=DigiCert Global Root CA".to_string()),
                },
            ],
        },
    );
    certs.insert(
        "cc33".to_string(),
        Certificate {
            serial: "cc33".to_string(),
            in_ct: true,
            served_live: false,
            currently_valid: true,
            ct_ids: vec![9612300001],
            common_name: Some("eas.example.com".to_string()),
            identities: vec!["eas.example.com".to_string()],
            not_before: Some(nb),
            not_after: Some(na - chrono::Duration::days(10)),
            pubkey_alg: None,
            sig_alg: None,
            issuer: Some("CN=Certum OV TLS G2 R39 CA".to_string()),
            key_algorithm: Some("RSA".to_string()),
            key_size: Some(2048),
            sig_key_algorithm: Some("RSA".to_string()),
            sig_hash_algorithm: Some("SHA-256".to_string()),
            cert_signature: Some("RSA-SHA256".to_string()),
            chain: Vec::new(),
        },
    );
    certs.insert(
        "bb22".to_string(),
        Certificate {
            serial: "bb22".to_string(),
            in_ct: true,
            served_live: false,
            currently_valid: true,
            ct_ids: vec![9612297416, 9612300000],
            common_name: Some("*.example.com".to_string()),
            identities: vec!["*.example.com".to_string()],
            not_before: Some(nb),
            not_after: Some(na),
            pubkey_alg: None,
            sig_alg: None,
            issuer: None,
            key_algorithm: Some("EC".to_string()),
            key_size: Some(256),
            sig_key_algorithm: Some("ECDSA".to_string()),
            sig_hash_algorithm: Some("SHA-256".to_string()),
            cert_signature: Some("ECDSA-P256".to_string()),
            chain: Vec::new(),
        },
    );

    let mut hosts = BTreeMap::new();
    let mut www = Host {
        name: "www.example.com".to_string(),
        origins: Origins::CT,
        resolves: Some(true),
        dns_status: Some(DnsStatus::Ok),
        ct_refs: vec![CertRef {
            serial: "aa11".to_string(),
            kind: MatchKind::Exact,
        }],
        dns_refs: Vec::new(),
        ports: Vec::new(),
        endpoint: Some(Endpoint {
            status: ProbeStatus::Ok,
            negotiated: Some(Negotiated {
                tls_version: Some("TLS1.3".to_string()),
                kx_group: Some("X25519MLKEM768".to_string()),
                cipher: Some("TLS13_AES_256_GCM_SHA384".to_string()),
            }),
            ip: Some("104.94.222.171".parse().unwrap()),
            served: Some(ServedCert {
                serial: "aa11".to_string(),
                common_name: Some("www.example.com".to_string()),
                identities: vec!["example.com".to_string(), "www.example.com".to_string()],
                pubkey_alg: Some("RSA".to_string()),
                sig_alg: Some("SHA256/RSA".to_string()),
                issuer: Some("CN=DigiCert TLS RSA SHA256 2020 CA-1".to_string()),
                not_before: Some(nb),
                not_after: Some(na),
                chain_sigs: vec!["SHA256/RSA".to_string()],
                pubkey_curve: None,
                cert_signature: Some("RSA-SHA256".to_string()),
            }),
            served_not_in_ct: false,
            observed_at: Some(observed),
        }),
    };
    www.origins.insert(Origins::DNS);
    hosts.insert("www.example.com".to_string(), www);
    hosts.insert(
        "example.com".to_string(),
        Host {
            name: "example.com".to_string(),
            origins: Origins::APEX,
            resolves: Some(true),
            dns_status: Some(DnsStatus::Ok),
            ct_refs: vec![CertRef {
                serial: "aa11".to_string(),
                kind: MatchKind::Exact,
            }],
            dns_refs: Vec::new(),
            ports: Vec::new(),
            endpoint: Some(Endpoint {
                status: ProbeStatus::Ok,
                ip: Some("104.94.222.1".parse().unwrap()),
                served: Some(ServedCert {
                    serial: "aa11".to_string(),
                    common_name: Some("www.example.com".to_string()),
                    identities: vec!["example.com".to_string(), "www.example.com".to_string()],
                    pubkey_alg: Some("RSA".to_string()),
                    sig_alg: Some("SHA256/RSA".to_string()),
                    issuer: Some("CN=DigiCert TLS RSA SHA256 2020 CA-1".to_string()),
                    not_before: Some(nb),
                    not_after: Some(na),
                    chain_sigs: vec!["SHA256/RSA".to_string()],
                    pubkey_curve: None,
                    cert_signature: Some("RSA-SHA256".to_string()),
                }),
                served_not_in_ct: false,
                observed_at: Some(observed),
                negotiated: Some(Negotiated {
                    tls_version: Some("TLS1.3".to_string()),
                    kx_group: Some("X25519MLKEM768".to_string()),
                    cipher: Some("TLS13_AES_256_GCM_SHA384".to_string()),
                }),
            }),
        },
    );
    hosts.insert(
        "old.example.com".to_string(),
        Host {
            name: "old.example.com".to_string(),
            origins: Origins::CT,
            resolves: Some(false),
            dns_status: Some(DnsStatus::NxDomain),
            ct_refs: vec![CertRef {
                serial: "bb22".to_string(),
                kind: MatchKind::Wildcard,
            }],
            dns_refs: Vec::new(),
            ports: Vec::new(),
            endpoint: Some(Endpoint::failed(ProbeStatus::DnsFailure)),
        },
    );
    hosts.insert(
        "vpn.example.com".to_string(),
        Host {
            name: "vpn.example.com".to_string(),
            origins: Origins::CT,
            resolves: Some(true),
            dns_status: Some(DnsStatus::Ok),
            ct_refs: vec![CertRef {
                serial: "bb22".to_string(),
                kind: MatchKind::Wildcard,
            }],
            dns_refs: Vec::new(),
            ports: Vec::new(),
            endpoint: Some(Endpoint::failed(ProbeStatus::TcpRefused)),
        },
    );
    hosts.insert(
        "eas.example.com".to_string(),
        Host {
            name: "eas.example.com".to_string(),
            origins: Origins::CT,
            resolves: Some(true),
            dns_status: Some(DnsStatus::Ok),
            ct_refs: vec![
                CertRef {
                    serial: "bb22".to_string(),
                    kind: MatchKind::Wildcard,
                },
                CertRef {
                    serial: "cc33".to_string(),
                    kind: MatchKind::Exact,
                },
            ],
            dns_refs: Vec::new(),
            ports: vec![
                PortScan {
                    port: 465,
                    state: ScanState::Open,
                    served: Some(ServedCert {
                        serial: "cc33".to_string(),
                        common_name: Some("eas.example.com".to_string()),
                        identities: vec!["eas.example.com".to_string()],
                        pubkey_alg: Some("RSA".to_string()),
                        sig_alg: Some("SHA256/RSA".to_string()),
                        issuer: Some("CN=Certum OV TLS G2 R39 CA".to_string()),
                        not_before: Some(nb),
                        not_after: Some(na - chrono::Duration::days(10)),
                        chain_sigs: vec!["SHA256/RSA".to_string()],
                        pubkey_curve: None,
                        cert_signature: Some("RSA-SHA256".to_string()),
                    }),
                    negotiated: Some(Negotiated {
                        tls_version: Some("TLS1.3".to_string()),
                        kx_group: Some("X25519".to_string()),
                        cipher: Some("TLS_AES_256_GCM_SHA384".to_string()),
                    }),
                    observed_at: Some(observed),
                },
                PortScan {
                    port: 25,
                    state: ScanState::Open,
                    served: Some(ServedCert {
                        serial: "cc33".to_string(),
                        common_name: Some("eas.example.com".to_string()),
                        identities: vec!["eas.example.com".to_string()],
                        pubkey_alg: Some("RSA".to_string()),
                        sig_alg: Some("SHA256/RSA".to_string()),
                        issuer: Some("CN=Certum OV TLS G2 R39 CA".to_string()),
                        not_before: Some(nb),
                        not_after: Some(na - chrono::Duration::days(10)),
                        chain_sigs: vec!["SHA256/RSA".to_string()],
                        pubkey_curve: None,
                        cert_signature: Some("RSA-SHA256".to_string()),
                    }),
                    negotiated: Some(Negotiated {
                        tls_version: Some("TLS1.3".to_string()),
                        kx_group: Some("X25519".to_string()),
                        cipher: Some("TLS_AES_256_GCM_SHA384".to_string()),
                    }),
                    observed_at: Some(observed),
                },
            ],
            endpoint: Some(Endpoint::failed(ProbeStatus::TcpRefused)),
        },
    );
    let mut apex = hosts.get("example.com").cloned().unwrap();
    apex.origins.insert(Origins::CT);
    hosts.insert("example.com".to_string(), apex);

    DomainState {
        domain: "example.com".to_string(),
        checked_at: Local.with_ymd_and_hms(2026, 9, 21, 12, 0, 0).unwrap(),
        provenance: Provenance::Cached { age_secs: 2520 },
        certs,
        hosts,
        mx: vec![MxRecord {
            priority: 10,
            target: "eas.example.com".to_string(),
        }],
        srv: vec![SrvRecord {
            service: "_sip._tls".to_string(),
            fqdn: "_sip._tls.example.com".to_string(),
            priority: 1,
            weight: 100,
            port: 443,
            target: "sipdir.online.lync.com".to_string(),
        }],
        https: vec![HttpsRecord {
            rr_type: "HTTPS".to_string(),
            priority: 1,
            target: ".".to_string(),
            params: "alpn=h2,h3".to_string(),
        }],
        ct_stats: CtStats {
            rows: 2,
            valid: 1,
            future: 1,
        },
    }
}

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

    #[test]
    fn cert_signature_names_are_canonical() {
        assert_eq!(
            cert_signature_from_db(Some("RSA"), Some(2048), Some("RSA"), Some("SHA-256")),
            Some("RSA-SHA256".to_string())
        );
        assert_eq!(
            cert_signature_from_db(Some("EC"), Some(256), Some("ECDSA"), Some("SHA-256")),
            Some("ECDSA-P256".to_string())
        );
        assert_eq!(
            cert_signature_from_db(Some("EC"), Some(384), Some("ECDSA"), Some("SHA-384")),
            Some("ECDSA-P384".to_string())
        );
        assert_eq!(
            cert_signature_name("rsaEncryption", Some("sha256"), None),
            Some("RSA-SHA256".to_string())
        );
        assert_eq!(
            cert_signature_name("id-ecPublicKey", Some("ecdsa-with-SHA384"), Some("P384")),
            Some("ECDSA-P384".to_string())
        );
        assert_eq!(
            cert_signature_name("Ed25519", None, None),
            Some("Ed25519".to_string())
        );
        assert_eq!(
            cert_signature_name("ML-DSA-65", None, None),
            Some("ML-DSA-65".to_string())
        );
        assert_eq!(
            cert_signature_name("1.2.3.4.5", None, None),
            Some("1.2.3.4.5".to_string())
        );
        assert_eq!(cert_signature_from_db(None, None, None, None), None);
    }

    #[test]
    fn curve_from_key_size_maps_nist_curves() {
        assert_eq!(curve_from_key_size(256), Some("P256"));
        assert_eq!(curve_from_key_size(384), Some("P384"));
        assert_eq!(curve_from_key_size(521), Some("P521"));
        assert_eq!(curve_from_key_size(2048), None);
        assert_eq!(curve_from_key_size(512), None);
    }

    #[test]
    fn cert_key_names_are_canonical() {
        assert_eq!(
            cert_key_name(Some("RSA"), Some(2048), None),
            Some("RSA-2048".to_string())
        );
        assert_eq!(
            cert_key_name(Some("EC"), Some(256), None),
            Some("EC-256".to_string())
        );
        assert_eq!(
            cert_key_name(Some("EC"), Some(384), None),
            Some("EC-384".to_string())
        );
        assert_eq!(
            cert_key_name(Some("ECDSA"), None, Some("P256")),
            Some("EC-256".to_string())
        );
        assert_eq!(
            cert_key_name(Some("id-ecPublicKey"), None, Some("P521")),
            Some("EC-521".to_string())
        );
        assert_eq!(
            cert_key_name(Some("RSA"), None, None),
            Some("RSA".to_string())
        );
        assert_eq!(
            cert_key_name(Some("Ed25519"), None, None),
            Some("Ed25519".to_string())
        );
        assert_eq!(cert_key_name(None, None, None), None);
    }

    #[test]
    fn symmetric_names_from_suite_names() {
        assert_eq!(
            symmetric_name("TLS13_AES_256_GCM_SHA384"),
            Some("AES256-GCM".to_string())
        );
        assert_eq!(
            symmetric_name("TLS_AES_128_GCM_SHA256"),
            Some("AES128-GCM".to_string())
        );
        assert_eq!(
            symmetric_name("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"),
            Some("AES128-GCM".to_string())
        );
        assert_eq!(
            symmetric_name("TLS13_CHACHA20_POLY1305_SHA256"),
            Some("CHACHA20-POLY1305".to_string())
        );
        assert_eq!(
            symmetric_name("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"),
            Some("AES256-CBC".to_string())
        );
        assert_eq!(symmetric_name("TLS_UNKNOWN"), None);
    }

    #[test]
    fn fixture_facts_are_consistent() {
        let state = fixture();
        let aa = &state.certs["aa11"];
        assert_eq!(aa.cert_signature.as_deref(), Some("RSA-SHA256"));
        assert_eq!(aa.key_size, Some(2048));
        let bb = &state.certs["bb22"];
        assert_eq!(bb.cert_signature.as_deref(), Some("ECDSA-P256"));
    }
}