openlatch-client 0.6.19

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
//! The per-install certificate authority behind the intercepting relay (I-2 plan 01, §1).
//!
//! Layout — `$OPENLATCH_DIR/model-relay/ca/`:
//!   `ca.key`  PKCS#8 PEM, owner-only (`fs_secure::write_owner_only`). Never leaves this process.
//!   `ca.pem`  the certificate alone, readable (`fs_secure::write_readable`): the trust installer
//!             (plan 02) and the CLI wrapper's `NODE_EXTRA_CA_CERTS` read it. No private material.
//!
//! Leaves never touch disk. Each has its own P-256 key, never the CA's.
//!
//! REGENERATION RULE (D-06): only when the pair is missing or does not parse. An EXPIRED CA is
//! loaded as it is — the OS trust store and every running agent read the CA once, so a CA that
//! changes under them is an outage with no error message. Rotation is an explicit, proven step
//! (plan 04, D-31) built on [`LocalCa::generate_into`].

use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::time::Instant;

use rcgen::{
    BasicConstraints, CertificateParams, DistinguishedName, DnType, ExtendedKeyUsagePurpose, IsCa,
    Issuer, KeyPair, KeyUsagePurpose,
};
use rustls::pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer};
use rustls::server::{ClientHello, ResolvesServerCert};
use rustls::sign::CertifiedKey;
use rustls::ServerConfig;
use time::{Duration, OffsetDateTime};

use super::host_match::{self, HostRule};
use crate::error::{OlError, ERR_MODEL_RELAY_IO};

// All four consts are `i64` and are used bare everywhere (`Duration::days(CA_RELEASE_DAYS)`):
// no `as i64` / `i64::from`, which clippy -D warnings rejects as an unnecessary cast.
pub const CA_VALIDITY_DAYS: i64 = 365;
pub const LEAF_VALIDITY_DAYS: i64 = 90;
/// Doctor renders Degraded under this many days of CA validity (plan 04 reads it, D-31).
pub const CA_WARN_DAYS: i64 = 30;
/// The daemon releases every ProxyEnv delivery under this many days (plan 04 acts on it, D-31).
pub const CA_RELEASE_DAYS: i64 = 7;
/// A leaf with less than this left is re-minted by the next `set_hosts`. Private: not contract.
const LEAF_REMINT_DAYS: i64 = 30;
/// Clock-skew allowance on `not_before`, CA and leaves alike (lifted from the POC).
const BACKDATE: Duration = Duration::hours(1);
pub(crate) const CA_COMMON_NAME: &str = "OpenLatch Model Relay CA";
/// At most this many pattern-host leaves are kept, least recently used evicted first (AGT-6
/// plan D-9). A pattern's host set is open by construction, so the cache is what bounds it.
const PATTERN_LEAF_CAP: usize = 64;
/// At most this many pattern-host leaves are minted per rolling [`PATTERN_MINT_WINDOW`] (D-9):
/// keygen cost and the decryptable surface stay bounded whatever an agent CONNECTs to.
const PATTERN_MINTS_PER_WINDOW: usize = 8;
const PATTERN_MINT_WINDOW: std::time::Duration = std::time::Duration::from_secs(60);

/// `$OPENLATCH_DIR/model-relay/ca`. Nested joins, never "model-relay/ca" (ci/check-portability.py).
pub fn ca_dir(openlatch_dir: &Path) -> PathBuf {
    openlatch_dir.join("model-relay").join("ca")
}
pub fn ca_key_path(dir: &Path) -> PathBuf {
    dir.join("ca.key")
}
pub fn ca_pem_path(dir: &Path) -> PathBuf {
    dir.join("ca.pem")
}

/// The sibling directory `name` alongside `dir` — `ca.next` and `ca.prev` live beside `ca/`,
/// never inside it (plan 04's interrupted-rotation recovery, and its promotion renames).
fn sibling_dir(dir: &Path, name: &str) -> PathBuf {
    dir.with_file_name(name)
}

fn io_err(path: &Path, e: std::io::Error) -> OlError {
    OlError::new(
        ERR_MODEL_RELAY_IO,
        format!("model relay CA {}: {e}", path.display()),
    )
}

fn rcgen_err(path: &Path, e: rcgen::Error) -> OlError {
    OlError::new(
        ERR_MODEL_RELAY_IO,
        format!("model relay CA {}: {e}", path.display()),
    )
}

/// True iff `dir` holds a `ca.key` + `ca.pem` pair that [`LocalCa::load`] can parse.
fn loadable(dir: &Path) -> bool {
    ca_key_path(dir).exists() && ca_pem_path(dir).exists() && LocalCa::load(dir).is_ok()
}

/// What `inspect` reads off `ca.pem` without touching the key or generating anything.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CaInfo {
    pub sha256_hex: String,
    pub not_after: OffsetDateTime,
}

pub struct LocalCa {
    /// ALWAYS an `Issuer` loaded through `Issuer::from_ca_cert_pem`, never a `CertifiedIssuer`:
    /// a fresh CA is written to disk and then reloaded through the same path an existing one
    /// takes, so the on-disk round trip runs on every first start.
    issuer: Issuer<'static, KeyPair>,
    sha256_hex: String,
    not_after: OffsetDateTime,
    dir: PathBuf,
}

impl LocalCa {
    /// Load the CA at `dir`, generating one if none exists (D-06: an EXPIRED CA is loaded as
    /// it is — never compare `not_after` here).
    ///
    /// Step 0 is plan 04's interrupted-rotation recovery: if `dir` does not hold a loadable
    /// pair and the sibling `ca.next` does, that promotion is finished here rather than
    /// generating a fresh CA nothing yet trusts.
    pub fn load_or_generate(dir: &Path) -> Result<LocalCa, OlError> {
        let next_dir = sibling_dir(dir, "ca.next");
        if !loadable(dir) && loadable(&next_dir) {
            let prev_dir = sibling_dir(dir, "ca.prev");
            if dir.exists() && !prev_dir.exists() {
                std::fs::rename(dir, &prev_dir).map_err(|e| io_err(dir, e))?;
            }
            std::fs::rename(&next_dir, dir).map_err(|e| io_err(&next_dir, e))?;
        }

        if ca_key_path(dir).exists() && ca_pem_path(dir).exists() {
            match Self::load(dir) {
                Ok(ca) => return Ok(ca),
                Err(e) => {
                    tracing::warn!(
                        error = %e.message,
                        "model relay CA unparseable; regenerating"
                    );
                }
            }
        }
        Self::generate_into(dir)
    }

    /// Mint a NEW CA into `dir`, overwriting whatever is there, then reload it. Rotation's
    /// first step (D-31, plan 04 passes a staging directory); [`load_or_generate`]'s second.
    pub fn generate_into(dir: &Path) -> Result<LocalCa, OlError> {
        let now = OffsetDateTime::now_utc();
        Self::build_and_persist(dir, now - BACKDATE, now + Duration::days(CA_VALIDITY_DAYS))
    }

    /// Test-only twin of [`generate_into`](Self::generate_into) with an explicit validity
    /// window, so a test can prove the D-06 "load an expired CA as it is" rule against a CA
    /// that is provably already expired.
    #[cfg(test)]
    fn generate_with_validity(
        dir: &Path,
        not_before: OffsetDateTime,
        not_after: OffsetDateTime,
    ) -> Result<LocalCa, OlError> {
        Self::build_and_persist(dir, not_before, not_after)
    }

    /// PRIVATE. The CertificateParams-build-write-reload shared by [`generate_into`]
    /// (Self::generate_into) and the test-only [`generate_with_validity`]
    /// (Self::generate_with_validity): they differ only in the validity window.
    fn build_and_persist(
        dir: &Path,
        not_before: OffsetDateTime,
        not_after: OffsetDateTime,
    ) -> Result<LocalCa, OlError> {
        let mut params =
            CertificateParams::new(Vec::<String>::new()).map_err(|e| rcgen_err(dir, e))?;
        let mut name = DistinguishedName::new();
        name.push(DnType::CommonName, CA_COMMON_NAME);
        name.push(DnType::OrganizationName, "OpenLatch");
        params.distinguished_name = name;
        params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
        params.key_usages = vec![
            KeyUsagePurpose::KeyCertSign,
            KeyUsagePurpose::CrlSign,
            KeyUsagePurpose::DigitalSignature,
        ];
        params.not_before = not_before;
        params.not_after = not_after;
        // D-04: no `name_constraints` — the allow-list is enforced by the resolver, never by
        // X.509 name constraints (see the REJECTED table in plan 01 §1).

        let key = KeyPair::generate().map_err(|e| rcgen_err(dir, e))?;
        let cert = params.self_signed(&key).map_err(|e| rcgen_err(dir, e))?;

        crate::fs_secure::create_dir_owner_only(dir).map_err(|e| io_err(dir, e))?;
        // KEY FIRST: a crash between the two writes leaves a new key beside an old or absent
        // cert, and step 1 of `load_or_generate` then fails to load the pair and regenerates —
        // the pair on disk is never half of two CAs that both "parse".
        crate::fs_secure::write_owner_only(&ca_key_path(dir), &key.serialize_pem())
            .map_err(|e| io_err(&ca_key_path(dir), e))?;
        crate::fs_secure::write_readable(&ca_pem_path(dir), &cert.pem())
            .map_err(|e| io_err(&ca_pem_path(dir), e))?;

        Self::load(dir)
    }

