purecrypto 0.5.1

A pure-Rust cryptography toolkit with no foreign-code dependencies, from constant-time primitives up to keys, X.509 and TLS.
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
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
//! Certificate-chain verification against a [`RootCertStore`].
//!
//! Given the peer's certificate chain (end-entity first, as sent in the TLS
//! `Certificate` message), each certificate is checked to be signed by the
//! next, names are matched issuer-to-subject, the topmost certificate is
//! anchored to a trusted root, and (when a verification time is supplied) every
//! certificate is checked to be within its validity period.
//!
//! Per RFC 5280:
//!   * every non-leaf certificate must carry `basicConstraints.cA = true`
//!     (or it cannot issue subordinates),
//!   * `pathLenConstraint`, when present on a non-leaf, bounds the number
//!     of intermediates that may follow it,
//!   * the inner `signature` AlgorithmIdentifier inside `TBSCertificate`
//!     MUST equal the outer `signatureAlgorithm` (RFC 5280 §4.1.1.2 /
//!     §4.1.2.3),
//!   * any `critical` extension we don't understand MUST cause rejection
//!     (RFC 5280 §4.2),
//!   * every non-leaf MUST have `keyUsage.keyCertSign` when it carries a
//!     `keyUsage` extension (RFC 5280 §4.2.1.3),
//!   * if the leaf carries a `keyUsage` extension it must include
//!     `digitalSignature` (TLS 1.3 servers authenticate with a signature),
//!   * if the leaf carries an `extKeyUsage` extension it must include
//!     `id-kp-serverAuth`.
//!
//! [`verify_hostname`] separately matches the end-entity certificate against
//! the expected host name (subjectAltName dNSNames, falling back to the subject
//! common name).

use super::crls::CrlStore;
use super::store::RootCertStore;
use crate::signature_registry::{SignaturePolicy, find_by_oid};
use crate::tls::Error;
use crate::x509::{AnyPublicKey, Certificate, Time, Validity, oid};
use alloc::vec::Vec;

/// `keyUsage` bit-0 `digitalSignature` (RFC 5280 §4.2.1.3).
const KU_DIGITAL_SIGNATURE: u16 = 0x80; // bit 0 in BIT STRING wire order = MSB of byte 0
/// `keyUsage` bit-5 `keyCertSign`.
const KU_KEY_CERT_SIGN: u16 = 0x04;

/// Upper bound on the length of a peer-supplied certificate chain. Each cert
/// triggers a signature verification (RSA / ECDSA / PQ) plus repeated DN
/// parsing; an unbounded chain is a DoS vector during TLS handshake. The
/// value is generous — production CAs rarely exceed 4 — but caps the worst
/// case at a few milliseconds of verification work.
const MAX_CHAIN_LEN: usize = 10;

/// Verifies a certificate `chain` (end-entity first) against `store` and, on
/// success, returns the end-entity (leaf) public key — the key whose possession
/// the peer proves in its `CertificateVerify`.
///
/// When `now` is `Some`, every certificate in the chain must be within its
/// validity period at that time; pass `None` to skip the expiry check.
///
/// `policy` is consulted for every signature in the chain (including the
/// anchor signature on the topmost certificate). A chain whose certificate
/// signatures use an algorithm not on the whitelist is rejected with
/// `BadCertificate`, regardless of whether the signature would otherwise
/// verify.
///
/// Equivalent to [`verify_chain_for_purpose`] with [`ChainPurpose::Server`]
/// (the most common case). Use the explicit form for client-cert
/// verification in mTLS.
#[allow(dead_code)] // useful for tests / future internal callers
pub(crate) fn verify_chain(
    store: &RootCertStore,
    chain: &[Vec<u8>],
    now: Option<&Time>,
    policy: &SignaturePolicy,
) -> Result<AnyPublicKey, Error> {
    verify_chain_for_purpose(store, chain, now, policy, ChainPurpose::Server)
}

/// Like [`verify_chain`], but additionally consults `crls` for revocation
/// after the regular signature/anchoring checks succeed.
///
/// CRL coverage is **opt-in advisory**: a chain is rejected only when a CRL
/// from `crls` whose issuer matches and whose signature verifies under the
/// chain issuer's key contains the cert's serial. CRLs signed by an unknown
/// key, or whose issuer name does not appear in the chain, are silently
/// ignored.
pub(crate) fn verify_chain_with_crls(
    store: &RootCertStore,
    crls: &CrlStore,
    chain: &[Vec<u8>],
    now: Option<&Time>,
    policy: &SignaturePolicy,
) -> Result<AnyPublicKey, Error> {
    verify_chain_with_crls_for_purpose(store, crls, chain, now, policy, ChainPurpose::Server)
}

/// Whether the leaf is the *server* (verified by a TLS client) or the
/// *client* (verified by a TLS server in mTLS). The distinction matters for
/// the leaf's `extKeyUsage`: server certs need `id-kp-serverAuth`, client
/// certs need `id-kp-clientAuth` (RFC 5280 §4.2.1.12). Conflating the two
/// would let a server cert authenticate as a client (or vice versa).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ChainPurpose {
    /// The leaf is a TLS server certificate. Requires `id-kp-serverAuth`
    /// EKU when an EKU extension is present.
    Server,
    /// The leaf is a TLS client certificate (mTLS). Requires
    /// `id-kp-clientAuth` EKU when an EKU extension is present.
    Client,
}

#[allow(dead_code)] // useful for tests / future internal callers
pub(crate) fn verify_chain_for_purpose(
    store: &RootCertStore,
    chain: &[Vec<u8>],
    now: Option<&Time>,
    policy: &SignaturePolicy,
    purpose: ChainPurpose,
) -> Result<AnyPublicKey, Error> {
    let empty = CrlStore::new();
    verify_chain_with_crls_for_purpose(store, &empty, chain, now, policy, purpose)
}

pub(crate) fn verify_chain_with_crls_for_purpose(
    store: &RootCertStore,
    crls: &CrlStore,
    chain: &[Vec<u8>],
    now: Option<&Time>,
    policy: &SignaturePolicy,
    purpose: ChainPurpose,
) -> Result<AnyPublicKey, Error> {
    if chain.is_empty() {
        return Err(Error::BadCertificate);
    }
    // Cap the chain length to bound verification cost (DoS protection).
    if chain.len() > MAX_CHAIN_LEN {
        return Err(Error::BadCertificate);
    }

    let certs: Vec<Certificate> = chain
        .iter()
        .map(|der| Certificate::from_der(der.clone()))
        .collect::<Result<_, _>>()
        .map_err(|_| Error::BadCertificate)?;

    // RFC 5280 §4.1.1.2 / §4.1.2.3: inner `signature` AlgorithmIdentifier in
    // TBSCertificate MUST equal outer `signatureAlgorithm`.
    for cert in &certs {
        cert.check_signature_algid_consistent()
            .map_err(|_| Error::BadCertificate)?;
    }

    // RFC 5280 §4.2: any extension marked `critical` whose OID we do not
    // understand requires rejection.
    for cert in &certs {
        check_critical_extensions_recognized(cert)?;
    }

    // Each certificate must currently be within its validity period.
    if let Some(now) = now {
        for cert in &certs {
            let validity = cert.validity().map_err(|_| Error::BadCertificate)?;
            if !validity.accepts(now) {
                return Err(Error::BadCertificate);
            }
        }
    }

    // Each certificate must be signed by the next, with matching names. We
    // also consult the CrlStore for revocation: the issuer key just verified
    // is exactly what we need to validate a candidate CRL.
    for pair in certs.windows(2) {
        let (cert, issuer) = (&pair[0], &pair[1]);
        let issuer_key = issuer
            .subject_public_key()
            .map_err(|_| Error::BadCertificate)?;
        verify_cert_against_issuer(cert, &issuer_key, policy)?;
        if names_differ(cert, issuer)? {
            return Err(Error::BadCertificate);
        }
        check_revocation(cert, &issuer_key, crls, now, policy)?;
    }

    // Anchor the top of the chain to a trusted root sharing its issuer name.
    // RFC 5280 §7.1 mandates byte-exact `Name` equality, so we compare the
    // raw DER. Multiple anchors may share a name (cross-signed renewal); we
    // accept the first whose key verifies the topmost cert's signature.
    let top = certs.last().expect("chain is non-empty");
    let top_issuer = top.issuer_der().map_err(|_| Error::BadCertificate)?;
    let mut anchored = false;
    let mut anchor_key: Option<&AnyPublicKey> = None;
    for anchor in store.anchors_with_subject(top_issuer) {
        if verify_cert_against_issuer(top, &anchor.key, policy).is_ok() {
            anchored = true;
            anchor_key = Some(&anchor.key);
            break;
        }
    }
    if !anchored {
        return Err(Error::BadCertificate);
    }
    // Top cert may itself be revoked by a CRL signed by the anchor.
    if let Some(key) = anchor_key {
        check_revocation(top, key, crls, now, policy)?;
    }

    // RFC 5280 §6.1.4 — nameConstraints accumulated across every CA above
    // the leaf, applied to the leaf's SAN entries. Critical constraints
    // referencing GeneralName variants we don't evaluate have already been
    // rejected upstream by check_critical_extensions_recognized.
    enforce_name_constraints(&certs)?;

    // RFC 5280 §4.2.1.9 / §4.2.1.3 / §4.2.1.12 enforcement.
    enforce_constraints(&certs, purpose)?;

    certs[0]
        .subject_public_key()
        .map_err(|_| Error::BadCertificate)
}

/// Consults `crls` for any CRL whose issuer name matches `cert.issuer_der()`
/// and whose signature verifies against `issuer_key`. If a matching CRL
/// lists `cert.serial_bytes()`, the cert is revoked (returns
/// [`Error::BadCertificate`]).
///
/// A CRL outside its `thisUpdate..=nextUpdate` window (when `now` is given)
/// is treated as "not covering" — advisory behavior. CRLs that fail their
/// own signature verification under the issuer key are silently skipped
/// (an attacker cannot make us reject a chain by injecting a forged CRL).
fn check_revocation(
    cert: &Certificate,
    issuer_key: &AnyPublicKey,
    crls: &CrlStore,
    now: Option<&Time>,
    policy: &SignaturePolicy,
) -> Result<(), Error> {
    let cert_issuer = cert.issuer_der().map_err(|_| Error::BadCertificate)?;
    let serial = cert.serial_bytes().map_err(|_| Error::BadCertificate)?;
    let issuer_spki = issuer_key.to_spki_der();
    for crl in crls.crls_with_issuer(cert_issuer) {
        // RFC 5280 §5.1.1.2: the CRL's `signatureAlgorithm` must be one we
        // accept under `policy` — the same whitelist that gates cert-chain
        // signatures. A CRL signed with e.g. SHA-1-RSA is silently ignored
        // (treated as "not consulted") under `SignaturePolicy::modern()`.
        let Ok(crl_sig_alg) = crl.signature_algorithm_oid() else {
            continue;
        };
        let Some(crl_algo) = find_by_oid(&crl_sig_alg) else {
            continue;
        };
        if !policy.permits(crl_algo, &issuer_spki) {
            continue;
        }
        // Skip CRLs not signed by this issuer.
        if crl.verify_signature_with(issuer_key).is_err() {
            continue;
        }
        // Skip CRLs that are not currently valid (advisory: stale CRL ≈ no CRL).
        if let Some(n) = now {
            let this_update = crl.this_update().map_err(|_| Error::BadCertificate)?;
            let next_update = crl.next_update().map_err(|_| Error::BadCertificate)?;
            let covers = match next_update {
                Some(na) => Validity::new(this_update.clone(), na).accepts(n),
                // No nextUpdate ⇒ treat as not stale (RFC 5280 allows nextUpdate
                // to be omitted; clients accept indefinite freshness).
                None => true,
            };
            if !covers {
                continue;
            }
        }
        // A covering, validly-signed CRL gets the deciding vote.
        let revoked = crl.is_revoked(serial).map_err(|_| Error::BadCertificate)?;
        if revoked {
            return Err(Error::BadCertificate);
        }
    }
    Ok(())
}

/// Verifies the signature on `cert` under `issuer_key`, gating on `policy`.
///
/// Looks up the certificate's `signatureAlgorithm` OID in the registry,
/// rejects any algorithm not on the whitelist (with `BadCertificate`), and
/// only then delegates to the issuer key's verifier.
fn verify_cert_against_issuer(
    cert: &Certificate,
    issuer_key: &AnyPublicKey,
    policy: &SignaturePolicy,
) -> Result<(), Error> {
    let sig_alg = cert
        .signature_algorithm_oid()
        .map_err(|_| Error::BadCertificate)?;
    let algo = find_by_oid(&sig_alg).ok_or(Error::BadCertificate)?;
    let issuer_spki = issuer_key.to_spki_der();
    if !policy.permits(algo, &issuer_spki) {
        return Err(Error::BadCertificate);
    }
    cert.verify_signature_with(issuer_key)
        .map_err(|_| Error::BadCertificate)
}

/// Per-position chain constraints:
///   * every non-leaf must have `basicConstraints.cA = true`;
///   * every non-leaf with a `keyUsage` extension must include `keyCertSign`
///     (RFC 5280 §4.2.1.3);
///   * `pathLenConstraint` on a non-leaf bounds the number of intermediates
///     between it and the leaf;
///   * if the leaf carries `keyUsage`, `digitalSignature` (bit 0) must be set;
///   * if the leaf carries `extKeyUsage`, it must include `id-kp-serverAuth`.
fn enforce_constraints(certs: &[Certificate], purpose: ChainPurpose) -> Result<(), Error> {
    // `certs[0]` is the leaf, `certs[last]` is the topmost supplied
    // certificate (its issuer is the trust anchor in the store).
    for (i, cert) in certs.iter().enumerate().skip(1) {
        // Every non-leaf in the supplied chain signs the cert below it, so it
        // MUST be a CA per RFC 5280 §4.2.1.9.
        let bc = cert
            .basic_constraints()
            .map_err(|_| Error::BadCertificate)?
            .ok_or(Error::BadCertificate)?;
        if !bc.0 {
            return Err(Error::BadCertificate);
        }
        // If a `keyUsage` extension is present, `keyCertSign` (bit 5) MUST
        // be set for this CA to sign certificates (RFC 5280 §4.2.1.3).
        if let Some(mask) = cert.key_usage().map_err(|_| Error::BadCertificate)?
            && (mask & KU_KEY_CERT_SIGN) == 0
        {
            return Err(Error::BadCertificate);
        }
        // `pathLenConstraint = N` permits at most N intermediate certificates
        // between this CA and any leaf. For the cert at position `i` (i > 0),
        // intermediates between it and the leaf live at positions 1..=i-1,
        // i.e. `i - 1` certs. So require `path_len >= i - 1`.
        if let Some(plc) = bc.1 {
            let intermediates_below = i.saturating_sub(1);
            if (plc as usize) < intermediates_below {
                return Err(Error::BadCertificate);
            }
        }
    }

    // Leaf: keyUsage (if present) must include digitalSignature; EKU (if
    // present) must include id-kp-serverAuth.
    let leaf = &certs[0];
    if let Some(mask) = leaf.key_usage().map_err(|_| Error::BadCertificate)?
        && (mask & KU_DIGITAL_SIGNATURE) == 0
    {
        return Err(Error::BadCertificate);
    }
    let ekus = leaf
        .extended_key_usages()
        .map_err(|_| Error::BadCertificate)?;
    let required = match purpose {
        ChainPurpose::Server => oid::ID_KP_SERVER_AUTH,
        ChainPurpose::Client => oid::ID_KP_CLIENT_AUTH,
    };
    if !ekus.is_empty() && !ekus.iter().any(|o| o.as_slice() == required) {
        return Err(Error::BadCertificate);
    }
    Ok(())
}

/// RFC 5280 §6.1.4 — name-constraints propagation.
///
/// A CA's `nameConstraints` extension applies to **every** certificate that
/// appears below it in the path — each subordinate intermediate CA *and* the
/// end-entity leaf — not only the leaf. The earlier implementation collected
/// every CA's permitted/excluded subtrees and applied them solely to the
/// leaf's SAN entries, so a constrained CA could issue an out-of-constraint
/// sub-CA that then issued an in-constraint leaf and the chain wrongly
/// validated (the intermediate's own names were never checked).
///
/// This walks the presented chain from the topmost supplied CA downward: as
/// each CA's constraints come into scope, they are enforced against the names
/// of every certificate beneath it (intermediates and leaf), using the same
/// `dns_in_subtree` / `ip_in_subtree` matchers. For each such certificate its
/// dNSName / iPAddress SAN entries must satisfy, for every in-scope CA
/// constraint:
///   * the cert must NOT match any excluded subtree (any match is fatal);
///   * when a CA declares ANY permitted dNSName subtree, each of the cert's
///     DNS SANs must match at least one such entry; same for iPAddress.
///
/// Scope / limitations:
///   * The matched trust anchor lives in the [`RootCertStore`], which retains
///     only the anchor's subject name + public key — not the anchor's full
///     certificate. A `nameConstraints` extension on the anchor (root) cert
///     itself therefore cannot be brought into scope here; only constraints
///     declared by CAs that appear in the presented chain (i.e.
///     intermediates) are enforced. In practice constrained CAs are deployed
///     as intermediates, which ARE in the chain. Enforcing anchor-resident
///     constraints would require the store to retain the anchor DER —
///     flagged-for-review, out of scope for this change.
///   * directoryName (subject DN) subtree constraints are NOT evaluated: the
///     parsed [`crate::x509::NameConstraints`] surfaces only dNSName and
///     iPAddress subtrees, and any constraint referencing another
///     GeneralName variant (including directoryName) sets a
///     `has_unenforceable_*` flag that causes
///     `check_critical_extensions_recognized` to reject the chain when the
///     constraint is critical. directoryName-subtree matching is therefore
///     flagged-for-review rather than implemented (possibly-wrong) here.
///   * Constraints referencing GeneralName variants other than dNSName /
///     iPAddress are skipped — a critical such constraint has already been
///     rejected upstream.
fn enforce_name_constraints(certs: &[Certificate]) -> Result<(), Error> {
    // Pre-parse each certificate's own constraints (only CAs, indices
    // 1..=last, can declare governing constraints; index 0 is the leaf). The
    // owned values live here so the `&` borrows accumulated in `in_scope`
    // remain valid for the whole walk.
    let mut ca_constraints: Vec<Option<crate::x509::NameConstraints>> =
        Vec::with_capacity(certs.len());
    ca_constraints.push(None); // leaf
    for cert in certs.iter().skip(1) {
        ca_constraints.push(cert.name_constraints().map_err(|_| Error::BadCertificate)?);
    }

    // Walk from the topmost supplied CA (`certs[last]`) down to the leaf
    // (`certs[0]`). The CA at index `i` issues the certificate at index
    // `i - 1`, so a CA's constraints govern every certificate at a strictly
    // lower index. We accumulate constraints as they come into scope (higher
    // CAs first) and, for each subordinate certificate, enforce all in-scope
    // CAs' constraints against that certificate's own SAN names.
    let mut in_scope: Vec<&crate::x509::NameConstraints> = Vec::new();
    for idx in (0..certs.len()).rev() {
        // Constraints declared by CAs above this position must hold for the
        // certificate at `idx`. Only meaningful once at least one such
        // constraint is in scope, i.e. for certificates that have a
        // constraint-declaring CA above them.
        if !in_scope.is_empty() {
            enforce_constraints_on_cert(&certs[idx], &in_scope)?;
        }
        // This certificate's own constraints (if it is a CA that declared
        // any) now come into scope for every certificate below it.
        if let Some(nc) = &ca_constraints[idx] {
            in_scope.push(nc);
        }
    }
    Ok(())
}