    /// Read both files back off disk and rebuild the signing issuer plus the cached facts.
    fn load(dir: &Path) -> Result<LocalCa, OlError> {
        let key_path = ca_key_path(dir);
        let pem_path = ca_pem_path(dir);
        let key_pem = std::fs::read_to_string(&key_path).map_err(|e| io_err(&key_path, e))?;
        let pem = std::fs::read_to_string(&pem_path).map_err(|e| io_err(&pem_path, e))?;

        let key = KeyPair::from_pem(&key_pem).map_err(|e| rcgen_err(&key_path, e))?;
        // A key that does not match the certificate is NOT detected here (rcgen does not
        // check); it surfaces as a handshake every client refuses, which D-32 counts.
        // Documented, not fixed.
        let issuer = Issuer::from_ca_cert_pem(&pem, key).map_err(|e| rcgen_err(&pem_path, e))?;

        let cert_der = CertificateDer::from_pem_slice(pem.as_bytes()).map_err(|e| {
            OlError::new(
                ERR_MODEL_RELAY_IO,
                format!("model relay CA {}: {e}", pem_path.display()),
            )
        })?;
        let (sha256_hex, not_after) = cert_facts(&cert_der)?;

        Ok(LocalCa {
            issuer,
            sha256_hex,
            not_after,
            dir: dir.to_path_buf(),
        })
    }

    /// Lowercase hex SHA-256 of the certificate DER — the key the trust store is idempotent
    /// on (D-29). macOS `security find-certificate -Z` prints UPPERCASE: compare
    /// case-insensitively.
    pub fn sha256_hex(&self) -> String {
        self.sha256_hex.clone()
    }
    pub fn not_after(&self) -> OffsetDateTime {
        self.not_after
    }
    pub fn pem_path(&self) -> PathBuf {
        ca_pem_path(&self.dir)
    }

    /// Mint a leaf for exactly `host` with its OWN key pair. A name carrying `*` is refused, so
    /// no wildcard certificate can be minted from any path (AGT-6 C-5).
    fn mint(&self, host: &str) -> Result<Leaf, OlError> {
        if host.contains('*') {
            return Err(OlError::new(
                ERR_MODEL_RELAY_IO,
                format!("model relay never mints a wildcard leaf: {host}"),
            ));
        }
        let mut params =
            CertificateParams::new(vec![host.to_string()]).map_err(|e| rcgen_err(&self.dir, e))?;
        let mut name = DistinguishedName::new();
        name.push(DnType::CommonName, host);
        params.distinguished_name = name;
        params.is_ca = IsCa::NoCa;
        // rustls requires id-kp-serverAuth on a server certificate.
        params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth];
        params.key_usages = vec![KeyUsagePurpose::DigitalSignature];
        params.use_authority_key_identifier_extension = true;
        let now = OffsetDateTime::now_utc();
        params.not_before = now - BACKDATE;
        let wanted = now + Duration::days(LEAF_VALIDITY_DAYS);
        // Never outlives the CA.
        params.not_after = if wanted < self.not_after {
            wanted
        } else {
            self.not_after
        };
        // `serial_number` left `None`: rcgen derives it from the SHA-256 of THIS leaf's fresh
        // public key, unique because every leaf key is fresh.

        let key = KeyPair::generate().map_err(|e| rcgen_err(&self.dir, e))?;
        let not_after = params.not_after;
        let cert = params
            .signed_by(&key, &self.issuer)
            .map_err(|e| rcgen_err(&self.dir, e))?;
        Ok(Leaf {
            cert,
            key,
            not_after,
        })
    }
}

/// SHA-256 (sha2 + hex, both full-cli deps) and `not_after` via the same call rcgen makes
/// internally. Shared by `load` and `inspect`.
fn cert_facts(der: &[u8]) -> Result<(String, OffsetDateTime), OlError> {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(der);
    let sha256_hex = hex::encode(hasher.finalize());

    let (_, x509) = x509_parser::parse_x509_certificate(der).map_err(|e| {
        OlError::new(
            ERR_MODEL_RELAY_IO,
            format!("model relay CA certificate could not be parsed: {e}"),
        )
    })?;
    let not_after = x509.validity().not_after.to_datetime();
    Ok((sha256_hex, not_after))
}

/// Read `ca.pem` only. `None` when absent or unparseable. NEVER generates, never reads the
/// key: doctor (plan 04) calls it on every run and must not mint a CA as a side effect.
pub fn inspect(dir: &Path) -> Option<CaInfo> {
    let pem = std::fs::read_to_string(ca_pem_path(dir)).ok()?;
    let der = CertificateDer::from_pem_slice(pem.as_bytes()).ok()?;
    let (sha256_hex, not_after) = cert_facts(&der).ok()?;
    Some(CaInfo {
        sha256_hex,
        not_after,
    })
}

/// The SHA-1 thumbprint of the certificate at `ca_pem`, spelled the way Windows' root-store
/// dialog prints it: uppercase hex in groups of eight, space-separated
/// (`06FA2596 A55ACC0E 657EF1EA F5942AAA D5F054F8`). It is what the user compares against the
/// dialog before answering it — an identifier, never an integrity check; the idempotency key
/// everywhere else stays SHA-256. `None` when the file is absent or not a PEM certificate.
pub fn windows_thumbprint(ca_pem: &Path) -> Option<String> {
    use sha1::{Digest, Sha1};
    let pem = std::fs::read(ca_pem).ok()?;
    let der = CertificateDer::from_pem_slice(&pem).ok()?;
    let hex = hex::encode_upper(Sha1::digest(der.as_ref()));
    let groups: Vec<&str> = hex
        .as_bytes()
        .chunks(8)
        .filter_map(|group| std::str::from_utf8(group).ok())
        .collect();
    Some(groups.join(" "))
}

/// Remove the whole CA directory. `Ok(true)` when something was removed, `Ok(false)` when it
/// was already absent (`NotFound` is not an error). The trust-store half of removal is plan
/// 04's (D-06r); this is the disk half only.
pub fn remove(dir: &Path) -> Result<bool, OlError> {
    match std::fs::remove_dir_all(dir) {
        Ok(()) => Ok(true),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(e) => Err(io_err(dir, e)),
    }
}

/// What `mint` returns: the rcgen certificate (for `.pem()`/`.der()`), its own key, its expiry.
struct Leaf {
    cert: rcgen::Certificate,
    key: KeyPair,
    not_after: OffsetDateTime,
}

/// One minted leaf, held in memory. `Debug` because `OlAuthority` derives it.
#[derive(Debug)]
struct LeafEntry {
    key: Arc<CertifiedKey>,
    not_after: OffsetDateTime,
}

/// One pattern host's leaf, as served: its pinned config (resolver over that one leaf) and expiry.
struct PatternLeaf {
    config: Arc<ServerConfig>,
    not_after: OffsetDateTime,
}

/// The pattern-host leaves minted at CONNECT (AGT-6 plan D-9): a small LRU (`order`, least recent
/// at the front) bounded at [`PATTERN_LEAF_CAP`], and the instants of recent mints, bounded at
/// [`PATTERN_MINTS_PER_WINDOW`] per rolling [`PATTERN_MINT_WINDOW`]. No new crate: at most 64
/// entries, so a linear `order` scan costs nothing. Held under one `Mutex` that is NEVER held
/// across a mint.
#[derive(Default)]
struct PatternLeaves {
    entries: BTreeMap<String, PatternLeaf>,
    order: VecDeque<String>,
    mints: VecDeque<Instant>,
}

impl PatternLeaves {
    /// The cached config for `host`, marked most recently used. A leaf within
    /// [`LEAF_REMINT_DAYS`] of expiry is dropped and reported as a miss, so it is re-minted —
    /// unless it was clipped to the CA's own expiry (`ca_not_after`): a re-mint could do no
    /// better, so a still-valid clipped leaf is served for the CA's last days.
    fn get(
        &mut self,
        host: &str,
        now: OffsetDateTime,
        ca_not_after: OffsetDateTime,
    ) -> Option<Arc<ServerConfig>> {
        let fresh = self.entries.get(host).map(|e| {
            e.not_after > now
                && (e.not_after - now > Duration::days(LEAF_REMINT_DAYS)
                    || e.not_after >= ca_not_after)
        })?;
        if !fresh {
            self.remove(host);
            return None;
        }
        self.touch(host);
        self.entries.get(host).map(|e| e.config.clone())
    }

    fn touch(&mut self, host: &str) {
        if let Some(pos) = self.order.iter().position(|h| h == host) {
            if let Some(h) = self.order.remove(pos) {
                self.order.push_back(h);
            }
        }
    }

    fn remove(&mut self, host: &str) {
        self.entries.remove(host);
        self.order.retain(|h| h != host);
    }

    /// Take one mint slot at `now`, or `false` when [`PATTERN_MINTS_PER_WINDOW`] mints already
    /// happened in the last [`PATTERN_MINT_WINDOW`].
    fn try_reserve_mint(&mut self, now: Instant) -> bool {
        while self
            .mints
            .front()
            .is_some_and(|t| now.saturating_duration_since(*t) >= PATTERN_MINT_WINDOW)
        {
            self.mints.pop_front();
        }
        if self.mints.len() >= PATTERN_MINTS_PER_WINDOW {
            return false;
        }
        self.mints.push_back(now);
        true
    }

    /// Insert (or replace) `host`'s leaf as the most recent, evicting the least recent past the cap.
    fn insert(&mut self, host: String, leaf: PatternLeaf) {
        self.order.retain(|h| h != &host);
        self.order.push_back(host.clone());
        self.entries.insert(host, leaf);
        while self.entries.len() > PATTERN_LEAF_CAP {
            match self.order.pop_front() {
                Some(oldest) => {
                    self.entries.remove(&oldest);
                }
                None => break,
            }
        }
    }

    /// Keep only the hosts `keep` accepts (a pattern withdrawn by `set_patterns`).
    fn retain(&mut self, keep: impl Fn(&str) -> bool) {
        self.entries.retain(|h, _| keep(h));
        let entries = &self.entries;
        self.order.retain(|h| entries.contains_key(h));
    }
}

/// The allow-list (lifted from the POC's `OlAuthority`, now a real `ResolvesServerCert`).
///
/// `pin = None`  (the contract's `server_config()`): SNI present → exact, case-insensitive
///               lookup; SNI absent → `None`.
/// `pin = Some(h)` (one per declared host, used by `handle_connect`): SNI absent → `h`'s leaf;
///               SNI == `h` → `h`'s leaf; any other SNI → `None`.
/// `None` is rustls's documented "abort the handshake". Nothing is minted here: `resolve` runs
/// synchronously inside the handshake.
#[derive(Debug)]
struct OlAuthority {
    leaves: Arc<RwLock<BTreeMap<String, LeafEntry>>>,
    pin: Option<String>,
}

impl ResolvesServerCert for OlAuthority {
    fn resolve(&self, hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
        let want = match (hello.server_name(), &self.pin) {
            (Some(sni), Some(pin)) if !sni.eq_ignore_ascii_case(pin) => return None,
            (Some(sni), _) => sni.to_ascii_lowercase(),
            (None, Some(pin)) => pin.clone(),
            (None, None) => return None,
        };
        // A poisoned lock is recovered, the same posture as `ModelRelayState::upstream_for`.
        let leaves = self.leaves.read().unwrap_or_else(|e| e.into_inner());
        leaves.get(&want).map(|l| l.key.clone())
    }
}

/// Everything `handle_connect` needs. Shared behind `Arc` in the `InterceptSlot`.
pub struct Interceptor {
    ca: LocalCa,
    /// Lowercase declared host → leaf. THE declared set: `intercepts` reads its keys.
    leaves: Arc<RwLock<BTreeMap<String, LeafEntry>>>,
    /// Lowercase declared host → whether its config offers ALPN `h2` (Cursor I-2 D-01), and a
    /// ServerConfig whose resolver is pinned to that host. The flag is the cache key's second
    /// half: a host whose h2 membership flips gets a fresh config, never the stale ALPN list.
    pinned: RwLock<BTreeMap<String, (bool, Arc<ServerConfig>)>>,
    /// The unpinned (SNI-keyed) config — the contract's `server_config()`. Exact hosts only: a
    /// pattern host is served through its own pinned config ([`Self::connect_config`]).
    any_host: Arc<ServerConfig>,
    /// The one-label host patterns declared beside the exact hosts (AGT-6 C-5, plan D-8).
    patterns: RwLock<Vec<HostRule>>,
    /// Leaves minted at CONNECT for pattern hosts (plan D-9).
    pattern_leaves: Mutex<PatternLeaves>,
    /// CONNECTs to a pattern host tunneled untouched because the mint cap was reached.
    pattern_mint_capped: AtomicU64,
}

impl Interceptor {
    /// `h2_hosts`: see [`Self::set_hosts`].
    pub fn new(
        dir: &Path,
        hosts: impl IntoIterator<Item = impl Into<String>>,
        h2_hosts: impl IntoIterator<Item = impl Into<String>>,
    ) -> Result<Interceptor, OlError> {
        let ca = LocalCa::load_or_generate(dir)?;
        let leaves: Arc<RwLock<BTreeMap<String, LeafEntry>>> =
            Arc::new(RwLock::new(BTreeMap::new()));
        let any_host = server_config_with(&leaves, None, false)?;
        let interceptor = Interceptor {
            ca,
            leaves,
            pinned: RwLock::new(BTreeMap::new()),
            any_host,
            patterns: RwLock::new(Vec::new()),
            pattern_leaves: Mutex::new(PatternLeaves::default()),
            pattern_mint_capped: AtomicU64::new(0),
        };
        interceptor.set_hosts(hosts, h2_hosts)?;
        Ok(interceptor)
    }

    /// Replace the declared set. Idempotent; plan 02's wiring tick calls it every tick.
    ///
    /// `h2_hosts` (Cursor I-2 D-01) names the declared hosts whose leaf offers ALPN `h2`, in the
    /// SAME call as the host set, so no tick can serve a new host set with a stale h2 set. Case
    /// is ignored; an entry that is not in `hosts` flags nothing.
    ///
    /// Minting happens OUTSIDE any lock, and both locks are taken and released one at a time
    /// (never together) — see the "Lock order" note in plan 01 §1. Any error is returned
    /// BEFORE either lock is written: a failed call leaves the previous set serving.
    pub fn set_hosts(
        &self,
        hosts: impl IntoIterator<Item = impl Into<String>>,
        h2_hosts: impl IntoIterator<Item = impl Into<String>>,
    ) -> Result<(), OlError> {
        let want = normalize_hosts(hosts);
        let h2 = normalize_hosts(h2_hosts);

        // Reusable leaves are copied out under the read lock; everything that needs minting is
        // minted after the guard is dropped, so a handshake's `resolve` never waits on keygen.
        let mut minted: BTreeMap<String, LeafEntry> = BTreeMap::new();
        {
            let existing = self.leaves.read().unwrap_or_else(|e| e.into_inner());
            let now = OffsetDateTime::now_utc();
            for h in &want {
                if let Some(entry) = existing.get(h) {
                    if entry.not_after - now > Duration::days(LEAF_REMINT_DAYS) {
                        minted.insert(
                            h.clone(),
                            LeafEntry {
                                key: entry.key.clone(),
                                not_after: entry.not_after,
                            },
                        );
                    }
                }
            }
        }
        let to_mint: Vec<&String> = want.iter().filter(|h| !minted.contains_key(*h)).collect();
        for h in to_mint {
            minted.insert(h.clone(), self.certified_leaf(h)?);
        }

        let mut pinned_new: BTreeMap<String, (bool, Arc<ServerConfig>)> = BTreeMap::new();
        {
            let existing_pinned = self.pinned.read().unwrap_or_else(|e| e.into_inner());
            for h in &want {
                let is_h2 = h2.contains(h);
                let cfg = match existing_pinned.get(h) {
                    // Reused only while its ALPN list still matches the host's h2 membership.
                    Some((was_h2, cfg)) if *was_h2 == is_h2 => cfg.clone(),
                    // `&self.leaves` — the resolver reads it live, so a config built now
                    // already serves whatever `minted` is about to become.
                    _ => server_config_with(&self.leaves, Some(h), is_h2)?,
                };
                pinned_new.insert(h.clone(), (is_h2, cfg));
            }
        }

        *self.leaves.write().unwrap_or_else(|e| e.into_inner()) = minted;
        *self.pinned.write().unwrap_or_else(|e| e.into_inner()) = pinned_new;
        Ok(())
    }

    /// A freshly minted leaf for `host`, ready to serve. Never called under a lock.
    fn certified_leaf(&self, host: &str) -> Result<LeafEntry, OlError> {
        let leaf = self.ca.mint(host)?;
        let signing_key = rustls::crypto::ring::sign::any_ecdsa_type(&PrivateKeyDer::Pkcs8(
            leaf.key.serialize_der().into(),
        ))
        .map_err(|e| {
            OlError::new(
                ERR_MODEL_RELAY_IO,
                format!("model relay leaf key for {host}: {e}"),
            )
        })?;
        let certified = CertifiedKey::new(vec![leaf.cert.der().clone()], signing_key);
        Ok(LeafEntry {
            key: Arc::new(certified),
            not_after: leaf.not_after,
        })
    }