/// Enforces the accumulated, in-scope name constraints (`active`) against a
/// single subordinate certificate's dNSName and iPAddress SAN entries.
///
/// Each constraint in `active` is checked independently (intersection
/// semantics across CAs): an excluded match in any CA is fatal, and a CA that
/// declares any permitted dNSName / iPAddress subtree requires every
/// corresponding SAN of `cert` to fall within one of its entries.
fn enforce_constraints_on_cert(
    cert: &Certificate,
    active: &[&crate::x509::NameConstraints],
) -> Result<(), Error> {
    let dns = cert
        .subject_alt_names()
        .map_err(|_| Error::BadCertificate)?;
    let ips = cert.subject_alt_ips().map_err(|_| Error::BadCertificate)?;

    // Close the CN-fallback bypass and refuse SAN-less certificates that are
    // governed by an active *permitted* constraint: the dNSName / iPAddress
    // checks below only iterate SAN entries, so a certificate with no SAN
    // would slip past every permitted-subtree constraint trivially (and for
    // the leaf, `verify_hostname` would then fall back to commonName). When
    // some active CA declared a permitted dNSName / iPAddress subtree, require
    // the certificate to carry a SAN so those constraints can apply. (Modern
    // PKI — CA/B Forum BR §7.1.4.2 — already requires SAN on server certs.)
    // A CA that declared ONLY excluded subtrees does not by itself force a
    // SAN to exist (RFC 5280: a name absent from the cert cannot violate an
    // exclusion). This preserves the original leaf behavior while extending
    // it to every governed subordinate certificate.
    if dns.is_empty() && ips.is_empty() {
        let any_permitted = active
            .iter()
            .any(|nc| !nc.permitted_dns.is_empty() || !nc.permitted_ip.is_empty());
        if any_permitted {
            return Err(Error::BadCertificate);
        }
        return Ok(());
    }

    for nc in active {
        // Excluded subtrees: any match in any in-scope CA is fatal.
        for name in &dns {
            for base in &nc.excluded_dns {
                if dns_in_subtree(name, base) {
                    return Err(Error::BadCertificate);
                }
            }
        }
        for ip in &ips {
            let bytes = match ip {
                crate::x509::SanIp::V4(b) => &b[..],
                crate::x509::SanIp::V6(b) => &b[..],
            };
            for (addr, mask) in &nc.excluded_ip {
                if ip_in_subtree(bytes, addr, mask) {
                    return Err(Error::BadCertificate);
                }
            }
        }
        // Permitted subtrees: when this CA declares ANY permitted dNSName
        // subtree, every DNS SAN of `cert` must match at least one of them.
        if !nc.permitted_dns.is_empty() {
            for name in &dns {
                if !nc
                    .permitted_dns
                    .iter()
                    .any(|base| dns_in_subtree(name, base))
                {
                    return Err(Error::BadCertificate);
                }
            }
        }
        if !nc.permitted_ip.is_empty() {
            for ip in &ips {
                let bytes = match ip {
                    crate::x509::SanIp::V4(b) => &b[..],
                    crate::x509::SanIp::V6(b) => &b[..],
                };
                if !nc
                    .permitted_ip
                    .iter()
                    .any(|(addr, mask)| ip_in_subtree(bytes, addr, mask))
                {
                    return Err(Error::BadCertificate);
                }
            }
        }
    }
    Ok(())
}

/// True if `name` falls within the dNSName subtree `base` per RFC 5280
/// §4.2.1.10. The constraint is a domain name in standard form:
/// * base "example.com" matches "example.com" and any host of the form
///   "*.example.com" (label-aligned suffix match).
/// * base ".example.com" (leading dot) matches any "*.example.com" but
///   NOT "example.com" itself (this leading-dot convention is widely
///   implemented for "all subdomains, not the apex").
///
/// Case-insensitive compare per RFC 4343 §2.
fn dns_in_subtree(name: &str, base: &str) -> bool {
    let name_l = name.to_ascii_lowercase();
    let base_l = base.to_ascii_lowercase();
    if let Some(suffix) = base_l.strip_prefix('.') {
        // ".example.com" → match strict subdomains only.
        if name_l.len() <= suffix.len() {
            return false;
        }
        let cut = name_l.len() - suffix.len();
        return name_l.as_bytes()[cut - 1] == b'.' && name_l[cut..] == *suffix;
    }
    // "example.com" → exact match OR label-aligned suffix.
    if name_l == base_l {
        return true;
    }
    if name_l.len() > base_l.len() {
        let cut = name_l.len() - base_l.len();
        return name_l.as_bytes()[cut - 1] == b'.' && name_l[cut..] == base_l;
    }
    false
}

/// True if `host` (the raw SAN iPAddress octet string) is within the CIDR
/// subtree `addr / mask`. Lengths must match (both v4 = 4, both v6 = 16);
/// length mismatch returns false (a v4 host cannot match a v6 constraint
/// or vice versa).
fn ip_in_subtree(host: &[u8], addr: &[u8], mask: &[u8]) -> bool {
    if host.len() != addr.len() || host.len() != mask.len() {
        return false;
    }
    for i in 0..host.len() {
        if (host[i] & mask[i]) != (addr[i] & mask[i]) {
            return false;
        }
    }
    true
}

/// RFC 5280 §4.2: reject the certificate if it carries any critical extension
/// whose OID we don't recognize. The handler set (basicConstraints, keyUsage,
/// extKeyUsage, subjectAltName, nameConstraints) is intentionally narrow —
/// every critical extension outside this set is treated as "we cannot enforce
/// this constraint", which must result in rejection.
///
/// `nameConstraints` is special: it's "recognized" only when every GeneralName
/// subtree references a variant we evaluate (dNSName / iPAddress). If a
/// critical constraint mentions any other type we route it through the same
/// fail-closed path as an unknown OID — accepting it would let a constraint
/// we can't check appear to have been honored.
fn check_critical_extensions_recognized(cert: &Certificate) -> Result<(), Error> {
    let critical = cert
        .critical_extension_oids()
        .map_err(|_| Error::BadCertificate)?;
    for o in critical {
        let bytes = o.as_slice();
        if bytes == oid::BASIC_CONSTRAINTS
            || bytes == oid::KEY_USAGE
            || bytes == oid::EXT_KEY_USAGE
            || bytes == oid::SUBJECT_ALT_NAME
        {
            continue;
        }
        if bytes == oid::NAME_CONSTRAINTS {
            // Re-parse to confirm we can evaluate every subtree. If any
            // unenforceable type slipped in, treat the critical extension
            // as unknown and reject.
            let nc = cert
                .name_constraints()
                .map_err(|_| Error::BadCertificate)?
                .ok_or(Error::BadCertificate)?;
            if nc.has_unenforceable_permitted || nc.has_unenforceable_excluded {
                return Err(Error::BadCertificate);
            }
            continue;
        }
        return Err(Error::BadCertificate);
    }
    Ok(())
}

/// Whether `cert.issuer != issuer.subject`. Compared as raw DER bytes per
/// RFC 5280 §7.1: any difference in encoding (PrintableString vs UTF8String,
/// extra attributes, multi-valued RDNs) MUST result in a non-match, which the
/// parsed-form comparison missed.
fn names_differ(cert: &Certificate, issuer: &Certificate) -> Result<bool, Error> {
    let cert_issuer = cert.issuer_der().map_err(|_| Error::BadCertificate)?;
    let issuer_subject = issuer.subject_der().map_err(|_| Error::BadCertificate)?;
    Ok(cert_issuer != issuer_subject)
}

/// Checks that the end-entity certificate identifies `host`. Prefers the
/// `subjectAltName` dNSName entries (RFC 6125); if there are none, falls back
/// to the subject common name.
pub(crate) fn verify_hostname(cert: &Certificate, host: &str) -> Result<(), Error> {
    // If the caller asked for an IP-literal host, the only spec-correct
    // SAN slot that can authorise it is iPAddress ([7]). Dispatch
    // accordingly; dNSName entries and the CN fallback are not consulted
    // for IP-literal reference identifiers (RFC 6125 §6.5.2).
    if let Some(host_bytes) = parse_host_ip(host) {
        let ips = cert.subject_alt_ips().map_err(|_| Error::BadCertificate)?;
        let matched = ips.iter().any(|san| match (san, &host_bytes) {
            (crate::x509::SanIp::V4(a), HostIp::V4(b)) => a == b,
            (crate::x509::SanIp::V6(a), HostIp::V6(b)) => a == b,
            _ => false,
        });
        return if matched {
            Ok(())
        } else {
            Err(Error::BadCertificate)
        };
    }
    let sans = cert
        .subject_alt_names()
        .map_err(|_| Error::BadCertificate)?;
    let matched = if !sans.is_empty() {
        sans.iter().any(|pattern| dns_name_matches(pattern, host))
    } else {
        cert.subject()
            .map_err(|_| Error::BadCertificate)?
            .common_name
            .as_deref()
            .map(|cn| dns_name_matches(cn, host))
            .unwrap_or(false)
    };
    if matched {
        Ok(())
    } else {
        Err(Error::BadCertificate)
    }
}

/// Parsed IP-literal host. `None` means the host is not an IP literal
/// (so dNSName matching is the right path).
enum HostIp {
    V4([u8; 4]),
    V6([u8; 16]),
}

/// Parses an IP-literal host (IPv4 dotted-quad, or any colon-bearing
/// string for IPv6). Returns `None` if the host is not an IP literal.
fn parse_host_ip(host: &str) -> Option<HostIp> {
    if !host.bytes().any(|b| b == b':') {
        // Pure dotted-quad IPv4.
        return crate::x509::cert::parse_ipv4(host).map(HostIp::V4);
    }
    parse_ipv6(host).map(HostIp::V6)
}