    /// Replace the declared one-label host patterns (AGT-6 C-5, plan D-8). Idempotent, like
    /// [`Self::set_hosts`]. A cached pattern leaf whose host no longer matches is dropped.
    pub fn set_patterns(&self, rules: impl IntoIterator<Item = HostRule>) {
        let rules: Vec<HostRule> = rules.into_iter().collect();
        self.pattern_leaves
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .retain(|h| host_match::matches(&rules, h));
        *self.patterns.write().unwrap_or_else(|e| e.into_inner()) = rules;
    }

    /// Whether `host` (already [`host_match::normalize`]d) matches a declared pattern.
    fn matches_pattern(&self, host: &str) -> bool {
        host_match::matches(
            &self.patterns.read().unwrap_or_else(|e| e.into_inner()),
            host,
        )
    }

    /// Whether `host` (already normalized) is a declared EXACT host.
    fn is_exact(&self, host: &str) -> bool {
        self.leaves
            .read()
            .unwrap_or_else(|e| e.into_inner())
            .contains_key(host)
    }

    /// True iff `host` (case-insensitive, one trailing dot ignored, no port) is declared: an
    /// exact host, or a match of a declared pattern. THE declared-host test; whether a pattern
    /// host is actually intercepted also depends on its leaf ([`Self::ensure_leaf`]).
    pub fn intercepts(&self, host: &str) -> bool {
        let host = host_match::normalize(host);
        self.is_exact(&host) || self.matches_pattern(&host)
    }

    /// Make sure a leaf is served for `host` — `handle_connect`'s decision between intercepting
    /// and tunneling. An exact host always has one (`set_hosts` pre-mints). A pattern host is
    /// served from the LRU, or minted now, OUTSIDE every lock (plan D-9); `false` when the mint
    /// cap is reached (counted in [`Self::pattern_mint_capped`]), when the mint fails, or when
    /// the host is not declared at all — the CONNECT is then tunneled untouched.
    pub fn ensure_leaf(&self, host: &str) -> bool {
        self.connect_config(host).is_some()
    }

    /// [`Self::ensure_leaf`]'s answer as the config itself: the leaf config this CONNECT is
    /// served with, chosen once here and kept by `handle_connect` for the handshake, so an LRU
    /// eviction while the ClientHello is awaited never invalidates a CONNECT already answered
    /// `200` (plan D-9). `None` exactly when [`Self::ensure_leaf`] is `false`.
    pub(crate) fn connect_config(&self, host: &str) -> Option<Arc<ServerConfig>> {
        let host = host_match::normalize(host);
        if self.is_exact(&host) {
            return self
                .pinned
                .read()
                .unwrap_or_else(|e| e.into_inner())
                .get(host.as_ref())
                .map(|(_, cfg)| cfg.clone());
        }
        if !self.matches_pattern(&host) {
            return None;
        }
        {
            let mut cache = self
                .pattern_leaves
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            if let Some(cfg) = cache.get(&host, OffsetDateTime::now_utc(), self.ca.not_after()) {
                return Some(cfg);
            }
            if !cache.try_reserve_mint(Instant::now()) {
                drop(cache);
                self.pattern_mint_capped.fetch_add(1, Ordering::Relaxed);
                tracing::debug!(
                    host = %host,
                    "model relay pattern leaf mint cap reached; CONNECT tunneled untouched"
                );
                return None;
            }
        }
        // Minted with no lock held: a handshake's `resolve` and other CONNECTs never wait on keygen.
        let built = self.certified_leaf(&host).and_then(|entry| {
            let not_after = entry.not_after;
            let one: Arc<RwLock<BTreeMap<String, LeafEntry>>> =
                Arc::new(RwLock::new(BTreeMap::from([(host.to_string(), entry)])));
            server_config_with(&one, Some(&host), false)
                .map(|config| PatternLeaf { config, not_after })
        });
        match built {
            Ok(leaf) => {
                let config = leaf.config.clone();
                self.pattern_leaves
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .insert(host.into_owned(), leaf);
                Some(config)
            }
            Err(e) => {
                tracing::warn!(
                    code = %e.code,
                    host = %host,
                    "model relay pattern leaf could not be minted; CONNECT tunneled untouched"
                );
                None
            }
        }
    }

    /// How many CONNECTs to a pattern host were tunneled because the mint cap was reached since
    /// this interceptor was built (`pattern_mint_capped` on the relay status, AGT-6 plan D-9).
    pub fn pattern_mint_capped(&self) -> u64 {
        self.pattern_mint_capped.load(Ordering::Relaxed)
    }

    /// The SNI-keyed config over every declared host (unpinned resolver).
    pub fn server_config(&self) -> Arc<ServerConfig> {
        self.any_host.clone()
    }

    /// The config a CONNECT authority would be served now: an exact host's pinned config, else
    /// a pattern host's leaf from the LRU. Tests only — `handle_connect` keeps the config it chose
    /// at CONNECT ([`Self::connect_config`]). `None` if not declared, or a pattern host with no leaf
    /// minted (never mints: [`Self::ensure_leaf`] does).
    #[cfg(test)]
    pub(crate) fn pinned_config(&self, host: &str) -> Option<Arc<ServerConfig>> {
        let host = host_match::normalize(host);
        let exact = self
            .pinned
            .read()
            .unwrap_or_else(|e| e.into_inner())
            .get(host.as_ref())
            .map(|(_, cfg)| cfg.clone());
        if exact.is_some() || !self.matches_pattern(&host) {
            return exact;
        }
        self.pattern_leaves
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .get(&host, OffsetDateTime::now_utc(), self.ca.not_after())
    }

    /// True iff `host` (case-insensitive, no port) is declared AND flagged h2-capable (Cursor
    /// I-2 D-01). A request to such a host is never buffered (D-04), whatever protocol its
    /// connection negotiated.
    pub fn is_h2_host(&self, host: &str) -> bool {
        let host = host_match::normalize(host);
        self.pinned
            .read()
            .unwrap_or_else(|e| e.into_inner())
            .get(host.as_ref())
            .is_some_and(|(h2, _)| *h2)
    }

    /// A fresh leaf for a DECLARED host — exact or pattern-matched — as a certificate PEM (no
    /// key), for the trust store's read-back (`security verify-cert`, D-29). Not cached, not
    /// served. A host neither declared nor matched is `Err` — a leaf exists for a declared host
    /// and for nothing else, even one that is only ever read back.
    pub fn mint_leaf_pem(&self, host: &str) -> Result<String, OlError> {
        if !self.intercepts(host) {
            return Err(OlError::new(
                ERR_MODEL_RELAY_IO,
                format!("not a declared intercept host: {host}"),
            ));
        }
        Ok(self.ca.mint(&host_match::normalize(host))?.cert.pem())
    }

    /// The CA this interceptor serves from (plan 02 installs exactly this one: its `pem_path`
    /// and `sha256_hex`).
    pub fn ca(&self) -> &LocalCa {
        &self.ca
    }
}

/// Trimmed, lowercased, non-empty host names with one trailing dot removed — the one shape both
/// of `set_hosts`'s sets compare in (`host_match::normalize`). A name carrying `*` is dropped and
/// logged: no wildcard leaf is ever minted (AGT-6 C-5), and one such name must not fail the
/// whole set.
fn normalize_hosts(hosts: impl IntoIterator<Item = impl Into<String>>) -> BTreeSet<String> {
    hosts
        .into_iter()
        .map(|h| host_match::normalize(h.into().trim()).into_owned())
        .filter(|h| !h.is_empty())
        .filter(|h| {
            let wildcard = h.contains('*');
            if wildcard {
                tracing::warn!(host = %h, "model relay ignores a wildcard intercept host");
            }
            !wildcard
        })
        .collect()
}

/// A free function (not a method): `new` calls it before the `Interceptor` exists.
///
/// `h2`: whether this config's ALPN offers `h2` ahead of `http/1.1` (Cursor I-2 D-01) — `false`
/// for the any-host config and for every host not flagged h2-capable.
fn server_config_with(
    leaves: &Arc<RwLock<BTreeMap<String, LeafEntry>>>,
    pin: Option<&str>,
    h2: bool,
) -> Result<Arc<ServerConfig>, OlError> {
    let mut config =
        ServerConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
            .with_safe_default_protocol_versions()
            .map_err(|e| {
                OlError::new(
                    ERR_MODEL_RELAY_IO,
                    format!("model relay TLS server config: {e}"),
                )
            })?
            .with_no_client_auth()
            .with_cert_resolver(Arc::new(OlAuthority {
                leaves: leaves.clone(),
                pin: pin.map(str::to_string),
            }));
    // `intercept::terminate` serves HTTP/2 on a connection that negotiated `h2`, and HTTP/1.1 on
    // every other — so only an h2-flagged host is ever offered `h2`.
    config.alpn_protocols = if h2 {
        vec![b"h2".to_vec(), b"http/1.1".to_vec()]
    } else {
        vec![b"http/1.1".to_vec()]
    };
    Ok(Arc::new(config))
}

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

    /// A self-signed P-256 certificate minted once with `openssl req -x509`; its SHA-1
    /// fingerprint was read with `openssl x509 -noout -fingerprint -sha1` and pasted below, so
    /// the test proves the printed value is the one Windows shows, not one this code computed
    /// for itself.
    const FIXTURE_PEM: &str = "-----BEGIN CERTIFICATE-----
MIIBVDCB+gIJAJapbvI+vytBMAoGCCqGSM49BAMCMDIxMDAuBgNVBAMMJ09wZW5M
YXRjaCBNb2RlbCBSZWxheSBDQSAodGVzdCBmaXh0dXJlKTAeFw0yNjEwMTIyMTI5
MjRaFw0zNjEwMDkyMTI5MjRaMDIxMDAuBgNVBAMMJ09wZW5MYXRjaCBNb2RlbCBS
ZWxheSBDQSAodGVzdCBmaXh0dXJlKTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA
BEw1f96hzUHBgHWgq8MArvBeMhEvGJwuq/WddWb0q1nNRSo5c7IjIk/fNQY3PNwQ
Y21qN/aDosIP5qyjvdBO3u8wCgYIKoZIzj0EAwIDSQAwRgIhAIh0EGybuU3vtaEG
myr9qVGNaEFoqRFYvYFdqQwBF2vPAiEAxVPs54aHF5vH9g60KMQkHIJaxchUeywm
pdQ2kqiYF64=
-----END CERTIFICATE-----
";
    /// `openssl x509 -noout -fingerprint -sha1` on `FIXTURE_PEM`, colons dropped and regrouped
    /// by eight as the Windows dialog does.
    const FIXTURE_WINDOWS_THUMBPRINT: &str = "BE095A3B F3CE7BDE 40E88C58 C3F82B51 311943F6";

    #[test]
    fn windows_thumbprint_matches_openssl_in_the_dialog_layout() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let pem = tmp.path().join("ca.pem");
        std::fs::write(&pem, FIXTURE_PEM).expect("write fixture");
        assert_eq!(
            windows_thumbprint(&pem).as_deref(),
            Some(FIXTURE_WINDOWS_THUMBPRINT)
        );
    }

    #[test]
    fn windows_thumbprint_is_none_for_a_missing_or_non_pem_file() {
        let tmp = tempfile::tempdir().expect("tempdir");
        assert_eq!(windows_thumbprint(&tmp.path().join("absent.pem")), None);
        let junk = tmp.path().join("junk.pem");
        std::fs::write(&junk, "not a certificate").expect("write junk");
        assert_eq!(windows_thumbprint(&junk), None);
    }

    #[test]
    fn the_ca_is_generated_once_and_reused() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dir = tmp.path().join("ca");

        let first = LocalCa::load_or_generate(&dir).expect("first generate");
        let second = LocalCa::load_or_generate(&dir).expect("second load");
        assert_eq!(first.sha256_hex(), second.sha256_hex());
        let days = (second.not_after() - OffsetDateTime::now_utc()).whole_days();
        assert!(
            (CA_VALIDITY_DAYS - 1..=CA_VALIDITY_DAYS).contains(&days),
            "expected not_after within a day of {CA_VALIDITY_DAYS}, got {days}"
        );

        // Delete `ca.key` alone: a different sha (regenerated).
        std::fs::remove_file(ca_key_path(&dir)).expect("remove key");
        let third = LocalCa::load_or_generate(&dir).expect("regenerate after missing key");
        assert_ne!(second.sha256_hex(), third.sha256_hex());

        // Replace `ca.pem` with garbage: a different sha.
        std::fs::write(ca_pem_path(&dir), b"not a certificate").expect("corrupt pem");
        let fourth = LocalCa::load_or_generate(&dir).expect("regenerate after garbage pem");
        assert_ne!(third.sha256_hex(), fourth.sha256_hex());
    }

    #[test]
    fn an_expired_ca_is_loaded_not_regenerated() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dir = tmp.path().join("ca");
        let now = OffsetDateTime::now_utc();

        let expired = LocalCa::generate_with_validity(
            &dir,
            now - Duration::days(400),
            now - Duration::days(1),
        )
        .expect("generate an already-expired CA");
        let loaded = LocalCa::load_or_generate(&dir).expect("load, never regenerate an expired CA");
        assert_eq!(expired.sha256_hex(), loaded.sha256_hex());
        assert!(loaded.not_after() < now);
    }

    #[test]
    #[cfg(unix)]
    fn the_ca_key_is_owner_only() {
        use std::os::unix::fs::PermissionsExt;
        let tmp = tempfile::tempdir().expect("tempdir");
        let dir = tmp.path().join("ca");
        LocalCa::load_or_generate(&dir).expect("generate");

        let key_mode = std::fs::metadata(ca_key_path(&dir))
            .expect("key metadata")
            .permissions()
            .mode();
        assert_eq!(key_mode & 0o777, 0o600);
        let pem_mode = std::fs::metadata(ca_pem_path(&dir))
            .expect("pem metadata")
            .permissions()
            .mode();
        assert_eq!(pem_mode & 0o777, 0o644);
        let dir_mode = std::fs::metadata(&dir)
            .expect("dir metadata")
            .permissions()
            .mode();
        assert_eq!(dir_mode & 0o777, 0o700);
    }

    #[test]
    #[cfg(not(unix))]
    fn the_ca_key_is_owner_only() {
        // The ACL itself is asserted by `fs_secure::tests::windows_leaves_only_an_owner_ace`;
        // here we only prove both files exist under `create_dir_owner_only`/`write_owner_only`.
        let tmp = tempfile::tempdir().expect("tempdir");
        let dir = tmp.path().join("ca");
        LocalCa::load_or_generate(&dir).expect("generate");
        assert!(ca_key_path(&dir).exists());
        assert!(ca_pem_path(&dir).exists());
    }

    #[test]
    fn leaves_use_their_own_keys() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dir = tmp.path().join("ca");
        let ca = LocalCa::load_or_generate(&dir).expect("generate");

        let leaf1 = ca.mint("a.test").expect("mint 1");
        let leaf2 = ca.mint("a.test").expect("mint 2");

        let spki = |der: &[u8]| -> Vec<u8> {
            x509_parser::parse_x509_certificate(der)
                .expect("parse leaf")
                .1
                .tbs_certificate
                .subject_pki
                .subject_public_key
                .data
                .to_vec()
        };
        let ca_pem = std::fs::read_to_string(ca.pem_path()).expect("read ca.pem");
        let ca_der = CertificateDer::from_pem_slice(ca_pem.as_bytes()).expect("parse ca pem");

        let spki_ca = spki(&ca_der);
        let spki1 = spki(leaf1.cert.der());
        let spki2 = spki(leaf2.cert.der());
        assert_ne!(
            spki1, spki2,
            "two mints for one host must use distinct keys"
        );
        assert_ne!(spki1, spki_ca);
        assert_ne!(spki2, spki_ca);
    }

    #[test]
    fn a_leaf_names_its_host_and_chains_to_the_ca() {
        use rustls::client::danger::ServerCertVerifier;
        use rustls::client::WebPkiServerVerifier;
        use rustls::pki_types::{ServerName, UnixTime};
        use rustls::RootCertStore;

        let tmp = tempfile::tempdir().expect("tempdir");
        let dir = tmp.path().join("ca");
        let ca = LocalCa::load_or_generate(&dir).expect("generate");

        let ca_pem = std::fs::read_to_string(ca.pem_path()).expect("read ca.pem");
        let ca_der = CertificateDer::from_pem_slice(ca_pem.as_bytes()).expect("parse ca pem");
        let mut roots = RootCertStore::empty();
        roots.add(ca_der).expect("trust the CA");

        let verifier = WebPkiServerVerifier::builder_with_provider(
            Arc::new(roots),
            Arc::new(rustls::crypto::ring::default_provider()),
        )
        .build()
        .expect("build verifier");

        let leaf = ca.mint("a.test").expect("mint a.test");
        let leaf_der = leaf.cert.der().clone();
        let ok_name = ServerName::try_from("a.test").expect("server name");
        verifier
            .verify_server_cert(&leaf_der, &[], &ok_name, &[], UnixTime::now())
            .expect("a.test's leaf must verify for a.test");

        let bad_name = ServerName::try_from("b.test").expect("server name");
        verifier
            .verify_server_cert(&leaf_der, &[], &bad_name, &[], UnixTime::now())
            .expect_err("a.test's leaf must not verify for b.test");

        let ip_leaf = ca.mint("127.0.0.1").expect("mint IP leaf");
        let ip_der = ip_leaf.cert.der().clone();
        let ip_name = ServerName::try_from("127.0.0.1").expect("IP server name");
        verifier
            .verify_server_cert(&ip_der, &[], &ip_name, &[], UnixTime::now())
            .expect("an IP leaf must verify for its own IP SAN");
    }

    #[test]
    fn a_leaf_never_outlives_its_ca() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let short_dir = tmp.path().join("short");
        let now = OffsetDateTime::now_utc();
        let short_ca =
            LocalCa::generate_with_validity(&short_dir, now - BACKDATE, now + Duration::days(10))
                .expect("generate a short-lived CA");
        let short_leaf = short_ca.mint("a.test").expect("mint under a short CA");
        assert!(short_leaf.not_after <= short_ca.not_after());

        let long_dir = tmp.path().join("long");
        let long_ca = LocalCa::load_or_generate(&long_dir).expect("generate a full-validity CA");
        let long_leaf = long_ca
            .mint("a.test")
            .expect("mint under a full-validity CA");
        let days = (long_leaf.not_after - OffsetDateTime::now_utc()).whole_days();
        assert!(
            (LEAF_VALIDITY_DAYS - 1..=LEAF_VALIDITY_DAYS).contains(&days),
            "expected leaf not_after within a day of {LEAF_VALIDITY_DAYS}, got {days}"
        );
    }

    #[test]
    fn inspect_never_generates() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dir = tmp.path().join("ca");
        assert!(inspect(&dir).is_none());
        assert!(!dir.exists(), "inspect must never create the directory");

        let ca = LocalCa::load_or_generate(&dir).expect("generate");
        let info = inspect(&dir).expect("inspect after generate");
        assert_eq!(info.sha256_hex, ca.sha256_hex());
        assert_eq!(info.not_after, ca.not_after());
    }

    #[test]
    fn remove_deletes_the_directory_once() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dir = tmp.path().join("ca");
        LocalCa::load_or_generate(&dir).expect("generate");

        assert!(remove(&dir).expect("first remove"));
        assert!(!dir.exists());
        assert!(!remove(&dir).expect("second remove is not an error"));
    }

    #[test]
    fn generate_into_replaces_the_ca() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dir = tmp.path().join("ca");
        let first = LocalCa::load_or_generate(&dir).expect("first generate");
        let second = LocalCa::generate_into(&dir).expect("replace");
        assert_ne!(first.sha256_hex(), second.sha256_hex());
        let third = LocalCa::load_or_generate(&dir).expect("load the replacement");
        assert_eq!(second.sha256_hex(), third.sha256_hex());
    }

    #[test]
    fn an_interrupted_promotion_recovers_from_ca_next() {
        // (a) `ca/` absent, `ca.next/` holds a CA: the promotion finishes and nothing is
        // generated.
        {
            let tmp = tempfile::tempdir().expect("tempdir");
            let dir = tmp.path().join("ca");
            let next_dir = dir.with_file_name("ca.next");
            let next_ca = LocalCa::generate_into(&next_dir).expect("generate ca.next");
            assert!(!dir.exists());

            let loaded = LocalCa::load_or_generate(&dir).expect("promote and load");
            assert_eq!(loaded.sha256_hex(), next_ca.sha256_hex());
            assert!(
                !next_dir.exists(),
                "ca.next must be consumed by the promotion"
            );
        }

        // (b) `ca/` holds an unparseable `ca.pem` beside a valid `ca.key`, `ca.next/` holds a
        // CA: the ca.next sha wins, and the old `ca/` now sits at `ca.prev/`.
        {
            let tmp = tempfile::tempdir().expect("tempdir");
            let dir = tmp.path().join("ca");
            let _old = LocalCa::load_or_generate(&dir).expect("generate the old CA");
            std::fs::write(ca_pem_path(&dir), b"garbage").expect("corrupt the old pem");
            let next_dir = dir.with_file_name("ca.next");
            let next_ca = LocalCa::generate_into(&next_dir).expect("generate ca.next");
            let prev_dir = dir.with_file_name("ca.prev");
            assert!(!prev_dir.exists());

            let loaded = LocalCa::load_or_generate(&dir).expect("promote over a corrupt ca/");
            assert_eq!(loaded.sha256_hex(), next_ca.sha256_hex());
            assert!(!next_dir.exists());
            assert!(
                prev_dir.exists(),
                "the old ca/ must be preserved at ca.prev/"
            );
        }

        // (c) `ca/` absent, `ca.next/` holds garbage: a fresh generation, `ca.next/` untouched.
        {
            let tmp = tempfile::tempdir().expect("tempdir");
            let dir = tmp.path().join("ca");
            let next_dir = dir.with_file_name("ca.next");
            std::fs::create_dir_all(&next_dir).expect("create ca.next");
            std::fs::write(next_dir.join("ca.key"), b"garbage-key").expect("write garbage key");
            std::fs::write(next_dir.join("ca.pem"), b"garbage-pem").expect("write garbage pem");

            let _generated = LocalCa::load_or_generate(&dir).expect("fresh generation");
            assert!(dir.exists());
            assert_eq!(
                std::fs::read(next_dir.join("ca.key")).expect("ca.next/ca.key"),
                b"garbage-key"
            );
        }
    }

    #[test]
    fn set_hosts_mints_new_hosts_and_drops_removed_ones() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dir = tmp.path().join("ca");
        let ic = Interceptor::new(&dir, ["a.test"], None::<&str>).expect("new");

        ic.set_hosts(["b.test"], None::<&str>).expect("set_hosts");
        assert!(ic.intercepts("b.test"));
        assert!(ic.intercepts("B.TEST"));
        assert!(!ic.intercepts("a.test"));
        assert!(ic.pinned_config("a.test").is_none());

        let key_before = ic
            .leaves
            .read()
            .expect("read leaves")
            .get("b.test")
            .expect("b.test leaf")
            .key
            .clone();
        let config_before = ic.pinned_config("b.test").expect("b.test config");

        ic.set_hosts(["b.test"], None::<&str>)
            .expect("set_hosts again");

        let key_after = ic
            .leaves
            .read()
            .expect("read leaves")
            .get("b.test")
            .expect("b.test leaf")
            .key
            .clone();
        assert!(
            Arc::ptr_eq(&key_before, &key_after),
            "an unexpired leaf must be reused, not re-minted"
        );
        let config_after = ic.pinned_config("b.test").expect("b.test config");
        assert!(
            Arc::ptr_eq(&config_before, &config_after),
            "the pinned config must be reused when its leaf is reused"
        );
    }

    /// Cursor I-2 D-01: only a flagged host's leaf offers `h2`; every other config — the any-host
    /// one included — keeps exactly `[http/1.1]`.
    #[test]
    fn non_flagged_host_keeps_http1_alpn() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dir = tmp.path().join("ca");
        let ic = Interceptor::new(&dir, ["a.test", "h2.test"], ["H2.test"]).expect("new");

        let plain = ic.pinned_config("a.test").expect("a.test config");
        assert_eq!(plain.alpn_protocols, vec![b"http/1.1".to_vec()]);
        assert!(!ic.is_h2_host("a.test"));

        let flagged = ic.pinned_config("h2.test").expect("h2.test config");
        assert_eq!(
            flagged.alpn_protocols,
            vec![b"h2".to_vec(), b"http/1.1".to_vec()]
        );
        assert!(ic.is_h2_host("h2.TEST"));

        assert_eq!(
            ic.server_config().alpn_protocols,
            vec![b"http/1.1".to_vec()]
        );
        // An h2 entry that is not a declared host flags nothing and mints nothing.
        ic.set_hosts(["a.test"], ["z.test"]).expect("set_hosts");
        assert!(!ic.intercepts("z.test"));
        assert!(!ic.is_h2_host("z.test"));
    }

    /// The pinned cache is keyed on (host, h2): a host flagged after its config was built gets a
    /// rebuilt config offering `h2`, and unflagging it takes `h2` away again.
    #[test]
    fn pinned_config_is_rebuilt_when_h2_flips() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dir = tmp.path().join("ca");
        let ic = Interceptor::new(&dir, ["h.test"], None::<&str>).expect("new");
        let before = ic.pinned_config("h.test").expect("config");
        assert_eq!(before.alpn_protocols, vec![b"http/1.1".to_vec()]);

        ic.set_hosts(["h.test"], ["h.test"]).expect("flag h2");
        let flagged = ic.pinned_config("h.test").expect("config");
        assert!(
            !Arc::ptr_eq(&before, &flagged),
            "the config must be rebuilt"
        );
        assert_eq!(
            flagged.alpn_protocols,
            vec![b"h2".to_vec(), b"http/1.1".to_vec()]
        );

        ic.set_hosts(["h.test"], ["h.test"])
            .expect("same set again");
        assert!(
            Arc::ptr_eq(&flagged, &ic.pinned_config("h.test").expect("config")),
            "an unchanged flag reuses the config"
        );

        ic.set_hosts(["h.test"], None::<&str>).expect("unflag");
        assert_eq!(
            ic.pinned_config("h.test").expect("config").alpn_protocols,
            vec![b"http/1.1".to_vec()]
        );
    }

    #[test]
    fn mint_leaf_pem_refuses_an_undeclared_host() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dir = tmp.path().join("ca");
        let ic = Interceptor::new(&dir, ["a.test"], None::<&str>).expect("new");

        let pem = ic.mint_leaf_pem("a.test").expect("declared host mints");
        let der = CertificateDer::from_pem_slice(pem.as_bytes()).expect("parse minted pem");
        let (_, x509) = x509_parser::parse_x509_certificate(&der).expect("parse x509");
        assert!(!x509.is_ca(), "a leaf must not itself be a CA");
        let san = x509
            .subject_alternative_name()
            .expect("SAN parses")
            .expect("leaf carries a SAN");
        assert!(san
            .value
            .general_names
            .iter()
            .any(|n| matches!(n, GeneralName::DNSName(h) if *h == "a.test")));
        assert!(format!("{}", x509.issuer()).contains(CA_COMMON_NAME));

        let err = ic
            .mint_leaf_pem("z.test")
            .expect_err("an undeclared host must be refused");
        assert_eq!(err.code, ERR_MODEL_RELAY_IO);
    }

    /// One TLS handshake against `config`, the client trusting `ca_der` and sending `sni`.
    async fn one_handshake(
        config: Arc<ServerConfig>,
        ca_der: &CertificateDer<'static>,
        sni: &str,
    ) -> (std::io::Result<()>, std::io::Result<()>) {
        let (client_io, server_io) = tokio::io::duplex(8192);
        let acceptor = tokio_rustls::TlsAcceptor::from(config);
        let mut roots = rustls::RootCertStore::empty();
        roots.add(ca_der.clone()).expect("trust the CA");
        let client_config = rustls::ClientConfig::builder()
            .with_root_certificates(roots)
            .with_no_client_auth();
        let connector = tokio_rustls::TlsConnector::from(Arc::new(client_config));
        let server_name =
            rustls::pki_types::ServerName::try_from(sni.to_string()).expect("server name");

        let (server_res, client_res) = tokio::time::timeout(
            std::time::Duration::from_secs(5),
            futures_util::future::join(
                acceptor.accept(server_io),
                connector.connect(server_name, client_io),
            ),
        )
        .await
        .expect("handshake did not hang");
        (server_res.map(|_| ()), client_res.map(|_| ()))
    }

    #[tokio::test]
    async fn the_pinned_resolver_refuses_a_foreign_sni() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dir = tmp.path().join("ca");
        let ic = Interceptor::new(&dir, ["a.test", "c.test"], None::<&str>).expect("new");
        let ca_pem = std::fs::read_to_string(ic.ca().pem_path()).expect("read ca.pem");
        let ca_der = CertificateDer::from_pem_slice(ca_pem.as_bytes()).expect("parse ca pem");
        let config = ic.pinned_config("a.test").expect("a.test is declared");

        // SNI a.test → both halves succeed.
        let (server_ok, client_ok) = one_handshake(config.clone(), &ca_der, "a.test").await;
        server_ok.expect("server accepts a matching SNI");
        client_ok.expect("client completes against a matching SNI");

        // SNI c.test (declared, but not what THIS pinned config serves) → refused.
        let (server_err, client_err) = one_handshake(config, &ca_der, "c.test").await;
        let server_err = server_err.expect_err("server must refuse a foreign SNI");
        assert!(
            server_err
                .to_string()
                .contains("no server certificate chain resolved"),
            "unexpected server error: {server_err}"
        );
        let client_err = client_err.expect_err("client must see the refusal");
        let inner = client_err
            .get_ref()
            .and_then(|e| e.downcast_ref::<rustls::Error>());
        assert_eq!(
            inner,
            Some(&rustls::Error::AlertReceived(
                rustls::AlertDescription::AccessDenied
            )),
            "unexpected client error: {client_err}"
        );
    }

    /// A pattern rule for the tests: `<label>.pat.test`.
    const PAT: HostRule = HostRule::OneLabel {
        prefix: "",
        suffix: ".pat.test",
    };

    fn pattern_interceptor(dir: &Path) -> Interceptor {
        let ic = Interceptor::new(dir, ["a.test"], None::<&str>).expect("new");
        ic.set_patterns([PAT]);
        ic
    }

    /// The SAN DNS names of a PEM certificate.
    fn san_names(pem: &str) -> Vec<String> {
        let der = CertificateDer::from_pem_slice(pem.as_bytes()).expect("parse pem");
        let (_, x509) = x509_parser::parse_x509_certificate(&der).expect("parse x509");
        let san = x509
            .subject_alternative_name()
            .expect("SAN parses")
            .expect("leaf carries a SAN");
        san.value
            .general_names
            .iter()
            .filter_map(|n| match n {
                GeneralName::DNSName(h) => Some(h.to_string()),
                _ => None,
            })
            .collect()
    }

    /// AGT-6 C-5 / D-9: a pattern host is declared, gets no leaf until `ensure_leaf` mints one at
    /// CONNECT, then is served from the cache — reused, not re-minted. An exact host needs no mint.
    #[test]
    fn a_pattern_host_gets_its_own_leaf_at_connect() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let ic = pattern_interceptor(&tmp.path().join("ca"));

        assert!(ic.intercepts("us-east-1.pat.test"));
        assert!(ic.intercepts("US-EAST-1.PAT.TEST."));
        assert!(
            ic.pinned_config("us-east-1.pat.test").is_none(),
            "no mint before CONNECT"
        );

        assert!(ic.ensure_leaf("us-east-1.pat.test"));
        let first = ic
            .pinned_config("us-east-1.pat.test")
            .expect("served after the mint");
        assert!(
            !ic.is_h2_host("us-east-1.pat.test"),
            "a pattern leaf offers http/1.1 only"
        );
        assert_eq!(first.alpn_protocols, vec![b"http/1.1".to_vec()]);

        assert!(ic.ensure_leaf("us-east-1.pat.test."));
        let again = ic
            .pinned_config("US-EAST-1.pat.test")
            .expect("still served");
        assert!(
            Arc::ptr_eq(&first, &again),
            "a cached leaf is reused, not re-minted"
        );

        // An exact host is pre-minted by `set_hosts` and never touches the pattern cache.
        assert!(ic.ensure_leaf("a.test"));
        assert!(ic.pinned_config("a.test").is_some());
        assert_eq!(ic.pattern_mint_capped(), 0);
    }

    /// AC-12 (tunnel half), AC-13: a host neither declared nor matched gets no leaf from any
    /// path — CONNECT, served config, or trust-store read-back — and so is tunneled.
    #[test]
    fn a_host_outside_the_rules_gets_no_leaf() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let ic = pattern_interceptor(&tmp.path().join("ca"));
        for host in [
            "z.test",
            "pat.test",
            ".pat.test",
            "a.b.pat.test",
            "*.pat.test",
            "us-east-1.pat.test.evil",
        ] {
            assert!(!ic.intercepts(host), "{host}");
            assert!(!ic.ensure_leaf(host), "{host}");
            assert!(ic.pinned_config(host).is_none(), "{host}");
            assert!(ic.mint_leaf_pem(host).is_err(), "{host}");
        }
        assert_eq!(
            ic.pattern_mint_capped(),
            0,
            "an undeclared host is not a capped mint"
        );
    }

    /// AC-13: no minted name ever carries `*` — refused by the minter itself, dropped from an
    /// exact host set without failing it, and impossible through a pattern (one label only).
    #[test]
    fn no_leaf_ever_carries_a_wildcard_name() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let ic = pattern_interceptor(&tmp.path().join("ca"));
        assert!(ic.ca.mint("*.pat.test").is_err());
        assert!(ic.ca.mint("*").is_err());

        ic.set_hosts(["a.test", "*.wild.test"], None::<&str>)
            .expect("a wildcard entry is dropped, not fatal");
        assert!(ic.intercepts("a.test"));
        assert!(!ic.intercepts("*.wild.test"));
        assert!(!ic.intercepts("x.wild.test"));

        for host in ["a.test", "us-east-1.pat.test", "x.pat.test"] {
            let pem = ic.mint_leaf_pem(host).expect("declared host mints");
            let names = san_names(&pem);
            assert_eq!(names, vec![host.to_string()]);
            assert!(names.iter().all(|n| !n.contains('*')), "{names:?}");
        }
    }

    /// AC-13 / D-9: at most eight pattern leaves are minted per rolling minute; past that the
    /// CONNECT is refused a leaf (tunneled) and counted. A cached host still intercepts.
    #[test]
    fn mints_past_the_per_minute_cap_tunnel_and_are_counted() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let ic = pattern_interceptor(&tmp.path().join("ca"));
        for i in 0..PATTERN_MINTS_PER_WINDOW {
            assert!(ic.ensure_leaf(&format!("h{i}.pat.test")), "mint {i}");
        }
        assert!(
            !ic.ensure_leaf("over.pat.test"),
            "the ninth mint in a minute is capped"
        );
        assert!(ic.pinned_config("over.pat.test").is_none());
        assert!(
            ic.intercepts("over.pat.test"),
            "still declared, just not minted"
        );
        assert_eq!(ic.pattern_mint_capped(), 1);
        assert!(!ic.ensure_leaf("over2.pat.test"));
        assert_eq!(ic.pattern_mint_capped(), 2);
        // A host already cached costs no mint.
        assert!(ic.ensure_leaf("h0.pat.test"));
        assert_eq!(ic.pattern_mint_capped(), 2);
    }

    /// D-9: the rolling window frees a slot exactly one minute after a mint.
    #[test]
    fn the_mint_window_rolls() {
        let mut cache = PatternLeaves::default();
        let t0 = Instant::now();
        for _ in 0..PATTERN_MINTS_PER_WINDOW {
            assert!(cache.try_reserve_mint(t0));
        }
        assert!(!cache.try_reserve_mint(t0));
        assert!(
            !cache.try_reserve_mint(t0 + PATTERN_MINT_WINDOW - std::time::Duration::from_millis(1))
        );
        // A minute later every t0 mint has left the window; the slots come back, eight of them.
        let t1 = t0 + PATTERN_MINT_WINDOW;
        for _ in 0..PATTERN_MINTS_PER_WINDOW {
            assert!(cache.try_reserve_mint(t1));
        }
        assert!(!cache.try_reserve_mint(t1));
    }

    /// D-9: the cache holds at most 64 leaves and evicts the least recently USED one.
    #[test]
    fn the_pattern_cache_is_a_bounded_lru() {
        let leaves: Arc<RwLock<BTreeMap<String, LeafEntry>>> = Arc::default();
        let config = server_config_with(&leaves, Some("x.test"), false).expect("config");
        let far = OffsetDateTime::now_utc() + Duration::days(LEAF_VALIDITY_DAYS);
        let now = OffsetDateTime::now_utc();
        let leaf = || PatternLeaf {
            config: config.clone(),
            not_after: far,
        };

        let mut cache = PatternLeaves::default();
        for i in 0..PATTERN_LEAF_CAP {
            cache.insert(format!("h{i}"), leaf());
        }
        assert_eq!(cache.entries.len(), PATTERN_LEAF_CAP);
        // Touch the oldest, so `h1` becomes the least recent.
        assert!(cache.get("h0", now, far).is_some());
        cache.insert("new".into(), leaf());
        assert_eq!(cache.entries.len(), PATTERN_LEAF_CAP);
        assert_eq!(cache.order.len(), PATTERN_LEAF_CAP);
        assert!(
            cache.get("h0", now, far).is_some(),
            "a recently used leaf survives"
        );
        assert!(
            cache.get("h1", now, far).is_none(),
            "the least recently used leaf is evicted"
        );
        assert!(cache.get("new", now, far).is_some());

        // A leaf near its expiry is a miss and is dropped, so the next CONNECT re-mints it.
        cache.insert(
            "old".into(),
            PatternLeaf {
                config: config.clone(),
                not_after: now + Duration::days(LEAF_REMINT_DAYS - 1),
            },
        );
        assert!(cache.get("old", now, far).is_none());
        assert!(!cache.entries.contains_key("old"));
        assert!(!cache.order.iter().any(|h| h == "old"));

        // A leaf clipped to its CA's own expiry is served while still valid: a re-mint could do
        // no better. Once past its expiry it is a miss like any other.
        let ca_end = now + Duration::days(10);
        cache.insert(
            "clipped".into(),
            PatternLeaf {
                config: config.clone(),
                not_after: ca_end,
            },
        );
        assert!(cache.get("clipped", now, ca_end).is_some());
        assert!(cache
            .get("clipped", ca_end + Duration::seconds(1), ca_end)
            .is_none());
    }

    /// Completes an in-memory TLS handshake for `host` against `config`, the client trusting
    /// only the CA at `dir`. True when both sides finish.
    fn handshakes(config: Arc<ServerConfig>, dir: &Path, host: &str) -> bool {
        use rustls::pki_types::ServerName;
        let pem = std::fs::read_to_string(ca_pem_path(dir)).expect("ca pem");
        let mut roots = rustls::RootCertStore::empty();
        roots
            .add(CertificateDer::from_pem_slice(pem.as_bytes()).expect("parse ca"))
            .expect("trust the CA");
        let client_config = Arc::new(
            rustls::ClientConfig::builder_with_provider(Arc::new(
                rustls::crypto::ring::default_provider(),
            ))
            .with_safe_default_protocol_versions()
            .expect("versions")
            .with_root_certificates(roots)
            .with_no_client_auth(),
        );
        let name = ServerName::try_from(host.to_string()).expect("server name");
        let mut client = rustls::ClientConnection::new(client_config, name).expect("client");
        let mut server = rustls::ServerConnection::new(config).expect("server");
        for _ in 0..8 {
            let mut buf = Vec::new();
            client.write_tls(&mut buf).expect("client write");
            server.read_tls(&mut buf.as_slice()).expect("server read");
            if server.process_new_packets().is_err() {
                return false;
            }
            let mut buf = Vec::new();
            server.write_tls(&mut buf).expect("server write");
            client.read_tls(&mut buf.as_slice()).expect("client read");
            if client.process_new_packets().is_err() {
                return false;
            }
            if !client.is_handshaking() && !server.is_handshaking() {
                return true;
            }
        }
        false
    }

    /// Plan D-9: the config chosen at CONNECT is the one the handshake uses. A pattern leaf
    /// evicted from the LRU while the ClientHello is still awaited does not close the CONNECT.
    #[test]
    fn a_connect_config_survives_its_eviction_from_the_lru() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dir = tmp.path().join("ca");
        let ic = pattern_interceptor(&dir);
        let held = ic.connect_config("us-east-1.pat.test").expect("minted");
        // Evicted before the handshake runs.
        ic.pattern_leaves
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .retain(|_| false);
        assert!(ic.pinned_config("us-east-1.pat.test").is_none());
        assert!(handshakes(held, &dir, "us-east-1.pat.test"));
        // An exact host's CONNECT config is its pinned config.
        assert!(handshakes(
            ic.connect_config("a.test").expect("exact"),
            &dir,
            "a.test"
        ));
    }

    /// A CA within its last thirty days: the pattern leaf minted at CONNECT is clipped to the
    /// CA's expiry, and the cache keeps serving it instead of dropping it the moment it lands.
    #[test]
    fn a_pattern_leaf_under_a_near_expiry_ca_is_served_and_handshakes() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dir = tmp.path().join("ca");
        let now = OffsetDateTime::now_utc();
        LocalCa::generate_with_validity(&dir, now - BACKDATE, now + Duration::days(10))
            .expect("a CA ten days from expiry");
        let ic = pattern_interceptor(&dir);
        let config = ic.connect_config("x.pat.test").expect("minted");
        assert!(
            ic.pinned_config("x.pat.test").is_some(),
            "the clipped leaf stays cached"
        );
        assert!(ic.ensure_leaf("x.pat.test"));
        assert_eq!(ic.pattern_mint_capped(), 0);
        assert!(handshakes(config, &dir, "x.pat.test"));
    }

    /// Withdrawing a pattern drops its cached leaves and its declaration together.
    #[test]
    fn set_patterns_withdraws_cached_leaves() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let ic = pattern_interceptor(&tmp.path().join("ca"));
        assert!(ic.ensure_leaf("x.pat.test"));
        ic.set_patterns([]);
        assert!(!ic.intercepts("x.pat.test"));
        assert!(ic.pinned_config("x.pat.test").is_none());
        assert!(!ic.ensure_leaf("x.pat.test"));
        assert!(ic.intercepts("a.test"), "exact hosts are untouched");
    }

    /// A pattern host's pinned config completes a real handshake for its own SNI and refuses any
    /// other — the same allow-list as an exact host's.
    #[tokio::test]
    async fn a_pattern_leaf_serves_its_own_host_only() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let ic = pattern_interceptor(&tmp.path().join("ca"));
        let ca_pem = std::fs::read_to_string(ic.ca().pem_path()).expect("read ca.pem");
        let ca_der = CertificateDer::from_pem_slice(ca_pem.as_bytes()).expect("parse ca pem");
        assert!(ic.ensure_leaf("eu-west-1.pat.test"));
        let config = ic.pinned_config("eu-west-1.pat.test").expect("minted");

        let (server_ok, client_ok) =
            one_handshake(config.clone(), &ca_der, "eu-west-1.pat.test").await;
        server_ok.expect("server accepts its own SNI");
        client_ok.expect("client trusts the pattern leaf");

        let (server_err, client_err) = one_handshake(config, &ca_der, "us-east-1.pat.test").await;
        server_err.expect_err("a sibling pattern host is a different leaf");
        client_err.expect_err("client sees the refusal");
    }
}