/// Parses an IPv6 literal in the canonical full or compressed forms
/// (RFC 4291 §2.2). Embedded-IPv4 form (`::ffff:192.0.2.1`) is
/// recognised on input — host machines accept it — and is returned as
/// its 16-byte IPv6 representation. The SAN-side matcher then refuses
/// to match it against a 16-byte iPAddress entry because
/// [`Certificate::subject_alt_ips`] never surfaces IPv4-mapped-IPv6
/// SAN entries. So a leaf claiming `::ffff:10.0.0.1` in iPAddress can
/// match neither `10.0.0.1` (the 4-byte SAN that would have been
/// correct) nor `::ffff:10.0.0.1` (rejected at parse).
fn parse_ipv6(s: &str) -> Option<[u8; 16]> {
    // Split on "::" to handle compression.
    let (head, tail) = if let Some(idx) = s.find("::") {
        let head = &s[..idx];
        let tail = &s[idx + 2..];
        if head.contains("::") || tail.contains("::") {
            return None;
        }
        (head, tail)
    } else {
        (s, "")
    };
    let mut head_groups: alloc::vec::Vec<u16> = alloc::vec::Vec::new();
    let mut tail_groups: alloc::vec::Vec<u16> = alloc::vec::Vec::new();
    for (target, src) in [(&mut head_groups, head), (&mut tail_groups, tail)] {
        if src.is_empty() {
            continue;
        }
        for group in src.split(':') {
            // Embedded-IPv4 in the last group (e.g. "::ffff:10.0.0.1") —
            // expand to two 16-bit groups.
            if group.contains('.') {
                let v4 = crate::x509::cert::parse_ipv4(group)?;
                target.push(((v4[0] as u16) << 8) | v4[1] as u16);
                target.push(((v4[2] as u16) << 8) | v4[3] as u16);
                continue;
            }
            if group.is_empty() || group.len() > 4 {
                return None;
            }
            let g = u16::from_str_radix(group, 16).ok()?;
            target.push(g);
        }
    }
    let total = head_groups.len() + tail_groups.len();
    if total > 8 {
        return None;
    }
    let zero_groups = 8 - total;
    // Compression `::` is required when total < 8 unless the original
    // string contained one explicit `::`.
    if zero_groups > 0 && !s.contains("::") {
        return None;
    }
    let mut out = [0u8; 16];
    let mut i = 0;
    for g in head_groups
        .into_iter()
        .chain(core::iter::repeat_n(0, zero_groups))
        .chain(tail_groups)
    {
        out[i] = (g >> 8) as u8;
        out[i + 1] = (g & 0xff) as u8;
        i += 2;
    }
    Some(out)
}

/// Matches a certificate dNSName `pattern` against `host`, case-insensitively,
/// allowing a single leftmost-label `*` wildcard (`*.example.com` matches
/// `a.example.com` but not `example.com` or `a.b.example.com`).
fn dns_name_matches(pattern: &str, host: &str) -> bool {
    // RFC 6125 §6.5.2: dNSName / CN-fallback matching MUST NOT be used
    // for IP-literal hosts. If either side looks IP-shaped, refuse the
    // match — IPs belong in the iPAddress SAN slot and have a separate
    // matcher.
    if looks_like_ip(pattern) || looks_like_ip(host) {
        return false;
    }
    if let Some(suffix) = pattern.strip_prefix("*.") {
        // RFC 6125 §6.4.3: wildcard is the leftmost label only, must
        // cover exactly one label, and the wildcard label MUST NOT be
        // partial (`f*.example.com` is forbidden — already prevented by
        // requiring the prefix `*.`).
        match host.split_once('.') {
            Some((label, rest)) => {
                !label.is_empty() && !rest.is_empty() && rest.eq_ignore_ascii_case(suffix)
            }
            None => false,
        }
    } else {
        !pattern.is_empty() && pattern.eq_ignore_ascii_case(host)
    }
}

/// Coarse IP-literal heuristic; defense-in-depth against bytes that
/// slipped past [`parse_dns_names`] (e.g. via CN-fallback). Matches the
/// same shape: any colon, or an IPv4 dotted-quad of 1-3-digit labels.
fn looks_like_ip(s: &str) -> bool {
    if s.bytes().any(|b| b == b':') {
        return true;
    }
    let mut count = 0usize;
    for label in s.split('.') {
        count += 1;
        if count > 4 {
            return false;
        }
        if label.is_empty() || label.len() > 3 {
            return false;
        }
        if !label.bytes().all(|b| b.is_ascii_digit()) {
            return false;
        }
    }
    count == 4
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_util::{from_hex_vec, rsa_test_key_a, rsa_test_key_b};
    use crate::x509::{Certificate, DistinguishedName, Time, Validity};

    fn validity() -> Validity {
        Validity::new(
            Time::utc(2024, 1, 1, 0, 0, 0),
            Time::utc(2034, 1, 1, 0, 0, 0),
        )
    }

    /// The shipped default policy.
    fn policy() -> SignaturePolicy {
        SignaturePolicy::modern()
    }

    #[test]
    fn rfc8448_self_signed_anchor() {
        // The RFC 8448 server certificate is self-signed ("rsa" -> "rsa"); its
        // key is RSA-1024, so a default-policy verify would refuse it on the
        // min_rsa_bits check. Lower the floor for this single legacy fixture.
        let flight = from_hex_vec(include_str!(
            "../../../testdata/rfc8448_server_flight_payload.hex"
        ));
        let cert_der = flight[51..483].to_vec();

        let mut store = RootCertStore::new();
        store.add_der(cert_der.clone()).unwrap();

        let relaxed = SignaturePolicy::modern().with_min_rsa_bits(1024);
        let leaf_key = verify_chain(&store, &[cert_der], None, &relaxed).unwrap();
        assert!(matches!(leaf_key, AnyPublicKey::Rsa(_)));
    }

    #[test]
    fn two_cert_chain_to_root() {
        let ca_key = rsa_test_key_a();
        let leaf_key = rsa_test_key_b();
        let ca_name = DistinguishedName::common_name("purecrypto Root");
        let leaf_name = DistinguishedName::common_name("leaf.example");

        let root = Certificate::self_signed(&ca_key, &ca_name, &validity(), 1, true).unwrap();
        let leaf = Certificate::issue(
            &ca_key,
            &ca_name,
            &leaf_name,
            &leaf_key.public_key(),
            &validity(),
            2,
            false,
        )
        .unwrap();

        let mut store = RootCertStore::new();
        store.add_der(root.to_der().to_vec()).unwrap();

        // Within the validity window (exercises the expiry check positively).
        let now = Time::utc(2026, 1, 1, 0, 0, 0);
        let policy = policy();
        // Chain with the leaf alone (root supplied by the store).
        verify_chain(&store, &[leaf.to_der().to_vec()], Some(&now), &policy).unwrap();
        // Chain that also carries the root certificate.
        verify_chain(
            &store,
            &[leaf.to_der().to_vec(), root.to_der().to_vec()],
            Some(&now),
            &policy,
        )
        .unwrap();
    }

    #[test]
    fn rejects_untrusted_and_empty() {
        let ca_key = rsa_test_key_a();
        let ca_name = DistinguishedName::common_name("Untrusted Root");
        let root = Certificate::self_signed(&ca_key, &ca_name, &validity(), 1, true).unwrap();

        // Empty store -> no anchor.
        let empty = RootCertStore::new();
        let policy = policy();
        assert!(matches!(
            verify_chain(&empty, &[root.to_der().to_vec()], None, &policy),
            Err(Error::BadCertificate)
        ));

        // Empty chain.
        assert!(matches!(
            verify_chain(&empty, &[], None, &policy),
            Err(Error::BadCertificate)
        ));
    }

    #[test]
    fn rejects_broken_signature() {
        let ca_key = rsa_test_key_a();
        let leaf_key = rsa_test_key_b();
        let ca_name = DistinguishedName::common_name("purecrypto Root");
        let leaf_name = DistinguishedName::common_name("leaf.example");

        let root = Certificate::self_signed(&ca_key, &ca_name, &validity(), 1, true).unwrap();
        // Leaf "signed" by the leaf's own key, not the CA -> chain to root fails.
        let bogus = Certificate::issue(
            &leaf_key,
            &ca_name,
            &leaf_name,
            &leaf_key.public_key(),
            &validity(),
            3,
            false,
        )
        .unwrap();

        let mut store = RootCertStore::new();
        store.add_der(root.to_der().to_vec()).unwrap();
        assert!(matches!(
            verify_chain(&store, &[bogus.to_der().to_vec()], None, &policy()),
            Err(Error::BadCertificate)
        ));
    }

    /// An "intermediate" that lacks `basicConstraints.cA = true` cannot sign
    /// the leaf — chain validation rejects.
    #[test]
    fn rejects_non_ca_as_intermediate() {
        let ca_key = rsa_test_key_a();
        let leaf_key = rsa_test_key_b();
        let ca_name = DistinguishedName::common_name("purecrypto Root");
        let leaf_name = DistinguishedName::common_name("leaf.example");

        let root = Certificate::self_signed(&ca_key, &ca_name, &validity(), 1, true).unwrap();
        // The "intermediate" is signed by the root but is itself marked as
        // a non-CA (is_ca = false). It still issues a leaf — a forged path.
        let bad_int = Certificate::issue(
            &ca_key,
            &ca_name,
            &DistinguishedName::common_name("fake-intermediate"),
            &leaf_key.public_key(),
            &validity(),
            2,
            false,
        )
        .unwrap();
        let leaf = Certificate::issue(
            &leaf_key,
            &DistinguishedName::common_name("fake-intermediate"),
            &leaf_name,
            &leaf_key.public_key(),
            &validity(),
            3,
            false,
        )
        .unwrap();

        let mut store = RootCertStore::new();
        store.add_der(root.to_der().to_vec()).unwrap();
        let chain = alloc::vec![leaf.to_der().to_vec(), bad_int.to_der().to_vec()];
        assert!(matches!(
            verify_chain(&store, &chain, None, &policy()),
            Err(Error::BadCertificate)
        ));
    }

    #[test]
    fn rejects_expired_certificate() {
        let ca_key = rsa_test_key_a();
        let name = DistinguishedName::common_name("expired.example");
        let past = Validity::new(
            Time::utc(2020, 1, 1, 0, 0, 0),
            Time::utc(2021, 1, 1, 0, 0, 0),
        );
        let cert = Certificate::self_signed(&ca_key, &name, &past, 1, true).unwrap();

        let mut store = RootCertStore::new();
        store.add_der(cert.to_der().to_vec()).unwrap();

        let now = Time::utc(2026, 1, 1, 0, 0, 0);
        let policy = policy();
        // Expired at `now`.
        assert!(matches!(
            verify_chain(&store, &[cert.to_der().to_vec()], Some(&now), &policy),
            Err(Error::BadCertificate)
        ));
        // Accepted when no clock is supplied (expiry skipped).
        verify_chain(&store, &[cert.to_der().to_vec()], None, &policy).unwrap();
    }

    #[test]
    fn hostname_san_and_cn() {
        let key = rsa_test_key_a();
        // SAN cert: matches SAN entries (incl. wildcard), ignores CN.
        let san_cert = Certificate::self_signed_with_sans(
            &key,
            &DistinguishedName::common_name("ignored"),
            &validity(),
            1,
            false,
            &["example.com", "*.svc.example.com"],
        )
        .unwrap();
        verify_hostname(&san_cert, "example.com").unwrap();
        verify_hostname(&san_cert, "api.svc.example.com").unwrap();
        assert!(verify_hostname(&san_cert, "ignored").is_err()); // CN not consulted
        assert!(verify_hostname(&san_cert, "other.com").is_err());
        assert!(verify_hostname(&san_cert, "svc.example.com").is_err()); // wildcard needs a label
        assert!(verify_hostname(&san_cert, "a.b.svc.example.com").is_err()); // one label only

        // No SAN: falls back to the subject common name.
        let cn_cert = Certificate::self_signed(
            &key,
            &DistinguishedName::common_name("host.example"),
            &validity(),
            2,
            false,
        )
        .unwrap();
        verify_hostname(&cn_cert, "HOST.example").unwrap(); // case-insensitive
        assert!(verify_hostname(&cn_cert, "wrong.example").is_err());
    }

    /// Issuing and validating a self-signed ML-DSA-65 certificate through
    /// the full `verify_chain` path. ML-DSA is on the default whitelist as
    /// of commit 3, so no policy tuning is needed.
    #[test]
    fn mldsa_self_signed_chain() {
        use crate::hash::Sha256;
        use crate::mldsa::MlDsa65PrivateKey;
        use crate::rng::HmacDrbg;
        use crate::x509::CertSigner;
        let mut rng = HmacDrbg::<Sha256>::new(b"verify-mldsa65", b"n", &[]);
        let (sk, _pk) = MlDsa65PrivateKey::generate(&mut rng);
        let signer = CertSigner::MlDsa65(&sk);
        let name = DistinguishedName::common_name("pqc.example");
        let cert =
            Certificate::self_signed_general(&signer, &name, &validity(), 1, true, &[]).unwrap();

        let mut store = RootCertStore::new();
        store.add_der(cert.to_der().to_vec()).unwrap();
        let leaf_key = verify_chain(&store, &[cert.to_der().to_vec()], None, &policy()).unwrap();
        assert!(matches!(leaf_key, AnyPublicKey::MlDsa65(_)));
    }

    /// A chain whose leaf is signed with secp256k1 verifies only when the
    /// policy explicitly permits the algorithm; the default `modern()`
    /// policy refuses (secp256k1 is in the registry but not on the
    /// whitelist).
    #[test]
    fn secp256k1_chain_under_extended_policy() {
        use crate::ec::{BoxedEcdsaPrivateKey, CurveId};
        use crate::hash::Sha256;
        use crate::rng::HmacDrbg;
        use crate::x509::CertSigner;
        let mut rng = HmacDrbg::<Sha256>::new(b"verify-k1", b"n", &[]);
        let sk = BoxedEcdsaPrivateKey::generate(CurveId::Secp256k1, &mut rng);
        let signer = CertSigner::Ecdsa(&sk);
        let name = DistinguishedName::common_name("k1.example");
        let cert =
            Certificate::self_signed_general(&signer, &name, &validity(), 1, true, &[]).unwrap();

        let mut store = RootCertStore::new();
        store.add_der(cert.to_der().to_vec()).unwrap();

        // Cert's signatureAlgorithm is `ecdsa-with-SHA256`. The default policy
        // permits the `ecdsa-with-sha256` OID-keyed entry — which accepts any
        // supported curve — so the chain validates without opt-in. (secp256k1
        // is in the registry; the policy gates the OID-keyed entry, not the
        // strict secp256k1 entry.)
        verify_chain(&store, &[cert.to_der().to_vec()], None, &policy()).unwrap();

        // To assert the strict-pair entry is opt-in only, build a policy that
        // permits only Ed25519 — secp256k1 + ECDSA-SHA256 must be refused.
        let restrictive = SignaturePolicy::empty().permit("ed25519");
        assert!(matches!(
            verify_chain(&store, &[cert.to_der().to_vec()], None, &restrictive),
            Err(Error::BadCertificate)
        ));
    }

    /// A self-signed SLH-DSA-SHA2-128f cert validates only under a policy
    /// that explicitly permits SLH-DSA (the default `modern()` does not).
    #[test]
    fn slhdsa_chain_under_extended_policy() {
        use crate::hash::Sha256;
        use crate::rng::HmacDrbg;
        use crate::slhdsa::{ParamSet, PrivateKey};
        use crate::x509::CertSigner;
        let mut rng = HmacDrbg::<Sha256>::new(b"verify-slhdsa", b"n", &[]);
        let (sk, _pk) = PrivateKey::generate(ParamSet::Sha2_128f, &mut rng);
        let signer = CertSigner::SlhDsa(&sk);
        let name = DistinguishedName::common_name("slhdsa.example");
        let cert =
            Certificate::self_signed_general(&signer, &name, &validity(), 1, true, &[]).unwrap();

        let mut store = RootCertStore::new();
        store.add_der(cert.to_der().to_vec()).unwrap();

        // Default policy refuses.
        assert!(matches!(
            verify_chain(&store, &[cert.to_der().to_vec()], None, &policy()),
            Err(Error::BadCertificate)
        ));
        // Extended policy accepts.
        let extended = SignaturePolicy::modern().permit("slh-dsa-sha2-128f");
        verify_chain(&store, &[cert.to_der().to_vec()], None, &extended).unwrap();
    }

    /// A SHA-1-RSA legacy chain verifies only when the policy explicitly
    /// opts in via `permit("rsa-pkcs1-sha1")`. The default `modern()`
    /// policy refuses (SHA-1 is in the registry, not on the whitelist).
    #[test]
    fn legacy_sha1_chain_only_under_opt_in() {
        use crate::der::{encode_bit_string, encode_sequence};
        use crate::hash::Sha1;
        use crate::rsa::Pkcs1Digest;
        use crate::test_util::rsa_test_key_a;
        use crate::x509::cert::build_tbs_raw;
        use crate::x509::{AnyPublicKey, Certificate, algorithm_identifier};

        // Build a fully-consistent SHA-1-RSA self-signed cert: inner and
        // outer signature AlgorithmIdentifiers are BOTH `sha1WithRSAEncryption`
        // (RFC 5280 §4.1.1.2 requires equality, and chain validation enforces
        // it). The earlier version of this test crafted a mismatch on purpose
        // and is now rejected at the algid-consistency check before ever
        // reaching the policy whitelist — that's the desired behavior.
        assert_eq!(Sha1::DIGEST_INFO_PREFIX.len(), 15);
        let key = rsa_test_key_a();
        let subj = DistinguishedName::common_name("legacy.example");
        // Wrap the const-generic public key into a BoxedRsaPublicKey so we
        // can use the AnyPublicKey SPKI encoder.
        let mut n_bytes = alloc::vec![0u8; 256];
        key.public_key().modulus().write_be_bytes(&mut n_bytes);
        let mut e_bytes = alloc::vec![0u8; 256];
        key.public_key().exponent().write_be_bytes(&mut e_bytes);
        let boxed_pub = crate::rsa::BoxedRsaPublicKey::new(
            crate::bignum::BoxedUint::from_be_bytes(&n_bytes),
            crate::bignum::BoxedUint::from_be_bytes(&e_bytes),
        );
        let spki = AnyPublicKey::Rsa(boxed_pub).to_spki_der();
        let algid = algorithm_identifier(oid::SHA1_WITH_RSA, true);
        let exts = crate::x509::cert::legacy_extensions(true, &[]);
        let tbs = build_tbs_raw(1, &subj, &subj, &validity(), &spki, &algid, &exts);
        let sig = key.sign_pkcs1v15::<Sha1>(&tbs).unwrap();
        let der = encode_sequence(&[tbs.clone(), algid.clone(), encode_bit_string(&sig)].concat());
        let legacy = Certificate::from_der(der).unwrap();

        let mut store = RootCertStore::new();
        store.add_der(legacy.to_der().to_vec()).unwrap();

        // Default policy refuses.
        assert!(matches!(
            verify_chain(&store, &[legacy.to_der().to_vec()], None, &policy()),
            Err(Error::BadCertificate)
        ));
        // Opt-in permits.
        let with_sha1 = SignaturePolicy::modern().permit("rsa-pkcs1-sha1");
        verify_chain(&store, &[legacy.to_der().to_vec()], None, &with_sha1).unwrap();
    }

    /// A certificate whose inner `signature` AlgorithmIdentifier differs from
    /// its outer `signatureAlgorithm` is rejected at the consistency check,
    /// even when the signature itself would verify (RFC 5280 §4.1.1.2 /
    /// §4.1.2.3).
    #[test]
    fn rejects_inner_outer_algid_mismatch() {
        use crate::der::{encode_bit_string, encode_sequence};
        use crate::hash::Sha1;
        use crate::rsa::Pkcs1Digest;
        use crate::test_util::rsa_test_key_a;
        use crate::x509::cert::build_tbs_raw;
        use crate::x509::{AnyPublicKey, Certificate, algorithm_identifier};
        assert_eq!(Sha1::DIGEST_INFO_PREFIX.len(), 15);
        let key = rsa_test_key_a();
        let subj = DistinguishedName::common_name("mismatch.example");
        // Wrap the const-generic public key into a BoxedRsaPublicKey so we
        // can use the AnyPublicKey SPKI encoder.
        let mut n_bytes = alloc::vec![0u8; 256];
        key.public_key().modulus().write_be_bytes(&mut n_bytes);
        let mut e_bytes = alloc::vec![0u8; 256];
        key.public_key().exponent().write_be_bytes(&mut e_bytes);
        let boxed_pub = crate::rsa::BoxedRsaPublicKey::new(
            crate::bignum::BoxedUint::from_be_bytes(&n_bytes),
            crate::bignum::BoxedUint::from_be_bytes(&e_bytes),
        );
        let spki = AnyPublicKey::Rsa(boxed_pub).to_spki_der();
        // Inner = SHA-256, outer = SHA-1 — historically common in attempted
        // algorithm-substitution attacks.
        let inner = algorithm_identifier(oid::SHA256_WITH_RSA, true);
        let outer = algorithm_identifier(oid::SHA1_WITH_RSA, true);
        let exts = crate::x509::cert::legacy_extensions(true, &[]);
        let tbs = build_tbs_raw(1, &subj, &subj, &validity(), &spki, &inner, &exts);
        let sig = key.sign_pkcs1v15::<Sha1>(&tbs).unwrap();
        let der = encode_sequence(&[tbs, outer, encode_bit_string(&sig)].concat());
        let mismatched = Certificate::from_der(der).unwrap();

        let mut store = RootCertStore::new();
        store.add_der(mismatched.to_der().to_vec()).unwrap();

        let with_sha1 = SignaturePolicy::modern().permit("rsa-pkcs1-sha1");
        assert!(matches!(
            verify_chain(&store, &[mismatched.to_der().to_vec()], None, &with_sha1),
            Err(Error::BadCertificate)
        ));
    }

    /// A CRL signed by the CA that revokes the leaf serial → chain
    /// validation refuses the leaf; a sibling leaf with a different serial
    /// validates normally.
    #[test]
    fn crl_revokes_leaf_serial() {
        use crate::tls::pki::CrlStore;
        use crate::x509::{CertSigner, CrlBuilder};
        let ca_key = rsa_test_key_a();
        let leaf_key = rsa_test_key_b();
        let ca_name = DistinguishedName::common_name("CRL Test CA");

        let root = Certificate::self_signed(&ca_key, &ca_name, &validity(), 1, true).unwrap();
        let leaf_revoked = Certificate::issue(
            &ca_key,
            &ca_name,
            &DistinguishedName::common_name("revoked.example"),
            &leaf_key.public_key(),
            &validity(),
            42,
            false,
        )
        .unwrap();
        let leaf_ok = Certificate::issue(
            &ca_key,
            &ca_name,
            &DistinguishedName::common_name("ok.example"),
            &leaf_key.public_key(),
            &validity(),
            43,
            false,
        )
        .unwrap();

        let mut store = RootCertStore::new();
        store.add_der(root.to_der().to_vec()).unwrap();

        // Build a CRL that revokes serial 42.
        let signer = CertSigner::Rsa(
            &crate::rsa::BoxedRsaPrivateKey::from_pkcs1_pem(include_str!(
                "../../../testdata/rsa2048_test_a.pem"
            ))
            .unwrap(),
        );
        let mut b = CrlBuilder::new(&ca_name, Time::utc(2026, 1, 1, 0, 0, 0), None);
        b.revoke(&[42], Time::utc(2026, 1, 2, 0, 0, 0), None);
        let crl = b.sign(&signer).unwrap();
        let mut crls = CrlStore::new();
        crls.add_der(crl.to_der().to_vec()).unwrap();

        // The OK leaf still validates.
        verify_chain_with_crls(&store, &crls, &[leaf_ok.to_der().to_vec()], None, &policy())
            .unwrap();
        // The revoked leaf is rejected.
        assert!(matches!(
            verify_chain_with_crls(
                &store,
                &crls,
                &[leaf_revoked.to_der().to_vec()],
                None,
                &policy(),
            ),
            Err(Error::BadCertificate)
        ));
        // With an empty CRL store the revoked leaf would have passed (sanity
        // check that we're testing the CRL path, not a different bug).
        verify_chain_with_crls(
            &store,
            &CrlStore::new(),
            &[leaf_revoked.to_der().to_vec()],
            None,
            &policy(),
        )
        .unwrap();
    }

    /// A CRL outside its `thisUpdate..=nextUpdate` window is advisory:
    /// the chain validates even though the leaf serial would otherwise
    /// be revoked.
    #[test]
    fn expired_crl_is_advisory() {
        use crate::tls::pki::CrlStore;
        use crate::x509::{CertSigner, CrlBuilder};
        let ca_key = rsa_test_key_a();
        let leaf_key = rsa_test_key_b();
        let ca_name = DistinguishedName::common_name("CRL Test CA");

        let root = Certificate::self_signed(&ca_key, &ca_name, &validity(), 1, true).unwrap();
        let leaf = Certificate::issue(
            &ca_key,
            &ca_name,
            &DistinguishedName::common_name("leaf.example"),
            &leaf_key.public_key(),
            &validity(),
            7,
            false,
        )
        .unwrap();

        let mut store = RootCertStore::new();
        store.add_der(root.to_der().to_vec()).unwrap();

        let signer = CertSigner::Rsa(
            &crate::rsa::BoxedRsaPrivateKey::from_pkcs1_pem(include_str!(
                "../../../testdata/rsa2048_test_a.pem"
            ))
            .unwrap(),
        );
        // CRL window: 2024-01-01 .. 2024-12-31. We verify at `now =
        // 2026-01-01`, which is past nextUpdate ⇒ the CRL is treated as
        // not covering this point in time.
        let mut b = CrlBuilder::new(
            &ca_name,
            Time::utc(2024, 1, 1, 0, 0, 0),
            Some(Time::utc(2024, 12, 31, 0, 0, 0)),
        );
        b.revoke(&[7], Time::utc(2024, 6, 1, 0, 0, 0), None);
        let crl = b.sign(&signer).unwrap();
        let mut crls = CrlStore::new();
        crls.add_der(crl.to_der().to_vec()).unwrap();

        let now = Time::utc(2026, 1, 1, 0, 0, 0);
        // Advisory: the expired CRL does not block the chain.
        verify_chain_with_crls(
            &store,
            &crls,
            &[leaf.to_der().to_vec()],
            Some(&now),
            &policy(),
        )
        .unwrap();
    }

    /// A CRL whose signature does not match the issuer key (e.g. signed by
    /// a different key) is silently ignored by chain validation.
    #[test]
    fn crl_signed_by_wrong_key_is_ignored() {
        use crate::tls::pki::CrlStore;
        use crate::x509::{CertSigner, CrlBuilder};
        let ca_key = rsa_test_key_a();
        let other_key = rsa_test_key_b();
        let ca_name = DistinguishedName::common_name("CRL Test CA");

        let root = Certificate::self_signed(&ca_key, &ca_name, &validity(), 1, true).unwrap();
        let leaf = Certificate::issue(
            &ca_key,
            &ca_name,
            &DistinguishedName::common_name("leaf.example"),
            &other_key.public_key(),
            &validity(),
            55,
            false,
        )
        .unwrap();

        let mut store = RootCertStore::new();
        store.add_der(root.to_der().to_vec()).unwrap();

        // CRL signed by the OTHER key, not the CA. is_revoked would say
        // true, but the signature won't verify under the CA, so the CRL is
        // ignored.
        let bogus_signer = CertSigner::Rsa(
            &crate::rsa::BoxedRsaPrivateKey::from_pkcs1_pem(include_str!(
                "../../../testdata/rsa2048_test_b.pem"
            ))
            .unwrap(),
        );
        let mut b = CrlBuilder::new(&ca_name, Time::utc(2026, 1, 1, 0, 0, 0), None);
        b.revoke(&[55], Time::utc(2026, 1, 2, 0, 0, 0), None);
        let crl = b.sign(&bogus_signer).unwrap();
        let mut crls = CrlStore::new();
        crls.add_der(crl.to_der().to_vec()).unwrap();

        verify_chain_with_crls(&store, &crls, &[leaf.to_der().to_vec()], None, &policy()).unwrap();
    }

    /// A chain whose signature algorithm is in the registry but not on the
    /// whitelist is rejected (with `BadCertificate`), even when the signature
    /// itself would verify.
    #[test]
    fn rejects_unpermitted_algorithm() {
        let key = rsa_test_key_a();
        let cert = Certificate::self_signed(
            &key,
            &DistinguishedName::common_name("rsa.example"),
            &validity(),
            1,
            true,
        )
        .unwrap();

        let mut store = RootCertStore::new();
        store.add_der(cert.to_der().to_vec()).unwrap();

        // The cert is `sha256WithRSAEncryption`. A policy that permits only
        // ed25519 must reject it; the default policy must accept it.
        let ed_only = SignaturePolicy::empty().permit("ed25519");
        assert!(matches!(
            verify_chain(&store, &[cert.to_der().to_vec()], None, &ed_only),
            Err(Error::BadCertificate)
        ));
        verify_chain(&store, &[cert.to_der().to_vec()], None, &policy()).unwrap();
    }

    /// H-4 — RFC 5280 §5.1.1.2: weak CRL signature algorithms must be
    /// gated by the same `SignaturePolicy` that gates the certificate
    /// path. A CRL signed with SHA-1-RSA under `SignaturePolicy::modern()`
    /// must be silently dropped — the chain still validates the cert as
    /// not revoked. Under an explicit `permit("rsa-pkcs1-sha1")` opt-in,
    /// the same CRL is consulted and revokes the leaf.
    #[test]
    fn crl_signed_with_sha1_rejected_under_modern_policy() {
        use crate::der::{encode_bit_string, encode_sequence};
        use crate::hash::Sha1;
        use crate::tls::pki::CrlStore;
        use crate::x509::{CertificateRevocationList, algorithm_identifier};

        let ca_key = rsa_test_key_a();
        let leaf_key = rsa_test_key_b();
        let ca_name = DistinguishedName::common_name("CRL SHA-1 Test CA");

        let root = Certificate::self_signed(&ca_key, &ca_name, &validity(), 1, true).unwrap();
        let leaf = Certificate::issue(
            &ca_key,
            &ca_name,
            &DistinguishedName::common_name("sha1crl.example"),
            &leaf_key.public_key(),
            &validity(),
            99,
            false,
        )
        .unwrap();

        let mut store = RootCertStore::new();
        store.add_der(root.to_der().to_vec()).unwrap();

        // Hand-build a SHA-1-RSA-signed CRL that revokes serial 99. The
        // inner and outer AlgorithmIdentifiers both carry
        // sha1WithRSAEncryption; the signature is computed under SHA-1
        // so it would verify under the issuer key — except `policy()`
        // refuses SHA-1, so the CRL is silently dropped.
        let algid_sha1 = algorithm_identifier(oid::SHA1_WITH_RSA, true);
        // Revoked-certificates SEQUENCE: one entry { serial=99, revoked_at }.
        let serial = crate::der::encode_integer(&[99]);
        let revoked_at = Time::utc(2026, 1, 2, 0, 0, 0).to_der_choice();
        let entry = encode_sequence(&[serial, revoked_at].concat());
        // Build the TBS body manually so we can splice in a revoked entry
        // (the in-tree `CrlBuilder` always uses the signer's chosen algid,
        // which for `BoxedRsaPrivateKey` is SHA-256-RSA — we need SHA-1
        // here).
        let mut body = alloc::vec::Vec::new();
        body.extend_from_slice(&crate::der::encode_integer(&[1])); // version v2
        body.extend_from_slice(&algid_sha1);
        body.extend_from_slice(&ca_name.to_der());
        body.extend_from_slice(&Time::utc(2026, 1, 1, 0, 0, 0).to_der_choice());
        body.extend_from_slice(&encode_sequence(&entry));
        let tbs = encode_sequence(&body);
        let sig = ca_key.sign_pkcs1v15::<Sha1>(&tbs).unwrap();
        let crl_der = encode_sequence(&[tbs, algid_sha1, encode_bit_string(&sig)].concat());
        let crl = CertificateRevocationList::from_der(crl_der).unwrap();

        let mut crls = CrlStore::new();
        crls.add_der(crl.to_der().to_vec()).unwrap();

        // Under modern policy: CRL is ignored, leaf validates as not revoked.
        verify_chain_with_crls(&store, &crls, &[leaf.to_der().to_vec()], None, &policy()).unwrap();

        // Sanity: under an explicit SHA-1 opt-in, the same CRL revokes the leaf.
        let with_sha1 = SignaturePolicy::modern().permit("rsa-pkcs1-sha1");
        assert!(matches!(
            verify_chain_with_crls(&store, &crls, &[leaf.to_der().to_vec()], None, &with_sha1,),
            Err(Error::BadCertificate)
        ));
    }

    /// dns_name_matches must refuse IP-literal patterns and IP-literal
    /// hosts (RFC 6125 §6.5.2 — IPs belong in iPAddress SAN, not dNSName /
    /// CN). The unit test asserts the refusal at both the pattern and
    /// host slots, including the IPv4-mapped-IPv6 form.
    #[test]
    fn dns_matcher_refuses_ip_pattern_or_host() {
        // Pattern is IPv4 → no match, even when host equals pattern byte-for-byte.
        assert!(!super::dns_name_matches("10.0.0.1", "10.0.0.1"));
        // Host is IPv4 → no match against any pattern.
        assert!(!super::dns_name_matches("example.com", "10.0.0.1"));
        assert!(!super::dns_name_matches("*.example.com", "10.0.0.1"));
        // IPv6 either side → no match.
        assert!(!super::dns_name_matches("::1", "::1"));
        assert!(!super::dns_name_matches("2001:db8::1", "2001:db8::1"));
        assert!(!super::dns_name_matches(
            "::ffff:10.0.0.1",
            "::ffff:10.0.0.1"
        ));
        // Sanity: normal hostnames still match.
        assert!(super::dns_name_matches("example.com", "example.com"));
        assert!(super::dns_name_matches("*.example.com", "host.example.com"));
        // Wildcard refuses a deeper host.
        assert!(!super::dns_name_matches("*.example.com", "a.b.example.com"));
        // Wildcard refuses the bare apex.
        assert!(!super::dns_name_matches("*.example.com", "example.com"));
        // Partial wildcard (`f*.example.com`) is not stripped → literal
        // compare → no match against `foo.example.com`.
        assert!(!super::dns_name_matches(
            "f*.example.com",
            "foo.example.com"
        ));
    }

    // ----------------------------------------------------------------------
    // Name-constraints unit tests (RFC 5280 §4.2.1.10 / §6.1.4).
    // ----------------------------------------------------------------------

    #[test]
    fn dns_in_subtree_label_alignment() {
        // base "example.com" matches exactly + any label-aligned subdomain.
        assert!(super::dns_in_subtree("example.com", "example.com"));
        assert!(super::dns_in_subtree("foo.example.com", "example.com"));
        assert!(super::dns_in_subtree("a.b.example.com", "example.com"));
        // ...but NOT a name with the same suffix at a different label boundary.
        assert!(!super::dns_in_subtree("notexample.com", "example.com"));
        // base ".example.com" matches strict subdomains only.
        assert!(super::dns_in_subtree("foo.example.com", ".example.com"));
        assert!(!super::dns_in_subtree("example.com", ".example.com"));
        // Case-insensitive.
        assert!(super::dns_in_subtree("FOO.Example.Com", "example.com"));
    }

    #[test]
    fn ip_in_subtree_cidr() {
        // 10.0.0.0/8 matches 10.x.y.z, not 11.x.y.z.
        let addr = [10u8, 0, 0, 0];
        let mask = [0xffu8, 0, 0, 0];
        assert!(super::ip_in_subtree(&[10, 1, 2, 3], &addr, &mask));
        assert!(super::ip_in_subtree(&[10, 0, 0, 0], &addr, &mask));
        assert!(!super::ip_in_subtree(&[11, 0, 0, 1], &addr, &mask));
        // v4 host against a v6 constraint never matches.
        assert!(!super::ip_in_subtree(&[10, 0, 0, 1], &[0; 16], &[0; 16]));
    }

    /// Builds a 2-CA chain (root → intermediate → leaf) with the intermediate
    /// carrying the supplied `nameConstraints` extension. The leaf is a
    /// server cert with `Certificate::issue_with_extensions` so SANs are
    /// caller-controlled.
    fn build_chain_with_nc(
        nc_ext: crate::x509::Extension,
        leaf_sans: &[crate::x509::GeneralName],
    ) -> (Certificate, Certificate, Certificate) {
        use crate::ec::{BoxedEcdsaPrivateKey, CurveId};
        use crate::rng::HmacDrbg;
        use crate::x509::{
            CertSigner, DistinguishedName, Extension, GeneralName, KeyUsageBits,
            extension::{basic_constraints, extended_key_usage, key_usage, subject_alt_name},
        };

        let _ = GeneralName::Dns; // silence unused-import warning if no DNS SAN
        let mut rng = HmacDrbg::<crate::hash::Sha256>::new(b"nc-chain", b"n", &[]);
        let root_key = BoxedEcdsaPrivateKey::generate(CurveId::P256, &mut rng);
        let int_key = BoxedEcdsaPrivateKey::generate(CurveId::P256, &mut rng);
        let leaf_key = BoxedEcdsaPrivateKey::generate(CurveId::P256, &mut rng);
        let root_signer = CertSigner::Ecdsa(&root_key);
        let int_signer = CertSigner::Ecdsa(&int_key);

        let root_name = DistinguishedName::common_name("nc-root");
        let int_name = DistinguishedName::common_name("nc-intermediate");
        let leaf_name = DistinguishedName::common_name("nc-leaf");

        let root_exts = [
            basic_constraints(true, None),
            key_usage(KeyUsageBits::KEY_CERT_SIGN | KeyUsageBits::CRL_SIGN),
        ];
        let root = Certificate::self_signed_with_extensions(
            &root_signer,
            &root_name,
            &validity(),
            1,
            &root_exts,
        )
        .unwrap();

        let int_exts: alloc::vec::Vec<Extension> = alloc::vec![
            basic_constraints(true, Some(0)),
            key_usage(KeyUsageBits::KEY_CERT_SIGN | KeyUsageBits::CRL_SIGN),
            nc_ext,
        ];
        let int_pub = crate::x509::AnyPublicKey::Ecdsa(int_key.public_key());
        let int = Certificate::issue_with_extensions(
            &root_signer,
            &root_name,
            &int_name,
            &int_pub,
            &validity(),
            2,
            &int_exts,
        )
        .unwrap();

        let leaf_exts = [
            basic_constraints(false, None),
            key_usage(KeyUsageBits::DIGITAL_SIGNATURE),
            extended_key_usage(&[oid::ID_KP_SERVER_AUTH]),
            subject_alt_name(leaf_sans),
        ];
        let leaf_pub = crate::x509::AnyPublicKey::Ecdsa(leaf_key.public_key());
        let leaf = Certificate::issue_with_extensions(
            &int_signer,
            &int_name,
            &leaf_name,
            &leaf_pub,
            &validity(),
            3,
            &leaf_exts,
        )
        .unwrap();
        (root, int, leaf)
    }

    #[test]
    fn name_constraints_permitted_dns_accepts_matching() {
        use crate::x509::GeneralName;
        let nc = crate::x509::extension::name_constraints(
            &[GeneralName::Dns(".good.example".into())],
            &[],
        );
        let leaf_sans = [GeneralName::Dns("host.good.example".into())];
        let (root, int, leaf) = build_chain_with_nc(nc, &leaf_sans);

        let mut store = RootCertStore::new();
        store.add_der(root.to_der().to_vec()).unwrap();
        let now = Time::utc(2026, 1, 1, 0, 0, 0);
        verify_chain(
            &store,
            &[leaf.to_der().to_vec(), int.to_der().to_vec()],
            Some(&now),
            &policy(),
        )
        .unwrap();
    }

    #[test]
    fn name_constraints_permitted_dns_rejects_outside_subtree() {
        use crate::x509::GeneralName;
        let nc = crate::x509::extension::name_constraints(
            &[GeneralName::Dns(".good.example".into())],
            &[],
        );
        // Leaf claims a host outside the permitted subtree.
        let leaf_sans = [GeneralName::Dns("attacker.example".into())];
        let (root, int, leaf) = build_chain_with_nc(nc, &leaf_sans);

        let mut store = RootCertStore::new();
        store.add_der(root.to_der().to_vec()).unwrap();
        let now = Time::utc(2026, 1, 1, 0, 0, 0);
        assert!(matches!(
            verify_chain(
                &store,
                &[leaf.to_der().to_vec(), int.to_der().to_vec()],
                Some(&now),
                &policy(),
            ),
            Err(Error::BadCertificate)
        ));
    }

    #[test]
    fn name_constraints_excluded_dns_rejects_matching() {
        use crate::x509::GeneralName;
        let nc = crate::x509::extension::name_constraints(
            &[],
            &[GeneralName::Dns(".bad.example".into())],
        );
        let leaf_sans = [GeneralName::Dns("host.bad.example".into())];
        let (root, int, leaf) = build_chain_with_nc(nc, &leaf_sans);

        let mut store = RootCertStore::new();
        store.add_der(root.to_der().to_vec()).unwrap();
        let now = Time::utc(2026, 1, 1, 0, 0, 0);
        assert!(matches!(
            verify_chain(
                &store,
                &[leaf.to_der().to_vec(), int.to_der().to_vec()],
                Some(&now),
                &policy(),
            ),
            Err(Error::BadCertificate)
        ));
    }

    #[test]
    fn name_constraints_chain_rejects_san_less_leaf() {
        // CN-fallback bypass: when any CA declares name constraints, a leaf
        // without SAN slips past the constraint loop trivially (nothing to
        // iterate over) and then `verify_hostname` would happily fall back
        // to commonName matching. Refuse the chain instead.
        use crate::x509::GeneralName;
        let nc = crate::x509::extension::name_constraints(
            &[GeneralName::Dns(".good.example".into())],
            &[],
        );
        // No SAN on the leaf — only a CN, which the bypass would route
        // around constraints with.
        let leaf_sans: [GeneralName; 0] = [];
        let (root, int, leaf) = build_chain_with_nc(nc, &leaf_sans);

        let mut store = RootCertStore::new();
        store.add_der(root.to_der().to_vec()).unwrap();
        let now = Time::utc(2026, 1, 1, 0, 0, 0);
        assert!(matches!(
            verify_chain(
                &store,
                &[leaf.to_der().to_vec(), int.to_der().to_vec()],
                Some(&now),
                &policy(),
            ),
            Err(Error::BadCertificate)
        ));
    }

    #[test]
    fn name_constraints_critical_with_unenforceable_type_rejected() {
        // A critical nameConstraints carrying an rfc822Name (email) subtree
        // is something we can't evaluate — the chain must fail closed.
        use crate::x509::GeneralName;
        let nc = crate::x509::extension::name_constraints(
            &[GeneralName::Email("admin@example.com".into())],
            &[],
        );
        // SAN unrelated; the rejection comes from the extension being a
        // critical unknown-shape rather than from SAN evaluation.
        let leaf_sans = [GeneralName::Dns("leaf.example".into())];
        let (root, int, leaf) = build_chain_with_nc(nc, &leaf_sans);

        let mut store = RootCertStore::new();
        store.add_der(root.to_der().to_vec()).unwrap();
        let now = Time::utc(2026, 1, 1, 0, 0, 0);
        assert!(matches!(
            verify_chain(
                &store,
                &[leaf.to_der().to_vec(), int.to_der().to_vec()],
                Some(&now),
                &policy(),
            ),
            Err(Error::BadCertificate)
        ));
    }

    // ----------------------------------------------------------------------
    // RFC 5280 §6.1.4 propagation regression tests: a CA's nameConstraints
    // must apply to EVERY subordinate certificate (intermediates + leaf), not
    // only the end-entity leaf. The constraint is declared on the topmost
    // in-chain intermediate (`sub1`) — the trust anchor (root) lives in the
    // store, which retains only its name + key, so a root-resident constraint
    // could not be enforced; `sub1` IS part of the presented chain.
    // ----------------------------------------------------------------------

    /// Builds `root → sub1 → sub2 → leaf`. `sub1` (topmost in-chain
    /// intermediate) declares `nameConstraints` permitting only
    /// `.example.com`. `sub2_san` is sub-CA-2's dNSName SAN; `leaf_san` is the
    /// leaf's. The root is unconstrained. Returns `(root, sub1, sub2, leaf)`.
    #[allow(clippy::type_complexity)]
    fn build_propagation_chain(
        sub2_san: &str,
        leaf_san: &str,
    ) -> (Certificate, Certificate, Certificate, Certificate) {
        use crate::ec::{BoxedEcdsaPrivateKey, CurveId};
        use crate::rng::HmacDrbg;
        use crate::x509::{
            CertSigner, GeneralName, KeyUsageBits,
            extension::{
                basic_constraints, extended_key_usage, key_usage, name_constraints,
                subject_alt_name,
            },
        };

        let mut rng = HmacDrbg::<crate::hash::Sha256>::new(b"nc-propagate", b"n", &[]);
        let root_key = BoxedEcdsaPrivateKey::generate(CurveId::P256, &mut rng);
        let sub1_key = BoxedEcdsaPrivateKey::generate(CurveId::P256, &mut rng);
        let sub2_key = BoxedEcdsaPrivateKey::generate(CurveId::P256, &mut rng);
        let leaf_key = BoxedEcdsaPrivateKey::generate(CurveId::P256, &mut rng);
        let root_signer = CertSigner::Ecdsa(&root_key);
        let sub1_signer = CertSigner::Ecdsa(&sub1_key);
        let sub2_signer = CertSigner::Ecdsa(&sub2_key);

        let root_name = DistinguishedName::common_name("prop-root");
        let sub1_name = DistinguishedName::common_name("prop-sub1");
        let sub2_name = DistinguishedName::common_name("prop-sub2");
        let leaf_name = DistinguishedName::common_name("prop-leaf");

        // Unconstrained root (anchor; its own constraints could not be
        // enforced from the store anyway).
        let root = Certificate::self_signed_with_extensions(
            &root_signer,
            &root_name,
            &validity(),
            1,
            &[
                basic_constraints(true, None),
                key_usage(KeyUsageBits::KEY_CERT_SIGN | KeyUsageBits::CRL_SIGN),
            ],
        )
        .unwrap();

        // Topmost in-chain intermediate constrains the subtree below it to
        // `.example.com`. It declares no SAN of its own (the constraint it
        // declares governs its subordinates, not itself).
        let sub1_pub = crate::x509::AnyPublicKey::Ecdsa(sub1_key.public_key());
        let sub1 = Certificate::issue_with_extensions(
            &root_signer,
            &root_name,
            &sub1_name,
            &sub1_pub,
            &validity(),
            2,
            &[
                basic_constraints(true, None),
                key_usage(KeyUsageBits::KEY_CERT_SIGN | KeyUsageBits::CRL_SIGN),
                name_constraints(&[GeneralName::Dns(".example.com".into())], &[]),
            ],
        )
        .unwrap();

        // Sub-CA-2: a subordinate CA governed by sub1's constraint. Its own
        // SAN is `sub2_san`.
        let sub2_pub = crate::x509::AnyPublicKey::Ecdsa(sub2_key.public_key());
        let sub2 = Certificate::issue_with_extensions(
            &sub1_signer,
            &sub1_name,
            &sub2_name,
            &sub2_pub,
            &validity(),
            3,
            &[
                basic_constraints(true, None),
                key_usage(KeyUsageBits::KEY_CERT_SIGN | KeyUsageBits::CRL_SIGN),
                subject_alt_name(&[GeneralName::Dns(sub2_san.into())]),
            ],
        )
        .unwrap();

        // Leaf signed by sub2, with SAN `leaf_san`.
        let leaf_pub = crate::x509::AnyPublicKey::Ecdsa(leaf_key.public_key());
        let leaf = Certificate::issue_with_extensions(
            &sub2_signer,
            &sub2_name,
            &leaf_name,
            &leaf_pub,
            &validity(),
            4,
            &[
                basic_constraints(false, None),
                key_usage(KeyUsageBits::DIGITAL_SIGNATURE),
                extended_key_usage(&[oid::ID_KP_SERVER_AUTH]),
                subject_alt_name(&[GeneralName::Dns(leaf_san.into())]),
            ],
        )
        .unwrap();
        (root, sub1, sub2, leaf)
    }

    /// Case a: a constraint-declaring intermediate (`sub1` permits
    /// `.example.com`) plus an out-of-constraint sub-CA (`sub2`'s own SAN is
    /// `evil.com`) plus an in-constraint leaf MUST be rejected — the sub-CA
    /// violates `sub1`'s constraint even though the leaf is in-scope. The old
    /// leaf-only check wrongly accepted this; it never looked at the
    /// intermediate's names.
    #[test]
    fn name_constraints_reject_out_of_scope_intermediate() {
        let (root, sub1, sub2, leaf) = build_propagation_chain("evil.com", "host.example.com");
        let mut store = RootCertStore::new();
        store.add_der(root.to_der().to_vec()).unwrap();
        let now = Time::utc(2026, 1, 1, 0, 0, 0);
        let chain = alloc::vec![
            leaf.to_der().to_vec(),
            sub2.to_der().to_vec(),
            sub1.to_der().to_vec(),
        ];
        assert!(matches!(
            verify_chain(&store, &chain, Some(&now), &policy()),
            Err(Error::BadCertificate)
        ));
    }

    /// Case b: a fully in-constraint chain (the sub-CA below the constraint
    /// and the leaf both within `.example.com`) still validates.
    #[test]
    fn name_constraints_accept_fully_in_scope_chain() {
        let (root, sub1, sub2, leaf) =
            build_propagation_chain("ca2.example.com", "host.example.com");
        let mut store = RootCertStore::new();
        store.add_der(root.to_der().to_vec()).unwrap();
        let now = Time::utc(2026, 1, 1, 0, 0, 0);
        let chain = alloc::vec![
            leaf.to_der().to_vec(),
            sub2.to_der().to_vec(),
            sub1.to_der().to_vec(),
        ];
        verify_chain(&store, &chain, Some(&now), &policy()).unwrap();
    }

    /// Variant of (a): the sub-CA is in-scope but the LEAF is out-of-scope —
    /// still rejected (the leaf check was already correct, and propagation
    /// must not regress it).
    #[test]
    fn name_constraints_reject_out_of_scope_leaf_below_in_scope_intermediate() {
        let (root, sub1, sub2, leaf) = build_propagation_chain("ca2.example.com", "host.evil.com");
        let mut store = RootCertStore::new();
        store.add_der(root.to_der().to_vec()).unwrap();
        let now = Time::utc(2026, 1, 1, 0, 0, 0);
        let chain = alloc::vec![
            leaf.to_der().to_vec(),
            sub2.to_der().to_vec(),
            sub1.to_der().to_vec(),
        ];
        assert!(matches!(
            verify_chain(&store, &chain, Some(&now), &policy()),
            Err(Error::BadCertificate)
        ));
    }
}