courierust 1.0.8

A zero-dependency, self-contained HTTP/1.1 + HTTP/2 + HTTP/3 (QUIC) + WebSocket + gRPC stack with a from-scratch TLS 1.2/1.3, a work-stealing scheduler, RFC 9218 priority and JA3/JA4 fingerprints.
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
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
//! TLS 1.3 (RFC 8446), implemented from scratch with zero dependencies.
//!
//! This module provides a complete client and server handshake over the
//! crate's [`crate::courierust_io::Read`]/[`crate::courierust_io::Write`] transport traits, so
//! it works over TCP, and integrates with the HTTP/1.1 / HTTP/2 /
//! gRPC codecs to make **HTTPS** a first-class capability.
//!
//! Supported cryptographic profile (the modern TLS 1.3 baseline):
//!
//! * Cipher suites: `TLS_CHACHA20_POLY1305_SHA256`, `TLS_AES_128_GCM_SHA256`,
//!   `TLS_AES_256_GCM_SHA384`.
//! * Key exchange: X25519.
//! * Certificate signature verification: RSA-PSS / RSA PKCS#1 v1.5,
//!   ECDSA P-256, Ed25519 (SHA-256 / SHA-384 digests).
//! * X.509 chain validation with a pluggable root store (no bundled
//!   root certificates — supply your own roots via [`RootStore`]).
//!
//! Honest scope note: 0-RTT / early data are not offered (replay
//! protection is deliberately not taken on); the record-layer TLS 1.3
//! KeyUpdate message is not sent (QUIC key updates are handled at the
//! transport layer via the key-phase bit). TLS 1.3 session resumption is
//! implemented — server-issued session tickets, 1-RTT PSK via
//! psk_dhe_ke, client-side session store — and a full handshake is
//! performed when no usable ticket is cached.
//! The certificate verification performs chain building against the
//! provided roots, validity-window and hostname checks, and standard
//! key-usage/basic-constraints enforcement.

pub mod crypto;
pub(crate) mod session;
pub mod system_roots;
pub mod x509;

#[cfg(test)]
pub(crate) mod testdata;

mod client_auth;
mod handshake;
mod identity;
mod key_schedule;
mod pem;
pub(crate) mod quic;
mod record;
mod tls12;

pub use client_auth::ClientAuth;
pub use identity::Identity;

use alloc::string::String;
use alloc::vec::Vec;

pub use x509::RootStore;

/// The TLS protocol version negotiated for a connection.
///
/// The crate speaks TLS 1.2 (RFC 5246, AEAD ECDHE suites only) and
/// TLS 1.3 (RFC 8446). Version selection is explicit and bounded by the
/// `min_version` / `max_version` fields on the client and server
/// configurations; the RFC 8446 §4.1.3 downgrade sentinel is enforced
/// on every path that could otherwise degrade silently.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum TlsVersion {
    /// TLS 1.2 (legacy records, AEAD ECDHE suites).
    Tls12,
    /// TLS 1.3 (RFC 8446).
    Tls13,
}

/// TLS version identifier for TLS 1.3 (supported_versions extension).
pub const TLS_VERSION_1_3: u16 = 0x0304;
/// TLS version identifier for TLS 1.2 (legacy_record_version / fallback).
pub const TLS_VERSION_1_2: u16 = 0x0303;

/// Upper bound on accumulated decrypted handshake bytes. The protocol's
/// handshake length field is 24 bits (~16 MiB max), so a peer streaming
/// handshake records without completing a message is hostile — without
/// this cap the receive buffer would grow without bound (memory DoS).
const MAX_HANDSHAKE_BUFFER: usize = 16 * 1024 * 1024;

/// A parsed `ClientHello` summary (used by server-side ALPN/SNI and by
/// the fingerprint layer).
#[derive(Debug, Clone, Default)]
pub struct ClientHelloInfo {
    /// Server Name Indication (if any).
    pub server_name: Option<String>,
    /// Application-Layer Protocol Negotiation list (raw).
    pub alpn: Vec<Vec<u8>>,
    /// Negotiated ALPN protocol (set after the server chooses).
    pub negotiated_alpn: Option<Vec<u8>>,
    /// Supported cipher suites offered by the client (wire values).
    pub cipher_suites: Vec<u16>,
}

/// Errors that can occur during a TLS handshake or record operation.
#[derive(Debug, Clone)]
pub enum TlsError {
    /// Underlying transport error.
    Io(String),
    /// The peer sent a malformed or protocol-violating message.
    Protocol(String),
    /// The peer sent an alert.
    Alert {
        /// Alert severity level (1 = warning, 2 = fatal).
        level: u8,
        /// Alert description (RFC 8446 §6).
        description: u8,
    },
    /// The certificate chain failed validation.
    Certificate(String),
    /// The handshake did not complete in time.
    Timeout,
    /// The peer aborted the connection.
    UnexpectedEof,
    /// Unsupported feature requested by the peer.
    Unsupported(String),
    /// Internal error (should not happen).
    Internal(String),
}

impl core::fmt::Display for TlsError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            TlsError::Io(m) => write!(f, "TLS I/O error: {m}"),
            TlsError::Protocol(m) => write!(f, "TLS protocol error: {m}"),
            TlsError::Alert { level, description } => {
                write!(f, "TLS alert level={level} description={description}")
            }
            TlsError::Certificate(m) => write!(f, "TLS certificate error: {m}"),
            TlsError::Timeout => write!(f, "TLS handshake timeout"),
            TlsError::UnexpectedEof => write!(f, "TLS unexpected EOF"),
            TlsError::Unsupported(m) => write!(f, "TLS unsupported: {m}"),
            TlsError::Internal(m) => write!(f, "TLS internal error: {m}"),
        }
    }
}

impl From<crate::courierust_error::Error> for TlsError {
    fn from(e: crate::courierust_error::Error) -> Self {
        use crate::courierust_error::ErrorKind;
        match e.kind {
            ErrorKind::Timeout => TlsError::Timeout,
            ErrorKind::UnexpectedEof => TlsError::UnexpectedEof,
            _ => TlsError::Io(e.to_string()),
        }
    }
}

/// The other direction, so a caller that speaks the crate's error type —
/// a `main` that loads an identity, an embedder wiring TLS into its own
/// startup path — can use `?` on TLS setup instead of restating the
/// message. The kinds that exist on both sides are carried over
/// unchanged; the rest keeps its message.
impl From<TlsError> for crate::courierust_error::Error {
    fn from(e: TlsError) -> Self {
        use crate::courierust_error::{Error, ErrorKind};
        match e {
            TlsError::Io(message) => Error::io(message),
            TlsError::Protocol(message) => Error::protocol(message),
            TlsError::Timeout => Error::new(ErrorKind::Timeout),
            TlsError::UnexpectedEof => Error::new(ErrorKind::UnexpectedEof),
            other => Error::with_message(ErrorKind::Other, alloc::format!("{other}")),
        }
    }
}

/// A result alias for TLS operations.
pub type TlsResult<T> = core::result::Result<T, TlsError>;

// `Identity` lives in its own module: it is the one type here whose
// construction needs validation (certificate parsing, key parsing and a
// key/certificate match check), and that check owns the module.

// ---------------------------------------------------------------------
// Record-level transport (TlsIo)
// ---------------------------------------------------------------------

use crate::courierust_io::{BufReader, BufWriter};
use record::{open_record, seal_record, Sequence, CONTENT_HANDSHAKE, MAX_RECORD_PAYLOAD};

/// Buffered record-level I/O over a transport. Sequence numbers are
/// tracked per direction and reset when the traffic keys change.
pub(crate) struct TlsIo<R, W> {
    reader: BufReader<R>,
    writer: BufWriter<W>,
    read_seq: Sequence,
    write_seq: Sequence,
}

impl<R: crate::courierust_io::Read, W: crate::courierust_io::Write> TlsIo<R, W> {
    pub(crate) fn new(reader: R, writer: W) -> Self {
        Self {
            reader: BufReader::new(reader, 65536),
            writer: BufWriter::new(writer, 65536),
            read_seq: Sequence::default(),
            write_seq: Sequence::default(),
        }
    }

    /// Write an unencrypted record (ClientHello / ServerHello / alerts).
    pub(crate) fn write_plaintext_record(
        &mut self,
        content_type: u8,
        payload: &[u8],
    ) -> TlsResult<()> {
        self.write_plaintext_record_v([0x03, 0x01], content_type, payload)
    }

    /// Write an unencrypted record with an explicit record-layer version
    /// (TLS 1.2 uses 0x0303 for its records; the TLS 1.3 client hello
    /// conventionally uses the legacy 0x0301).
    pub(crate) fn write_plaintext_record_v(
        &mut self,
        version: [u8; 2],
        content_type: u8,
        payload: &[u8],
    ) -> TlsResult<()> {
        if payload.len() > u16::MAX as usize {
            return Err(TlsError::Protocol("record too large".into()));
        }
        let header = [
            content_type,
            version[0],
            version[1],
            (payload.len() >> 8) as u8,
            payload.len() as u8,
        ];
        self.writer.write_all(&header).map_err(TlsError::from)?;
        self.writer.write_all(payload).map_err(TlsError::from)?;
        self.writer.flush().map_err(TlsError::from)
    }

    /// Write one TLS 1.2 AEAD record (RFC 5246 §6.2.3.3).
    pub(crate) fn write_tls12_record(
        &mut self,
        suite: tls12::Tls12Suite,
        keys: &key_schedule::TrafficKeys,
        content_type: u8,
        payload: &[u8],
    ) -> TlsResult<()> {
        let seq = self.write_seq.next()?;
        let rec = tls12::seal_record(suite, keys, seq, content_type, payload)?;
        self.writer.write_all(&rec).map_err(TlsError::from)?;
        self.writer.flush().map_err(TlsError::from)
    }

    /// Write one TLS 1.2 AEAD record into the internal buffer *without*
    /// flushing (bulk application data).
    pub(crate) fn write_tls12_record_buffered(
        &mut self,
        suite: tls12::Tls12Suite,
        keys: &key_schedule::TrafficKeys,
        content_type: u8,
        payload: &[u8],
    ) -> TlsResult<()> {
        let seq = self.write_seq.next()?;
        let rec = tls12::seal_record(suite, keys, seq, content_type, payload)?;
        self.writer.write_all(&rec).map_err(TlsError::from)
    }

    /// Read one TLS 1.2 record: decrypts AEAD records and returns the
    /// real content type and plaintext; a `change_cipher_spec` record is
    /// returned as-is (it is not protected and does not consume a
    /// sequence number).
    pub(crate) fn read_tls12_record(
        &mut self,
        suite: tls12::Tls12Suite,
        keys: &key_schedule::TrafficKeys,
    ) -> TlsResult<(u8, Vec<u8>)> {
        let mut header = [0u8; 5];
        self.reader
            .read_exact_into(&mut header)
            .map_err(TlsError::from)?;
        let len = ((header[3] as usize) << 8) | header[4] as usize;
        if len > record::MAX_RECORD_PAYLOAD + 8 + 16 {
            return Err(TlsError::Protocol("record too large".into()));
        }
        let body = self.reader.read_exact(len).map_err(TlsError::from)?;
        if header[0] == record::CONTENT_CHANGE_CIPHER_SPEC {
            if len != 1 || body.first() != Some(&1) {
                return Err(TlsError::Protocol("malformed ChangeCipherSpec".into()));
            }
            return Ok((record::CONTENT_CHANGE_CIPHER_SPEC, body));
        }
        let seq = self.read_seq.next()?;
        tls12::open_record(suite, keys, seq, &header, &body)
    }

    /// Read one unencrypted record and return (type, payload).
    pub(crate) fn read_plaintext_record(&mut self) -> TlsResult<(u8, Vec<u8>)> {
        let mut header = [0u8; 5];
        self.reader
            .read_exact_into(&mut header)
            .map_err(TlsError::from)?;
        let content_type = header[0];
        let len = ((header[3] as usize) << 8) | header[4] as usize;
        if len > MAX_RECORD_PAYLOAD {
            return Err(TlsError::Protocol("record too large".into()));
        }
        let payload = self.reader.read_exact(len).map_err(TlsError::from)?;
        Ok((content_type, payload))
    }

    /// Read one plaintext handshake record; returns the handshake body
    /// (after the 4-byte handshake header).
    pub(crate) fn read_plaintext_handshake(&mut self) -> TlsResult<(u8, Vec<u8>)> {
        let (ct, payload) = self.read_plaintext_record()?;
        if ct != CONTENT_HANDSHAKE {
            return Err(TlsError::Protocol("expected handshake record".into()));
        }
        if payload.len() < 4 {
            return Err(TlsError::Protocol("bad handshake record".into()));
        }
        Ok((payload[0], payload[4..].to_vec()))
    }

    /// Write an encrypted record and flush it to the transport. Used for
    /// handshake flights and alerts, where the peer is waiting on the
    /// bytes before it can continue.
    pub(crate) fn write_encrypted_record(
        &mut self,
        suite: key_schedule::CipherSuite,
        keys: &key_schedule::TrafficKeys,
        content_type: u8,
        payload: &[u8],
    ) -> TlsResult<()> {
        let seq = self.write_seq.next()?;
        let rec = seal_record(suite, keys, seq, content_type, payload)?;
        self.writer.write_all(&rec).map_err(TlsError::from)?;
        self.writer.flush().map_err(TlsError::from)
    }

    /// Write an encrypted record into the internal buffer *without*
    /// flushing. Bulk application data uses this and flushes once per
    /// batch ([`crate::courierust_tls::TlsStream::write_all`]) so a large
    /// body costs one syscall per buffer-full instead of one per
    /// ~16 KiB record.
    pub(crate) fn write_encrypted_record_buffered(
        &mut self,
        suite: key_schedule::CipherSuite,
        keys: &key_schedule::TrafficKeys,
        content_type: u8,
        payload: &[u8],
    ) -> TlsResult<()> {
        let seq = self.write_seq.next()?;
        let rec = seal_record(suite, keys, seq, content_type, payload)?;
        self.writer.write_all(&rec).map_err(TlsError::from)
    }

    pub(crate) fn read_encrypted_handshake(
        &mut self,
        suite: key_schedule::CipherSuite,
        keys: &key_schedule::TrafficKeys,
    ) -> TlsResult<Vec<u8>> {
        let mut plain = Vec::new();
        loop {
            let mut header = [0u8; 5];
            self.reader
                .read_exact_into(&mut header)
                .map_err(TlsError::from)?;
            let len = ((header[3] as usize) << 8) | header[4] as usize;
            if len > MAX_RECORD_PAYLOAD + 16 {
                return Err(TlsError::Protocol("record too large".into()));
            }
            let encrypted = self.reader.read_exact(len).map_err(TlsError::from)?;
            if header[0] == record::CONTENT_CHANGE_CIPHER_SPEC {
                if len != 1 || encrypted.first() != Some(&1) {
                    return Err(TlsError::Protocol("malformed ChangeCipherSpec".into()));
                }
                continue;
            }
            let seq = self.read_seq.next()?;
            let (ct, payload) = open_record(suite, keys, seq, &header, &encrypted)?;
            if ct == CONTENT_HANDSHAKE {
                if plain.len() > MAX_HANDSHAKE_BUFFER - payload.len() {
                    return Err(TlsError::Protocol(
                        "handshake message exceeds the 16 MiB protocol maximum".into(),
                    ));
                }
                plain.extend_from_slice(&payload);
                // A peer may fragment its flight across many records; only
                // stop once the whole flight (ending in Finished) is
                // buffered.
                if handshake::has_complete_finished(&plain) {
                    return Ok(plain);
                }
            }
        }
    }

    /// Switch to a fresh set of keys (resets sequence numbers).
    pub(crate) fn reset_sequences(&mut self) {
        self.read_seq = Sequence::default();
        self.write_seq = Sequence::default();
    }
}

// ---------------------------------------------------------------------
// Public TLS stream
// ---------------------------------------------------------------------

/// State of an in-progress inbound TLS record read. The transport read
/// timeout is a *wake-up* mechanism (the h2 driver polls with a short
/// socket timeout), so a record may be interrupted mid-header or
/// mid-payload. This state lets `read_record` resume exactly where it
/// stopped instead of treating a transient timeout as fatal (which would
/// otherwise kill TLS connections under load).
enum RecState {
    /// No partial record in flight.
    Idle,
    /// Reading the 5-byte record header.
    Header { hdr: [u8; 5], filled: usize },
    /// Header complete; reading the (encrypted) payload.
    Payload {
        header: [u8; 5],
        payload: Vec<u8>,
        filled: usize,
    },
}

/// RFC 8446 §5.5: how many records one key may protect before a
/// `KeyUpdate` is owed. AES-GCM is bounded by the AEAD analysis (2^24.5;
/// this implementation rekeys at 2^24, before the limit), while
/// ChaCha20-Poly1305 is bounded only by the sequence number, which §5.3
/// forbids wrapping.
fn key_use_limit(suite: key_schedule::CipherSuite) -> u64 {
    match suite {
        key_schedule::CipherSuite::TlsChaCha20Poly1305Sha256 => u64::MAX,
        _ => 1 << 24,
    }
}

/// A completed TLS 1.2 / 1.3 connection. Implements the crate's `Read`
/// and `Write` traits for encrypted application data. The record layer
/// branches on [`TlsVersion`]: TLS 1.3 uses the inner content-type
/// layout (RFC 8446 §5.2), TLS 1.2 the legacy AEAD layout (RFC 5246
/// §6.2.3.3) with real content types on the wire.
pub struct TlsStream<R, W> {
    io: TlsIo<R, W>,
    /// The negotiated protocol version.
    version: TlsVersion,
    /// The negotiated TLS 1.3 suite (meaningful when `version` is
    /// [`TlsVersion::Tls13`]).
    suite: key_schedule::CipherSuite,
    /// The negotiated TLS 1.2 suite (meaningful when `version` is
    /// [`TlsVersion::Tls12`]).
    suite12: Option<tls12::Tls12Suite>,
    write_keys: key_schedule::TrafficKeys,
    read_keys: key_schedule::TrafficKeys,
    negotiated_alpn: Option<Vec<u8>>,
    server_name: Option<String>,
    peer_certificate: Option<Vec<u8>>,
    closed: bool,
    /// A decrypted record awaiting delivery to the caller.
    pending: Vec<u8>,
    /// Read offset into `pending`. Keeping a cursor instead of draining
    /// the front of the Vec avoids an O(n²) memmove when a caller reads
    /// a large record in small chunks.
    pending_pos: usize,
    /// Resumable inbound record read (see [`RecState`]).
    rec: RecState,
    /// Client side: the resumption master secret (with the negotiated
    /// suite) used to derive per-ticket PSKs (RFC 8446 §7.1).
    resumption_master: Option<(Vec<u8>, key_schedule::CipherSuite)>,
    /// True when this handshake was resumed from a PSK.
    resumed: bool,
    /// Shared resumption-session cache (set by the connector): tickets
    /// captured lazily while reading are stored here for future connects.
    session_store: Option<std::sync::Arc<std::sync::Mutex<Vec<session::ClientSession>>>>,
    /// The server name this connection authenticated (used when storing
    /// resumption sessions).
    hostname: String,
    /// Current Unix time (stamps issued sessions).
    now: i64,
    /// TLS 1.3 application traffic secrets (write/read). A `KeyUpdate`
    /// derives the next generation from these (RFC 8446 §7.2); `None` on
    /// TLS 1.2, which has no key update.
    write_app_secret: Option<Vec<u8>>,
    read_app_secret: Option<Vec<u8>>,
    /// A `KeyUpdate` is owed to the peer (it asked, RFC 8446 §4.6.3) and
    /// must be sent before the next application record.
    pending_key_update: bool,
    /// Records written under the current write key, against
    /// [`Self::key_use_limit`] (RFC 8446 §5.5).
    write_records: u64,
    key_use_limit: u64,
    /// Key generations in use per direction (RFC 8446 §7.2).
    key_read_gen: u64,
    key_write_gen: u64,
}

impl<R: crate::courierust_io::Read, W: crate::courierust_io::Write> TlsStream<R, W> {
    /// The negotiated ALPN protocol, if any.
    pub fn alpn(&self) -> Option<&[u8]> {
        self.negotiated_alpn.as_deref()
    }

    /// Key generations in use, `(read, write)`. Each counts the updates
    /// applied to that direction since the handshake (RFC 8446 §7.2).
    pub fn key_generations(&self) -> (u64, u64) {
        (self.key_read_gen, self.key_write_gen)
    }

    /// Ask the peer to rekey (RFC 8446 §4.6.3): sends a `KeyUpdate` with
    /// `update_requested`, switches this side's write direction to the
    /// next generation, and flushes. The peer answers with its own
    /// update, so the read direction follows on the next record.
    pub fn request_key_update(&mut self) -> TlsResult<()> {
        if self.version != TlsVersion::Tls13 {
            return Err(TlsError::Protocol("KeyUpdate requires TLS 1.3".into()));
        }
        if self.closed {
            return Err(TlsError::Protocol("connection closed".into()));
        }
        self.send_key_update(true)?;
        self.io.writer.flush().map_err(TlsError::from)
    }

    /// Send a `KeyUpdate` under the current write key, then adopt the next
    /// generation for writing (RFC 8446 §4.6.3/§7.2).
    fn send_key_update(&mut self, request: bool) -> TlsResult<()> {
        let Some(secret) = self.write_app_secret.clone() else {
            return Err(TlsError::Protocol(
                "KeyUpdate without application keys".into(),
            ));
        };
        let msg = [handshake::HS_KEY_UPDATE, 0, 0, 1, u8::from(request)];
        self.io.write_encrypted_record_buffered(
            self.suite,
            &self.write_keys,
            record::CONTENT_HANDSHAKE,
            &msg,
        )?;
        let next = key_schedule::update_traffic_secret(self.suite.hash(), &secret);
        self.write_keys = key_schedule::TrafficKeys::from_secret(self.suite, &next);
        self.write_app_secret = Some(next);
        self.io.write_seq = Sequence::default();
        self.write_records = 0;
        self.key_write_gen += 1;
        Ok(())
    }

    /// The peer rekeyed its send direction: adopt the next generation for
    /// reading, and owe it an update of our own when one was requested.
    fn apply_key_update(&mut self, body: &[u8]) -> TlsResult<()> {
        let request = match body {
            [0] => false,
            [1] => true,
            // RFC 8446 §4.6.3: any other value is illegal_parameter.
            _ => {
                return Err(TlsError::Alert {
                    level: 2,
                    description: 47,
                })
            }
        };
        let Some(secret) = self.read_app_secret.clone() else {
            return Err(TlsError::Protocol(
                "KeyUpdate without application keys".into(),
            ));
        };
        let next = key_schedule::update_traffic_secret(self.suite.hash(), &secret);
        self.read_keys = key_schedule::TrafficKeys::from_secret(self.suite, &next);
        self.read_app_secret = Some(next);
        self.io.read_seq = Sequence::default();
        self.key_read_gen += 1;
        if request {
            // "MUST send a KeyUpdate of its own ... prior to sending its
            // next Application Data record."
            self.pending_key_update = true;
        }
        Ok(())
    }

    /// Test hook: shrink the per-key record budget so a proactive update
    /// can be observed without sending 2^24 records.
    #[cfg(test)]
    pub(crate) fn set_key_use_limit(&mut self, limit: u64) {
        self.key_use_limit = limit;
    }

    /// The underlying reader transport (used to reconfigure socket
    /// timeouts after the handshake).
    pub(crate) fn underlying(&self) -> &R {
        self.io.reader.get_ref()
    }

    /// The server name (SNI) used for this connection.
    pub fn server_name(&self) -> Option<&str> {
        self.server_name.as_deref()
    }

    /// The peer's leaf certificate (DER), if the peer authenticated.
    pub fn peer_certificate(&self) -> Option<&[u8]> {
        self.peer_certificate.as_deref()
    }

    /// The negotiated TLS version.
    pub fn version(&self) -> TlsVersion {
        self.version
    }

    /// The negotiated cipher suite wire value.
    pub fn cipher_suite(&self) -> u16 {
        match self.version {
            TlsVersion::Tls13 => self.suite.wire(),
            TlsVersion::Tls12 => self.suite12.map(|s| s.wire()).unwrap_or(0),
        }
    }

    /// Write application data (encrypted).
    pub fn write_all(&mut self, data: &[u8]) -> TlsResult<()> {
        if self.closed {
            return Err(TlsError::Protocol("connection closed".into()));
        }
        if self.version == TlsVersion::Tls13 {
            // An answer owed to the peer goes out before the next
            // application record (§4.6.3), and a key that has spent its
            // record budget is replaced before it exceeds it (§5.5).
            if self.pending_key_update {
                self.pending_key_update = false;
                self.send_key_update(false)?;
            } else if self.write_records >= self.key_use_limit {
                self.send_key_update(false)?;
            }
        }
        let mut off = 0;
        while off < data.len() {
            let take = core::cmp::min(data.len() - off, record::MAX_RECORD_PAYLOAD - 2);
            match self.version {
                TlsVersion::Tls13 => self.io.write_encrypted_record_buffered(
                    self.suite,
                    &self.write_keys,
                    record::CONTENT_APPLICATION_DATA,
                    &data[off..off + take],
                )?,
                TlsVersion::Tls12 => {
                    let suite12 = self
                        .suite12
                        .ok_or_else(|| TlsError::Internal("missing TLS 1.2 suite".into()))?;
                    self.io.write_tls12_record_buffered(
                        suite12,
                        &self.write_keys,
                        record::CONTENT_APPLICATION_DATA,
                        &data[off..off + take],
                    )?
                }
            }
            self.write_records = self.write_records.saturating_add(1);
            off += take;
        }
        self.io.writer.flush().map_err(TlsError::from)?;
        Ok(())
    }

    /// Read one application-data record (up to one TLS record of data).
    /// Returns Ok(0) on clean shutdown. Any `NewSessionTicket` messages
    /// carried in post-handshake records are captured first.
    pub fn read_record(&mut self) -> TlsResult<Vec<u8>> {
        if self.closed {
            return Ok(Vec::new());
        }
        // A previously stashed record (set by callers that pre-read) is
        // delivered before reading more from the transport.
        if self.pending_pos < self.pending.len() {
            let out = self.pending[self.pending_pos..].to_vec();
            self.pending_pos = self.pending.len();
            return Ok(out);
        }
        loop {
            match self.version {
                TlsVersion::Tls13 => match self.read_one_tls13_record()? {
                    None => return Ok(Vec::new()), // clean EOF
                    Some((ct, payload)) => match ct {
                        record::CONTENT_APPLICATION_DATA => return Ok(payload),
                        record::CONTENT_ALERT => {
                            if payload.first() == Some(&1) && payload.get(1) == Some(&0) {
                                self.closed = true;
                                return Ok(Vec::new());
                            }
                            return Err(TlsError::Alert {
                                level: payload.first().copied().unwrap_or(2),
                                description: payload.get(1).copied().unwrap_or(0),
                            });
                        }
                        record::CONTENT_HANDSHAKE => {
                            // A post-handshake record may carry several
                            // messages, so every one is processed
                            // (RFC 8446 §5.1).
                            let mut rest = &payload[..];
                            while let Some(m) = handshake::peek_complete_hs(rest) {
                                match m.msg_type {
                                    handshake::HS_NEW_SESSION_TICKET => {
                                        self.capture_ticket(rest)?;
                                    }
                                    handshake::HS_KEY_UPDATE => {
                                        self.apply_key_update(m.body)?;
                                    }
                                    _ => {
                                        return Err(TlsError::Protocol(
                                            "unexpected handshake after handshake".into(),
                                        ))
                                    }
                                }
                                rest = &rest[4 + m.body.len()..];
                            }
                        }
                        record::CONTENT_CHANGE_CIPHER_SPEC => continue,
                        _ => {
                            return Err(TlsError::Protocol("unexpected record type".into()));
                        }
                    },
                },
                TlsVersion::Tls12 => {
                    let payload_len = match &self.rec {
                        RecState::Payload { payload, .. } => payload.len(),
                        _ => match self.read_record_header()? {
                            Some((_, len)) => len,
                            None => return Ok(Vec::new()),
                        },
                    };
                    if payload_len > record::MAX_RECORD_PAYLOAD + 8 + 16 {
                        return Err(TlsError::Protocol("record too large".into()));
                    }
                    let (header, encrypted) = self.read_record_payload()?;
                    if header[0] == record::CONTENT_CHANGE_CIPHER_SPEC {
                        if encrypted.len() != 1 || encrypted[0] != 1 {
                            return Err(TlsError::Protocol("malformed ChangeCipherSpec".into()));
                        }
                        continue;
                    }
                    let suite12 = self
                        .suite12
                        .ok_or_else(|| TlsError::Internal("missing TLS 1.2 suite".into()))?;
                    let seq = self.io.read_seq.next()?;
                    let (ct, payload) =
                        tls12::open_record(suite12, &self.read_keys, seq, &header, &encrypted)?;
                    match ct {
                        record::CONTENT_APPLICATION_DATA => return Ok(payload),
                        record::CONTENT_ALERT => {
                            if payload.first() == Some(&1) && payload.get(1) == Some(&0) {
                                self.closed = true;
                                return Ok(Vec::new());
                            }
                            return Err(TlsError::Alert {
                                level: payload.first().copied().unwrap_or(2),
                                description: payload.get(1).copied().unwrap_or(0),
                            });
                        }
                        record::CONTENT_HANDSHAKE => {
                            return Err(TlsError::Protocol(
                                "unexpected handshake after handshake".into(),
                            ));
                        }
                        _ => {
                            return Err(TlsError::Protocol("unexpected record type".into()));
                        }
                    }
                }
            }
        }
    }

    /// Read and open one TLS 1.3 record (resuming a partial header/payload
    /// across a timed-out read). `Ok(None)` is a clean EOF; a read
    /// timeout surfaces as [`TlsError::Timeout`] with the read state
    /// preserved so a later read resumes.
    fn read_one_tls13_record(&mut self) -> TlsResult<Option<(u8, Vec<u8>)>> {
        loop {
            let payload_len = match &self.rec {
                RecState::Payload { payload, .. } => payload.len(),
                _ => match self.read_record_header()? {
                    Some((_, len)) => len,
                    None => return Ok(None),
                },
            };
            if payload_len > record::MAX_RECORD_PAYLOAD + 8 + 16 {
                return Err(TlsError::Protocol("record too large".into()));
            }
            let (header, encrypted) = self.read_record_payload()?;
            if header[0] == record::CONTENT_CHANGE_CIPHER_SPEC {
                if encrypted.len() != 1 || encrypted[0] != 1 {
                    return Err(TlsError::Protocol("malformed ChangeCipherSpec".into()));
                }
                continue;
            }
            if header[0] != record::CONTENT_APPLICATION_DATA {
                return Err(TlsError::Protocol("unexpected record type".into()));
            }
            let seq = self.io.read_seq.next()?;
            let (ct, payload) =
                record::open_record(self.suite, &self.read_keys, seq, &header, &encrypted)?;
            return Ok(Some((ct, payload)));
        }
    }

    /// Parse every `NewSessionTicket` in a post-handshake handshake
    /// record and derive its resumption PSK from the resumption master
    /// secret (RFC 8446 §7.1). The session is cached for future connects
    /// (lazy capture — this runs as tickets are read off the connection).
    fn capture_ticket(&mut self, payload: &[u8]) -> TlsResult<()> {
        let Some((res_master, suite)) = self.resumption_master.clone() else {
            return Ok(()); // no resumption on this connection
        };
        let mut rest = payload;
        while !rest.is_empty() {
            let Some(m) = handshake::peek_complete_hs(rest) else {
                break;
            };
            if m.msg_type == handshake::HS_NEW_SESSION_TICKET {
                if let Ok(ticket) = session::parse_new_session_ticket(m.body) {
                    let psk = session::derive_psk(suite, &res_master, &ticket.nonce);
                    let sess = session::ClientSession {
                        hostname: self.hostname.clone(),
                        ticket: ticket.ticket,
                        psk,
                        suite,
                        issued_at: self.now,
                        // Honor the server's lifetime, capped at 7 days.
                        lifetime: (ticket.lifetime as i64).min(session::SESSION_LIFETIME_SECS),
                        // 0-RTT allowance the ticket carries (0 = none).
                    };
                    if let Some(store) = &self.session_store {
                        cache_session(&mut crate::lock(store), sess);
                    }
                }
            }
            rest = &rest[4 + m.body.len()..];
        }
        Ok(())
    }

    /// Whether this handshake was resumed from a PSK.
    /// Whether this connection was resumed via a PSK (RFC 8446 §2.2).
    /// The first connection after a ticket is issued is a full handshake;
    /// a later connection offering that ticket is resumed.
    pub fn resumed(&self) -> bool {
        self.resumed
    }

    /// Ensure a complete 5-byte record header is buffered, resuming from
    /// a partial header left by a previous (timed-out) read. `Ok(None)`
    /// means the peer closed cleanly. On success the internal state
    /// transitions to [`RecState::Payload`] so the next phase knows the
    /// expected payload length.
    fn read_record_header(&mut self) -> TlsResult<Option<([u8; 5], usize)>> {
        let (mut hdr, mut filled) = match &self.rec {
            RecState::Header { hdr, filled } => (*hdr, *filled),
            _ => ([0u8; 5], 0),
        };
        loop {
            if filled == 5 {
                let payload_len = ((hdr[3] as usize) << 8) | hdr[4] as usize;
                self.rec = RecState::Payload {
                    header: hdr,
                    payload: vec![0u8; payload_len],
                    filled: 0,
                };
                return Ok(Some((hdr, payload_len)));
            }
            match self.io.reader.fill_buf() {
                Ok([]) => {
                    self.closed = true;
                    return Ok(None);
                }
                Ok(b) => {
                    let take = core::cmp::min(5 - filled, b.len());
                    hdr[filled..filled + take].copy_from_slice(&b[..take]);
                    self.io.reader.consume(take);
                    filled += take;
                }
                Err(e)
                    if e.kind == crate::courierust_error::ErrorKind::Timeout
                        || e.kind == crate::courierust_error::ErrorKind::WouldBlock =>
                {
                    self.rec = RecState::Header { hdr, filled };
                    return Err(TlsError::Timeout);
                }
                Err(e) if e.kind == crate::courierust_error::ErrorKind::UnexpectedEof => {
                    self.closed = true;
                    return Ok(None);
                }
                Err(e) => return Err(TlsError::from(e)),
            }
        }
    }

    /// Ensure the full encrypted payload of the current record is
    /// buffered, resuming from a partial payload. The internal state is
    /// in [`RecState::Payload`] when this is called.
    fn read_record_payload(&mut self) -> TlsResult<([u8; 5], Vec<u8>)> {
        let (header, mut payload, mut filled) =
            match core::mem::replace(&mut self.rec, RecState::Idle) {
                RecState::Payload {
                    header,
                    payload,
                    filled,
                } => (header, payload, filled),
                _ => return Err(TlsError::Internal("payload read without header".into())),
            };
        let total = payload.len();
        loop {
            if filled == total {
                return Ok((header, payload));
            }
            match self.io.reader.fill_buf() {
                Ok([]) => {
                    self.closed = true;
                    return Err(TlsError::UnexpectedEof);
                }
                Ok(b) => {
                    let take = core::cmp::min(total - filled, b.len());
                    payload[filled..filled + take].copy_from_slice(&b[..take]);
                    self.io.reader.consume(take);
                    filled += take;
                }
                Err(e)
                    if e.kind == crate::courierust_error::ErrorKind::Timeout
                        || e.kind == crate::courierust_error::ErrorKind::WouldBlock =>
                {
                    self.rec = RecState::Payload {
                        header,
                        payload,
                        filled,
                    };
                    return Err(TlsError::Timeout);
                }
                Err(e) if e.kind == crate::courierust_error::ErrorKind::UnexpectedEof => {
                    self.closed = true;
                    return Err(TlsError::UnexpectedEof);
                }
                Err(e) => return Err(TlsError::from(e)),
            }
        }
    }

    /// Send a close_notify alert and flush.
    pub fn close_notify(&mut self) -> TlsResult<()> {
        if !self.closed {
            let alert = [1u8, 0u8]; // warning, close_notify
            match self.version {
                TlsVersion::Tls13 => self.io.write_encrypted_record(
                    self.suite,
                    &self.write_keys,
                    record::CONTENT_ALERT,
                    &alert,
                )?,
                TlsVersion::Tls12 => {
                    let suite12 = self
                        .suite12
                        .ok_or_else(|| TlsError::Internal("missing TLS 1.2 suite".into()))?;
                    self.io.write_tls12_record(
                        suite12,
                        &self.write_keys,
                        record::CONTENT_ALERT,
                        &alert,
                    )?
                }
            }
        }
        self.closed = true;
        Ok(())
    }
}

impl<R: crate::courierust_io::Read, W: crate::courierust_io::Write> crate::courierust_io::Read
    for TlsStream<R, W>
{
    fn read(&mut self, buf: &mut [u8]) -> crate::courierust_error::Result<usize> {
        if self.pending_pos >= self.pending.len() {
            self.pending = match self.read_record() {
                Ok(p) => p,
                Err(TlsError::Timeout) => {
                    return Err(crate::courierust_error::Error::new(
                        crate::courierust_error::ErrorKind::Timeout,
                    ))
                }
                Err(e) => {
                    return Err(crate::courierust_error::Error::with_message(
                        crate::courierust_error::ErrorKind::Other,
                        e.to_string(),
                    ))
                }
            };
            self.pending_pos = 0;
            if self.pending.is_empty() {
                return Ok(0);
            }
        }
        let avail = self.pending.len() - self.pending_pos;
        let n = core::cmp::min(buf.len(), avail);
        buf[..n].copy_from_slice(&self.pending[self.pending_pos..self.pending_pos + n]);
        self.pending_pos += n;
        Ok(n)
    }
}

impl<R: crate::courierust_io::Read, W: crate::courierust_io::Write> crate::courierust_io::Write
    for TlsStream<R, W>
{
    fn write(&mut self, buf: &[u8]) -> crate::courierust_error::Result<usize> {
        self.write_all(buf).map_err(|e| {
            crate::courierust_error::Error::with_message(
                crate::courierust_error::ErrorKind::Other,
                e.to_string(),
            )
        })?;
        Ok(buf.len())
    }

    fn flush(&mut self) -> crate::courierust_error::Result<()> {
        self.io.writer.flush().map_err(|e| {
            crate::courierust_error::Error::with_message(
                crate::courierust_error::ErrorKind::Other,
                e.to_string(),
            )
        })
    }
}

// ---------------------------------------------------------------------
// Client connector
// ---------------------------------------------------------------------

/// Client-side TLS configuration.
#[derive(Clone)]
pub struct ClientConfig {
    /// Trust anchors for server certificate validation.
    pub roots: RootStore,
    /// Whether to validate the server certificate (and hostname).
    pub verify: bool,
    /// ALPN protocols offered (raw wire values).
    pub alpn: Vec<Vec<u8>>,
    /// The current time (Unix seconds) used for validity checks.
    pub now: i64,
    /// The lowest TLS version the client will negotiate. Defaults to
    /// [`TlsVersion::Tls12`]; set to [`TlsVersion::Tls13`] to refuse
    /// TLS 1.2 outright.
    pub min_version: TlsVersion,
    /// The highest TLS version the client will negotiate. Defaults to
    /// [`TlsVersion::Tls13`].
    pub max_version: TlsVersion,
    /// The client certificate to present when a server asks for one
    /// (mTLS). `None` answers a `CertificateRequest` with an empty
    /// certificate list, which a server that requires authentication
    /// refuses — exactly what that policy is for.
    pub identity: Option<Identity>,
}

impl Default for ClientConfig {
    fn default() -> Self {
        Self {
            roots: RootStore::new(),
            verify: true,
            alpn: Vec::new(),
            now: 0,
            min_version: TlsVersion::Tls12,
            max_version: TlsVersion::Tls13,
            identity: None,
        }
    }
}

/// A TLS 1.2 / 1.3 client connector. Cloning shares the resumption-session
/// store (an `Arc`), so a per-request connector fork still resumes against
/// sessions captured on an earlier connection.
#[derive(Clone)]
pub struct TlsConnector {
    config: ClientConfig,
    /// Resumable sessions (NewSessionTickets), keyed by server name.
    /// Shared across connects on the same connector and populated lazily
    /// as tickets are read off connections.
    sessions: std::sync::Arc<std::sync::Mutex<Vec<session::ClientSession>>>,
}

impl TlsConnector {
    /// Create a connector from a configuration.
    pub fn new(config: ClientConfig) -> Self {
        Self {
            config,
            sessions: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
        }
    }

    /// The underlying configuration.
    pub fn config(&self) -> &ClientConfig {
        &self.config
    }

    /// Forget every cached resumption session.
    pub fn clear_sessions(&self) {
        crate::lock(&self.sessions).clear();
    }

    /// Number of cached resumption sessions (diagnostics / tests).
    pub fn session_count(&self) -> usize {
        crate::lock(&self.sessions).len()
    }

    /// Find a fresh resumption session for `hostname`.
    fn find_session(&self, hostname: &str) -> Option<session::ClientSession> {
        let sessions = crate::lock(&self.sessions);
        sessions
            .iter()
            .find(|s| s.hostname == hostname)
            .filter(|s| s.is_fresh(self.config.now))
            .cloned()
    }

    /// Perform a TLS handshake over `stream`, authenticating `hostname`
    /// against the server certificate. The negotiated version is chosen
    /// by the server within `min_version..=max_version`; a TLS 1.2
    /// response to a client that offered TLS 1.3 is accepted only with
    /// the RFC 8446 downgrade sentinel, and a TLS 1.3 response to a
    /// client that did not offer TLS 1.3 is rejected.
    pub fn connect<R: crate::courierust_io::Read, W: crate::courierust_io::Write>(
        &self,
        hostname: &str,
        reader: R,
        writer: W,
    ) -> TlsResult<TlsStream<R, W>> {
        let mut io = TlsIo::new(reader, writer);
        let allow13 = self.config.max_version >= TlsVersion::Tls13;
        let allow12 = self.config.min_version <= TlsVersion::Tls12;

        // Build and send a ClientHello covering the configured window. A
        // fresh resumption session (if any) is offered via psk_dhe_ke.
        let mut random = [0u8; 32];
        handshake::fill_entropy(&mut random)?;
        let mut priv13 = [0u8; 32];
        handshake::fill_entropy(&mut priv13)?;
        let pub13 = crypto::x25519::x25519(&priv13, &crypto::x25519::BASE_POINT);
        let resume_session = allow13.then(|| self.find_session(hostname)).flatten();
        let ch = match &resume_session {
            Some(s) => session::build_client_hello_with_psk(
                &random,
                &pub13,
                &self.config.alpn,
                Some(hostname),
                s.suite,
                &s.psk,
                &s.ticket,
            )?,
            None => handshake::build_client_hello_negotiated(
                &random,
                Some(&pub13),
                &self.config.alpn,
                Some(hostname),
                None,
                allow13,
                allow12,
            ),
        };
        io.write_plaintext_record_v(tls12::VERSION_12, record::CONTENT_HANDSHAKE, &ch)?;

        // Read the first plaintext record and dispatch on the negotiated
        // version. The full payload is kept: a TLS 1.2 peer may coalesce
        // the ServerHello with the rest of its flight in one record.
        let (ct, first_payload) = io.read_plaintext_record()?;
        if ct != record::CONTENT_HANDSHAKE {
            return Err(TlsError::Protocol("expected handshake record".into()));
        }
        if first_payload.len() < 4 {
            return Err(TlsError::Protocol("bad handshake record".into()));
        }
        let sh_body = &first_payload[4..];
        // HelloRetryRequest (RFC 8446 §4.1.4). This client always offers
        // an X25519 share and implements only X25519 TLS 1.3 key
        // exchange, so a well-formed HRR either requests a group already
        // offered (a server protocol error — the retry would change
        // nothing) or a group this client cannot provide. Both cases
        // abort with the RFC-mandated fatal alert rather than mis-parsing
        // the HRR as a ServerHello.
        if handshake::is_hello_retry_request(sh_body) {
            let hrr = handshake::parse_hello_retry_request(sh_body)?;
            if hrr.selected_group == handshake::GROUP_X25519
                || (hrr.selected_group != tls12::GROUP_SECP256R1)
            {
                // Selected group already offered, or not in our
                // supported_groups at all.
                let _ = io.write_plaintext_record(record::CONTENT_ALERT, &[2, 47]); // illegal_parameter
                return Err(TlsError::Protocol(
                    "HelloRetryRequest selected an invalid key exchange group".into(),
                ));
            }
            // secp256r1 is supported but this client has no TLS 1.3
            // P-256 ECDHE implementation.
            let _ = io.write_plaintext_record(record::CONTENT_ALERT, &[2, 40]); // handshake_failure
            return Err(TlsError::Unsupported(format!(
                "HelloRetryRequest requested unsupported group 0x{:04x}",
                hrr.selected_group
            )));
        }
        let is13 = handshake::server_hello_negotiates_tls13(sh_body);
        if is13 {
            if !allow13 {
                return Err(TlsError::Protocol(
                    "server negotiated TLS 1.3 but the client did not offer it".into(),
                ));
            }
            let hs = handshake::ClientHandshake {
                server_name: Some(hostname.to_string()),
                verify: self.config.verify,
                psk: resume_session.map(|s| (s.psk, s.suite)),
                identity: self.config.identity.clone(),
            };
            let result = hs.run_from_server_hello(
                &mut io,
                &self.config.roots,
                self.config.now,
                &ch,
                &random,
                &priv13,
                sh_body,
                None,
            )?;
            io.reset_sequences();
            let stream = TlsStream {
                io,
                version: TlsVersion::Tls13,
                suite: result.suite,
                suite12: None,
                write_keys: result.keys.write,
                read_keys: result.keys.read,
                negotiated_alpn: result.alpn,
                server_name: result.server_name,
                peer_certificate: result.peer_cert,
                closed: false,
                pending: Vec::new(),
                pending_pos: 0,
                rec: RecState::Idle,
                resumption_master: result.resumption_master.map(|m| (m, result.suite)),
                resumed: result.resumed,
                session_store: Some(self.sessions.clone()),
                hostname: hostname.to_string(),
                now: self.config.now,
                write_app_secret: Some(result.keys.write_secret),
                read_app_secret: Some(result.keys.read_secret),
                pending_key_update: false,
                write_records: 0,
                key_use_limit: key_use_limit(result.suite),
                key_read_gen: 0,
                key_write_gen: 0,
            };
            // Tickets are captured lazily as records are read and cached
            // in the shared store; connect() never blocks waiting for a
            // post-handshake message.
            Ok(stream)
        } else {
            if !allow12 {
                return Err(TlsError::Protocol(
                    "server negotiated TLS 1.2 but the client refused it".into(),
                ));
            }
            let result = tls12::client_handshake(
                &mut io,
                &self.config.roots,
                self.config.now,
                self.config.verify,
                Some(hostname),
                &ch,
                &random,
                &first_payload,
                allow13,
            )?;
            // TLS 1.2 keeps one key generation for the whole connection:
            // the Finished already consumed sequence number 0, so the
            // sequence counters are NOT reset here (unlike TLS 1.3).
            Ok(TlsStream {
                io,
                version: TlsVersion::Tls12,
                suite: key_schedule::CipherSuite::TlsAes128GcmSha256,
                suite12: Some(result.suite),
                write_keys: result.keys.write,
                read_keys: result.keys.read,
                negotiated_alpn: result.alpn,
                server_name: result.server_name,
                peer_certificate: result.peer_cert,
                closed: false,
                pending: Vec::new(),
                pending_pos: 0,
                rec: RecState::Idle,
                resumption_master: None,
                resumed: false,
                session_store: None,
                hostname: hostname.to_string(),
                now: self.config.now,
                write_app_secret: None,
                read_app_secret: None,
                pending_key_update: false,
                write_records: 0,
                key_use_limit: u64::MAX,
                key_read_gen: 0,
                key_write_gen: 0,
            })
        }
    }
}

// ---------------------------------------------------------------------
// Server acceptor
// ---------------------------------------------------------------------

/// Insert a resumption session into a shared cache, replacing any older
/// entry for the same host and evicting the oldest when the bound is
/// exceeded (bounded memory).
fn cache_session(store: &mut Vec<session::ClientSession>, sess: session::ClientSession) {
    store.retain(|s| s.hostname != sess.hostname);
    store.push(sess);
    const MAX_SESSIONS: usize = 8;
    if store.len() > MAX_SESSIONS {
        let overflow = store.len() - MAX_SESSIONS;
        store.drain(..overflow);
    }
}

/// Current Unix time in seconds (server-side ticket stamping).
fn unix_now() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

/// Server-side TLS configuration.
pub struct ServerConfig {
    /// The server's certificate chain and private key.
    pub identity: Identity,
    /// ALPN protocols offered (the first match wins).
    pub alpn: Vec<Vec<u8>>,
    /// The lowest TLS version the server will negotiate. Defaults to
    /// [`TlsVersion::Tls12`]; set to [`TlsVersion::Tls13`] to refuse
    /// TLS 1.2 clients outright.
    pub min_version: TlsVersion,
    /// The highest TLS version the server will negotiate. Defaults to
    /// [`TlsVersion::Tls13`].
    pub max_version: TlsVersion,
    /// Key used to encrypt session tickets. `None` generates a fresh
    /// per-acceptor key, so sessions survive across connections served
    /// by the same acceptor but not across process restarts.
    pub session_ticket_key: Option<[u8; 32]>,
    /// Client authentication (mTLS). `None` (the default) never asks for
    /// a client certificate. Implemented for TLS 1.3; a client that
    /// negotiates TLS 1.2 is refused rather than admitted unauthenticated
    /// when this is set.
    pub client_auth: Option<ClientAuth>,
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            identity: Identity::empty(),
            alpn: Vec::new(),
            min_version: TlsVersion::Tls12,
            max_version: TlsVersion::Tls13,
            session_ticket_key: None,
            client_auth: None,
        }
    }
}

/// A TLS 1.2 / 1.3 server acceptor.
pub struct TlsAcceptor {
    config: ServerConfig,
    /// The session-ticket encryption key (shared across accepts). `None`
    /// disables resumption.
    ticket_key: Option<[u8; 32]>,
}

impl TlsAcceptor {
    /// Create an acceptor from a configuration.
    pub fn new(config: ServerConfig) -> Self {
        let ticket_key = match config.session_ticket_key {
            Some(k) if k != [0u8; 32] => Some(k),
            Some(_) => None,
            None => {
                let mut k = [0u8; 32];
                crypto::rng::fill_random(&mut k).then_some(k)
            }
        };
        Self { config, ticket_key }
    }

    /// The underlying configuration.
    pub fn config(&self) -> &ServerConfig {
        &self.config
    }

    /// Perform a TLS handshake as the server. The version is negotiated
    /// from the ClientHello: a client offering TLS 1.3 is answered with
    /// TLS 1.3 when `max_version` allows; otherwise TLS 1.2 is used (an
    /// Ed25519-only identity cannot sign a TLS 1.2 ServerKeyExchange, so
    /// such identities report "no shared TLS 1.2 cipher suite" rather
    /// than downgrading the record layer).
    pub fn accept<R: crate::courierust_io::Read, W: crate::courierust_io::Write>(
        &self,
        reader: R,
        writer: W,
    ) -> TlsResult<TlsStream<R, W>> {
        let mut io = TlsIo::new(reader, writer);
        let (_, ch_body) = io.read_plaintext_handshake()?;
        let allow13 = self.config.max_version >= TlsVersion::Tls13;
        let allow12 = self.config.min_version <= TlsVersion::Tls12;
        let client_offers_13 = handshake::client_hello_offers_tls13(&ch_body)?;

        if client_offers_13 && allow13 {
            let hs = handshake::ServerHandshake {
                identity: self.config.identity.clone(),
                alpn: self.config.alpn.clone(),
                ticket_key: self.ticket_key,
                now: unix_now(),
                client_auth: self.config.client_auth.clone(),
            };
            let result = hs.run_from_client_hello(&mut io, &ch_body)?;
            Ok(TlsStream {
                io,
                version: TlsVersion::Tls13,
                suite: result.suite,
                suite12: None,
                write_keys: result.keys.write,
                read_keys: result.keys.read,
                negotiated_alpn: result.alpn,
                server_name: result.server_name,
                peer_certificate: result.peer_cert,
                closed: false,
                pending: Vec::new(),
                pending_pos: 0,
                rec: RecState::Idle,
                resumption_master: None,
                resumed: result.resumed,
                session_store: None,
                hostname: String::new(),
                now: 0,
                write_app_secret: Some(result.keys.write_secret),
                read_app_secret: Some(result.keys.read_secret),
                pending_key_update: false,
                write_records: 0,
                key_use_limit: key_use_limit(result.suite),
                key_read_gen: 0,
                key_write_gen: 0,
            })
        } else if allow12 {
            if self.config.client_auth.is_some() {
                // Client authentication is implemented for TLS 1.3:
                // a TLS 1.2 client would arrive unauthenticated, so the
                // version is refused instead of the policy being
                // silently downgraded.
                return Err(TlsError::Unsupported(
                    "client authentication requires TLS 1.3".into(),
                ));
            }
            let result = match tls12::server_handshake(
                &mut io,
                &self.config.identity,
                &self.config.alpn,
                &ch_body,
            ) {
                Ok(r) => r,
                Err(e) => {
                    let _ = io.write_plaintext_record(
                        record::CONTENT_ALERT,
                        &[2, 40], // fatal, handshake_failure
                    );
                    return Err(e);
                }
            };
            Ok(TlsStream {
                io,
                version: TlsVersion::Tls12,
                suite: key_schedule::CipherSuite::TlsAes128GcmSha256,
                suite12: Some(result.suite),
                write_keys: result.keys.write,
                read_keys: result.keys.read,
                negotiated_alpn: result.alpn,
                server_name: result.server_name,
                peer_certificate: result.peer_cert,
                closed: false,
                pending: Vec::new(),
                pending_pos: 0,
                rec: RecState::Idle,
                resumption_master: None,
                resumed: false,
                session_store: None,
                hostname: String::new(),
                now: 0,
                write_app_secret: None,
                read_app_secret: None,
                pending_key_update: false,
                write_records: 0,
                key_use_limit: u64::MAX,
                key_read_gen: 0,
                key_write_gen: 0,
            })
        } else {
            let _ = io.write_plaintext_record(
                record::CONTENT_ALERT,
                &[2, 70], // fatal, protocol_version
            );
            Err(TlsError::Protocol(
                "no acceptable TLS version between client and server".into(),
            ))
        }
    }
}

/// Sign the CertificateVerify message with the server identity. Returns
/// the (signature scheme, signature) pair.
pub(crate) fn server_sign(
    identity: &Identity,
    message: &[u8],
    suite: key_schedule::CipherSuite,
) -> TlsResult<Option<(u16, Vec<u8>)>> {
    sign::sign_cert_verify(identity, message, suite)
}

mod sign;

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::{TcpListener, TcpStream};

    /// Full 1-RTT handshake over real loopback TCP: the client validates
    /// the server's Ed25519 certificate chain and hostname, both sides
    /// verify each other's Finished, and encrypted application data
    /// round-trips.
    #[test]
    fn tls13_handshake_roundtrip() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let server = std::thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            let acceptor = TlsAcceptor::new(ServerConfig {
                identity: testdata::server_identity(),
                alpn: vec![b"h2".to_vec()],
                min_version: TlsVersion::Tls13,
                max_version: TlsVersion::Tls13,
                session_ticket_key: None,

                client_auth: None,
            });
            let mut tls = acceptor.accept(&stream, &stream).unwrap();
            assert_eq!(tls.alpn(), Some(&b"h2"[..]));
            let data = tls.read_record().unwrap();
            assert_eq!(data, b"ping");
            tls.write_all(b"pong").unwrap();
            tls.close_notify().unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        let connector = TlsConnector::new(ClientConfig {
            roots: testdata::root_store(),
            verify: true,
            alpn: vec![b"h2".to_vec()],
            now: testdata::NOW,
            min_version: TlsVersion::Tls13,
            max_version: TlsVersion::Tls13,

            identity: None,
        });
        let mut tls = connector.connect("localhost", &stream, &stream).unwrap();
        assert_eq!(tls.alpn(), Some(&b"h2"[..]));
        assert!(tls.peer_certificate().is_some());
        tls.write_all(b"ping").unwrap();
        let data = tls.read_record().unwrap();
        assert_eq!(data, b"pong");
        tls.close_notify().unwrap();

        server.join().unwrap();
    }

    /// RFC 8446 §4.6.3: a `KeyUpdate` rekeys the *sender's* direction, the
    /// receiver adopts the next generation for reading, and a request is
    /// answered with an update of the peer's own — after which data still
    /// flows both ways under the new keys.
    #[test]
    fn tls13_key_update_rekeys_both_directions() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let server = std::thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            let acceptor = TlsAcceptor::new(ServerConfig {
                identity: testdata::server_identity(),
                alpn: Vec::new(),
                min_version: TlsVersion::Tls13,
                max_version: TlsVersion::Tls13,
                session_ticket_key: None,

                client_auth: None,
            });
            let mut tls = acceptor.accept(&stream, &stream).unwrap();
            assert_eq!(tls.read_record().unwrap(), b"before");
            tls.write_all(b"after").unwrap();
            // This read processes the client's KeyUpdate (answering it is
            // owed before the next application record).
            assert_eq!(tls.read_record().unwrap(), b"again");
            tls.write_all(b"end").unwrap();
            assert_eq!(tls.key_generations(), (1, 1));
            tls.close_notify().unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        stream
            .set_read_timeout(Some(std::time::Duration::from_secs(5)))
            .unwrap();
        let connector = TlsConnector::new(ClientConfig {
            roots: testdata::root_store(),
            verify: true,
            alpn: Vec::new(),
            now: testdata::NOW,
            min_version: TlsVersion::Tls13,
            max_version: TlsVersion::Tls13,

            identity: None,
        });
        let mut tls = connector.connect("localhost", &stream, &stream).unwrap();
        tls.write_all(b"before").unwrap();
        tls.request_key_update().unwrap();
        tls.write_all(b"again").unwrap();
        assert_eq!(tls.read_record().unwrap(), b"after");
        // The server's own update rides in front of `end`.
        assert_eq!(tls.read_record().unwrap(), b"end");
        assert_eq!(tls.key_generations(), (1, 1));
        tls.close_notify().unwrap();

        server.join().unwrap();
    }

    /// RFC 8446 §5.5: a key that has spent its record budget is replaced
    /// before the next record goes out, without the peer asking.
    #[test]
    fn tls13_key_update_record_budget_forces_a_rekey() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let server = std::thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            let acceptor = TlsAcceptor::new(ServerConfig {
                identity: testdata::server_identity(),
                alpn: Vec::new(),
                min_version: TlsVersion::Tls13,
                max_version: TlsVersion::Tls13,
                session_ticket_key: None,

                client_auth: None,
            });
            let mut tls = acceptor.accept(&stream, &stream).unwrap();
            for expected in [&b"one"[..], b"two", b"three"] {
                assert_eq!(tls.read_record().unwrap(), expected);
            }
            // One update was received; this side never sent one.
            assert_eq!(tls.key_generations(), (1, 0));
            tls.close_notify().unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        stream
            .set_read_timeout(Some(std::time::Duration::from_secs(5)))
            .unwrap();
        let connector = TlsConnector::new(ClientConfig {
            roots: testdata::root_store(),
            verify: true,
            alpn: Vec::new(),
            now: testdata::NOW,
            min_version: TlsVersion::Tls13,
            max_version: TlsVersion::Tls13,

            identity: None,
        });
        let mut tls = connector.connect("localhost", &stream, &stream).unwrap();
        tls.set_key_use_limit(2);
        tls.write_all(b"one").unwrap();
        tls.write_all(b"two").unwrap();
        // The budget is spent: the third record is preceded by an update.
        tls.write_all(b"three").unwrap();
        assert_eq!(tls.key_generations(), (0, 1));
        tls.close_notify().unwrap();

        server.join().unwrap();
    }

    /// The client must reject an untrusted server (empty root store) and
    /// a hostname that does not match the certificate.
    #[test]
    fn tls13_client_rejects_untrusted_and_hostname() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let server = std::thread::spawn(move || {
            // The server completes each handshake regardless of what the
            // client does; the client's validation failure closes the
            // connection (surfacing as an I/O error on the server, which
            // we ignore).
            for _ in 0..2 {
                let (stream, _) = listener.accept().unwrap();
                let acceptor = TlsAcceptor::new(ServerConfig {
                    identity: testdata::server_identity(),
                    alpn: Vec::new(),
                    min_version: TlsVersion::Tls13,
                    max_version: TlsVersion::Tls13,
                    session_ticket_key: None,

                    client_auth: None,
                });
                let _ = acceptor.accept(&stream, &stream);
            }
        });

        // 1. Untrusted root.
        let stream = TcpStream::connect(addr).unwrap();
        let connector = TlsConnector::new(ClientConfig {
            roots: RootStore::new(),
            verify: true,
            alpn: Vec::new(),
            now: testdata::NOW,
            min_version: TlsVersion::Tls13,
            max_version: TlsVersion::Tls13,

            identity: None,
        });
        let err = match connector.connect("localhost", &stream, &stream) {
            Ok(_) => panic!("untrusted root accepted"),
            Err(e) => e,
        };
        assert!(matches!(err, TlsError::Certificate(_)), "got {err:?}");
        // Close the socket so the server's pending Finished read unblocks.
        drop(stream);

        // 2. Hostname mismatch (certificate is for `localhost`).
        let stream = TcpStream::connect(addr).unwrap();
        let connector = TlsConnector::new(ClientConfig {
            roots: testdata::root_store(),
            verify: true,
            alpn: Vec::new(),
            now: testdata::NOW,
            min_version: TlsVersion::Tls13,
            max_version: TlsVersion::Tls13,

            identity: None,
        });
        let err = match connector.connect("not-localhost", &stream, &stream) {
            Ok(_) => panic!("hostname mismatch accepted"),
            Err(e) => e,
        };
        assert!(matches!(err, TlsError::Certificate(_)), "got {err:?}");
        drop(stream);

        let _ = server.join();
    }

    /// Full TLS 1.2 ECDHE-RSA handshake over loopback TCP with the RSA
    /// test identity: the client validates the certificate chain and
    /// hostname, both sides verify each other's Finished, and encrypted
    /// application data round-trips. Also asserts the negotiated version
    /// is TLS 1.2 with an ECDHE-RSA suite.
    /// mTLS (RFC 8446 §4.4.2): the server asks for a client certificate,
    /// the client presents one it proves possession of, and the handshake
    /// completes. The server keeps the peer's leaf, which is what an
    /// authorization layer above reads.
    #[test]
    fn tls13_mtls_roundtrip() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let server = std::thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            let mut roots = RootStore::new();
            roots.add_der(testdata::SERVER_CERT_DER.to_vec());
            let acceptor = TlsAcceptor::new(ServerConfig {
                identity: testdata::server_identity(),
                alpn: Vec::new(),
                min_version: TlsVersion::Tls13,
                max_version: TlsVersion::Tls13,
                session_ticket_key: None,
                client_auth: Some(ClientAuth::required(roots)),
            });
            let mut tls = acceptor.accept(&stream, &stream).unwrap();
            assert_eq!(
                tls.peer_certificate(),
                Some(testdata::SERVER_CERT_DER),
                "the authenticating client's leaf must reach the server"
            );
            let data = tls.read_record().unwrap();
            assert_eq!(data, b"ping");
            tls.write_all(b"pong").unwrap();
            tls.close_notify().unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        let connector = TlsConnector::new(ClientConfig {
            roots: testdata::root_store(),
            verify: true,
            alpn: Vec::new(),
            now: testdata::NOW,
            min_version: TlsVersion::Tls13,
            max_version: TlsVersion::Tls13,
            identity: Some(testdata::server_identity()),
        });
        let mut tls = connector.connect("localhost", &stream, &stream).unwrap();
        tls.write_all(b"ping").unwrap();
        assert_eq!(tls.read_record().unwrap(), b"pong");
        tls.close_notify().unwrap();
        server.join().unwrap();
    }

    /// The policy, not the mechanism: a server that *requires* client
    /// authentication refuses a client that answers the request with an
    /// empty certificate list (RFC 8446 §6.2, `certificate_required`),
    /// while `optional` admits the same client as anonymous.
    #[test]
    fn tls13_mtls_required_refuses_an_anonymous_client() {
        for required in [true, false] {
            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
            let addr = listener.local_addr().unwrap();

            let server = std::thread::spawn(move || {
                let (stream, _) = listener.accept().unwrap();
                let mut roots = RootStore::new();
                roots.add_der(testdata::SERVER_CERT_DER.to_vec());
                let auth = if required {
                    ClientAuth::required(roots)
                } else {
                    ClientAuth::optional(roots)
                };
                let acceptor = TlsAcceptor::new(ServerConfig {
                    identity: testdata::server_identity(),
                    alpn: Vec::new(),
                    min_version: TlsVersion::Tls13,
                    max_version: TlsVersion::Tls13,
                    session_ticket_key: None,
                    client_auth: Some(auth),
                });
                acceptor
                    .accept(&stream, &stream)
                    .map(|tls| tls.peer_certificate().is_some())
            });

            let stream = TcpStream::connect(addr).unwrap();
            let connector = TlsConnector::new(ClientConfig {
                roots: testdata::root_store(),
                verify: true,
                alpn: Vec::new(),
                now: testdata::NOW,
                min_version: TlsVersion::Tls13,
                max_version: TlsVersion::Tls13,
                identity: None,
            });
            let outcome = connector.connect("localhost", &stream, &stream);
            let server_outcome = server.join().unwrap();
            if required {
                assert!(
                    matches!(
                        server_outcome,
                        Err(TlsError::Alert {
                            level: 2,
                            description: 116
                        })
                    ),
                    "a required certificate must be refused with certificate_required"
                );
                // The client has already sent its Finished, so its handshake
                // completes locally; the refusal arrives as an alert on the
                // first read.
                let err = match outcome {
                    Err(e) => e,
                    Ok(mut tls) => tls
                        .read_record()
                        .expect_err("the server required a client certificate"),
                };
                assert!(
                    matches!(
                        err,
                        TlsError::Alert {
                            level: 2,
                            description: 116
                        }
                    ),
                    "got {err:?}"
                );
            } else {
                assert!(
                    outcome.is_ok() && matches!(server_outcome, Ok(false)),
                    "an optional request admits an anonymous client"
                );
                if let Ok(mut tls) = outcome {
                    let _ = tls.close_notify();
                }
            }
        }
    }

    /// A client certificate is only as good as its chain: one that does
    /// not anchor to the configured roots fails the handshake even though
    /// the client signed perfectly.
    #[test]
    fn tls13_mtls_refuses_an_untrusted_client_chain() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let server = std::thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            // Trusts the RSA certificate only; the client will present the
            // Ed25519 one.
            let mut roots = RootStore::new();
            roots.add_der(testdata::RSA_SERVER_CERT_DER.to_vec());
            let acceptor = TlsAcceptor::new(ServerConfig {
                identity: testdata::server_identity(),
                alpn: Vec::new(),
                min_version: TlsVersion::Tls13,
                max_version: TlsVersion::Tls13,
                session_ticket_key: None,
                client_auth: Some(ClientAuth::required(roots)),
            });
            acceptor.accept(&stream, &stream).map(|_| ())
        });

        let stream = TcpStream::connect(addr).unwrap();
        let connector = TlsConnector::new(ClientConfig {
            roots: testdata::root_store(),
            verify: true,
            alpn: Vec::new(),
            now: testdata::NOW,
            min_version: TlsVersion::Tls13,
            max_version: TlsVersion::Tls13,
            identity: Some(testdata::server_identity()),
        });
        let client_outcome = connector.connect("localhost", &stream, &stream);
        let server_outcome = server.join().unwrap();
        assert!(
            server_outcome.is_err(),
            "an untrusted client chain must be refused"
        );
        // Same asymmetry: the client finishes locally and learns about the
        // refusal from the alert the server sends (`bad_certificate`).
        let err = match client_outcome {
            Err(e) => e,
            Ok(mut tls) => tls
                .read_record()
                .expect_err("the server refused this client chain"),
        };
        assert!(
            matches!(
                err,
                TlsError::Alert {
                    level: 2,
                    description: 42
                }
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn tls13_with_rsa_identity_roundtrip() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let server = std::thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            let acceptor = TlsAcceptor::new(ServerConfig {
                identity: testdata::rsa_server_identity(),
                alpn: Vec::new(),
                min_version: TlsVersion::Tls13,
                max_version: TlsVersion::Tls13,
                session_ticket_key: None,

                client_auth: None,
            });
            let mut tls = acceptor.accept(&stream, &stream).unwrap();
            assert_eq!(tls.version(), TlsVersion::Tls13);
            let data = tls.read_record().unwrap();
            assert_eq!(data, b"ping");
            tls.write_all(b"pong").unwrap();
            tls.close_notify().unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        let connector = TlsConnector::new(ClientConfig {
            roots: testdata::rsa_root_store(),
            verify: true,
            alpn: Vec::new(),
            now: testdata::NOW,
            min_version: TlsVersion::Tls13,
            max_version: TlsVersion::Tls13,

            identity: None,
        });
        let mut tls = connector.connect("localhost", &stream, &stream).unwrap();
        assert_eq!(tls.version(), TlsVersion::Tls13);
        tls.write_all(b"ping").unwrap();
        let data = tls.read_record().unwrap();
        assert_eq!(data, b"pong");
        tls.close_notify().unwrap();
        server.join().unwrap();
    }

    /// Full TLS 1.2 ECDHE-RSA handshake over loopback TCP with the RSA
    /// test identity: the client validates the certificate chain and
    /// hostname, both sides verify each other's Finished, and encrypted
    /// application data round-trips. Also asserts the negotiated version
    /// is TLS 1.2 with an ECDHE-RSA suite.
    #[test]
    fn tls12_handshake_roundtrip() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let server = std::thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            let acceptor = TlsAcceptor::new(ServerConfig {
                identity: testdata::rsa_server_identity(),
                alpn: vec![b"h2".to_vec()],
                min_version: TlsVersion::Tls12,
                max_version: TlsVersion::Tls12,
                session_ticket_key: None,

                client_auth: None,
            });
            let mut tls = acceptor.accept(&stream, &stream).unwrap();
            assert_eq!(tls.version(), TlsVersion::Tls12);
            assert_eq!(tls.alpn(), Some(&b"h2"[..]));
            let data = tls.read_record().unwrap();
            assert_eq!(data, b"ping");
            tls.write_all(b"pong").unwrap();
            tls.close_notify().unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        let connector = TlsConnector::new(ClientConfig {
            roots: testdata::rsa_root_store(),
            verify: true,
            alpn: vec![b"h2".to_vec()],
            now: testdata::NOW,
            min_version: TlsVersion::Tls12,
            max_version: TlsVersion::Tls12,

            identity: None,
        });
        let mut tls = connector.connect("localhost", &stream, &stream).unwrap();
        assert_eq!(tls.version(), TlsVersion::Tls12);
        assert!(tls.peer_certificate().is_some());
        assert_eq!(tls.alpn(), Some(&b"h2"[..]));
        // The suite must be an ECDHE_RSA AEAD suite.
        let suite = tls.cipher_suite();
        assert!(
            matches!(suite, 0xc02f | 0xc030 | 0xcca8),
            "unexpected TLS 1.2 suite {suite:#06x}"
        );
        tls.write_all(b"ping").unwrap();
        let data = tls.read_record().unwrap();
        assert_eq!(data, b"pong");
        tls.close_notify().unwrap();

        server.join().unwrap();
    }

    /// Full TLS 1.3 handshake with a P-384 identity: the server presents
    /// a chain whose *intermediate CA is a P-384 ECDSA key*, the client
    /// verifies both chain links (ecdsa-with-SHA384) against the P-384
    /// root, and the CertificateVerify is signed/verified with scheme
    /// 0x0503 under the negotiated SHA-384 suite. Regression test for the
    /// verifier defect that accepted only P-256 (65-byte SPKI).
    #[test]
    fn tls13_with_p384_identity_roundtrip() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let server = std::thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            let acceptor = TlsAcceptor::new(ServerConfig {
                identity: testdata::p384_server_identity(),
                alpn: Vec::new(),
                min_version: TlsVersion::Tls13,
                max_version: TlsVersion::Tls13,
                session_ticket_key: None,

                client_auth: None,
            });
            let mut tls = acceptor.accept(&stream, &stream).unwrap();
            assert_eq!(tls.version(), TlsVersion::Tls13);
            let data = tls.read_record().unwrap();
            assert_eq!(data, b"ping");
            tls.write_all(b"pong").unwrap();
            tls.close_notify().unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        let connector = TlsConnector::new(ClientConfig {
            roots: testdata::p384_root_store(),
            verify: true,
            alpn: Vec::new(),
            now: testdata::NOW,
            min_version: TlsVersion::Tls13,
            max_version: TlsVersion::Tls13,

            identity: None,
        });
        let mut tls = connector.connect("localhost", &stream, &stream).unwrap();
        assert_eq!(tls.version(), TlsVersion::Tls13);
        // A P-384 identity can only negotiate the SHA-384 suite
        // (TLS_AES_256_GCM_SHA384 = 0x1302).
        assert_eq!(tls.cipher_suite(), 0x1302);
        assert!(tls.peer_certificate().is_some());
        tls.write_all(b"ping").unwrap();
        let data = tls.read_record().unwrap();
        assert_eq!(data, b"pong");
        tls.close_notify().unwrap();
        server.join().unwrap();
    }

    /// Full TLS 1.2 ECDHE_ECDSA handshake with a P-384 identity: the
    /// ServerKeyExchange is signed with scheme 0x0503 (ecdsa_secp384r1_
    /// sha384) and the suite is ECDHE_ECDSA AES-256-GCM SHA-384. This
    /// exercises the P-384 SPKI path in the TLS 1.2 client as well.
    #[test]
    fn tls12_with_p384_identity_roundtrip() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let server = std::thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            let acceptor = TlsAcceptor::new(ServerConfig {
                identity: testdata::p384_server_identity(),
                alpn: Vec::new(),
                min_version: TlsVersion::Tls12,
                max_version: TlsVersion::Tls12,
                session_ticket_key: None,

                client_auth: None,
            });
            let mut tls = acceptor.accept(&stream, &stream).unwrap();
            assert_eq!(tls.version(), TlsVersion::Tls12);
            let data = tls.read_record().unwrap();
            assert_eq!(data, b"ping");
            tls.write_all(b"pong").unwrap();
            tls.close_notify().unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        let connector = TlsConnector::new(ClientConfig {
            roots: testdata::p384_root_store(),
            verify: true,
            alpn: Vec::new(),
            now: testdata::NOW,
            min_version: TlsVersion::Tls12,
            max_version: TlsVersion::Tls12,

            identity: None,
        });
        let mut tls = connector.connect("localhost", &stream, &stream).unwrap();
        assert_eq!(tls.version(), TlsVersion::Tls12);
        // The P-384 identity forces the SHA-384 ECDHE_ECDSA suite
        // (0xc02c = TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384).
        assert_eq!(tls.cipher_suite(), 0xc02c);
        tls.write_all(b"ping").unwrap();
        let data = tls.read_record().unwrap();
        assert_eq!(data, b"pong");
        tls.close_notify().unwrap();
        server.join().unwrap();
    }

    /// Version auto-negotiation: both sides allow TLS 1.2..1.3, the
    /// client offers TLS 1.3, and the server (RSA identity) picks
    /// TLS 1.3. A TLS 1.3 suite must be negotiated.
    #[test]
    fn tls_version_autonegotiates_to_13_when_offered() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let server = std::thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            let acceptor = TlsAcceptor::new(ServerConfig {
                identity: testdata::rsa_server_identity(),
                alpn: Vec::new(),
                ..Default::default()
            });
            let mut tls = acceptor.accept(&stream, &stream).unwrap();
            assert_eq!(tls.version(), TlsVersion::Tls13);
            tls.close_notify().unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        let connector = TlsConnector::new(ClientConfig {
            roots: testdata::rsa_root_store(),
            verify: true,
            alpn: Vec::new(),
            now: testdata::NOW,
            ..Default::default()
        });
        let mut tls = connector.connect("localhost", &stream, &stream).unwrap();
        assert_eq!(tls.version(), TlsVersion::Tls13);
        tls.close_notify().unwrap();
        server.join().unwrap();
    }

    /// Downgrade protection (RFC 8446 §4.1.3): a client that offered
    /// TLS 1.3 must reject a TLS 1.2 ServerHello without the downgrade
    /// sentinel. The honest server (max_version = TLS 1.2) always adds
    /// the sentinel, so this test drives a real server and then asserts
    /// the sentinel was present by checking the client accepted the
    /// negotiated TLS 1.2; the absence case is covered at the unit level
    /// in `tls12.rs` (the sentinel bytes are asserted on the wire there).
    #[test]
    fn tls12_negotiated_with_sentinel_when_client_offers_13() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let server = std::thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            // Server refuses TLS 1.3 but accepts TLS 1.2; the client
            // offered TLS 1.3, so the ServerHello must carry the
            // sentinel (the client aborts otherwise).
            let acceptor = TlsAcceptor::new(ServerConfig {
                identity: testdata::rsa_server_identity(),
                alpn: Vec::new(),
                min_version: TlsVersion::Tls12,
                max_version: TlsVersion::Tls12,
                session_ticket_key: None,

                client_auth: None,
            });
            let mut tls = acceptor.accept(&stream, &stream).unwrap();
            assert_eq!(tls.version(), TlsVersion::Tls12);
            tls.close_notify().unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        // Client defaults to offering TLS 1.3 (max_version = TLS 1.3)
        // and accepting TLS 1.2.
        let connector = TlsConnector::new(ClientConfig {
            roots: testdata::rsa_root_store(),
            verify: true,
            alpn: Vec::new(),
            now: testdata::NOW,
            ..Default::default()
        });
        let mut tls = connector.connect("localhost", &stream, &stream).unwrap();
        assert_eq!(tls.version(), TlsVersion::Tls12);
        tls.close_notify().unwrap();
        server.join().unwrap();
    }

    /// A TLS 1.3-only client must refuse a TLS 1.2-only server instead
    /// of silently downgrading.
    #[test]
    fn tls13_only_client_refuses_tls12_server() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let server = std::thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            let acceptor = TlsAcceptor::new(ServerConfig {
                identity: testdata::rsa_server_identity(),
                alpn: Vec::new(),
                min_version: TlsVersion::Tls12,
                max_version: TlsVersion::Tls12,
                session_ticket_key: None,

                client_auth: None,
            });
            let _ = acceptor.accept(&stream, &stream);
        });

        let stream = TcpStream::connect(addr).unwrap();
        let connector = TlsConnector::new(ClientConfig {
            roots: testdata::rsa_root_store(),
            verify: true,
            alpn: Vec::new(),
            now: testdata::NOW,
            min_version: TlsVersion::Tls13,
            max_version: TlsVersion::Tls13,

            identity: None,
        });
        let err = match connector.connect("localhost", &stream, &stream) {
            Ok(_) => panic!("TLS 1.3-only client accepted a TLS 1.2 server"),
            Err(e) => e,
        };
        // The connection must fail (no silent downgrade). The exact
        // error is a Protocol error (alert record seen) or an
        // UnexpectedEof (server closed before the client read).
        assert!(
            matches!(
                err,
                TlsError::Protocol(_) | TlsError::Alert { .. } | TlsError::UnexpectedEof
            ),
            "got {err:?}"
        );
        drop(stream);
        let _ = server.join();
    }

    /// An Ed25519 identity negotiates TLS 1.2 via an ECDHE_ECDSA suite:
    /// the server signs the ServerKeyExchange with Ed25519 (RFC 8422
    /// §4.3, scheme 0x0807) and the client verifies it.
    #[test]
    fn tls12_ed25519_identity_roundtrip() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let server = std::thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            let acceptor = TlsAcceptor::new(ServerConfig {
                identity: testdata::server_identity(), // Ed25519
                alpn: vec![b"h2".to_vec()],
                min_version: TlsVersion::Tls12,
                max_version: TlsVersion::Tls12,
                session_ticket_key: None,

                client_auth: None,
            });
            let mut tls = acceptor.accept(&stream, &stream).unwrap();
            assert_eq!(tls.version(), TlsVersion::Tls12);
            let data = tls.read_record().unwrap();
            assert_eq!(data, b"ping");
            tls.write_all(b"pong").unwrap();
            tls.close_notify().unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        let connector = TlsConnector::new(ClientConfig {
            roots: testdata::root_store(),
            verify: true,
            alpn: vec![b"h2".to_vec()],
            now: testdata::NOW,
            min_version: TlsVersion::Tls12,
            max_version: TlsVersion::Tls12,

            identity: None,
        });
        let mut tls = connector.connect("localhost", &stream, &stream).unwrap();
        assert_eq!(tls.version(), TlsVersion::Tls12);
        assert!(tls.peer_certificate().is_some());
        // The suite must be an ECDHE_ECDSA AEAD suite (Ed25519 signs the
        // SKE of the ECDSA family, RFC 8422 §4.3).
        let suite = tls.cipher_suite();
        assert!(
            matches!(suite, 0xc02b | 0xc02c | 0xcca9),
            "unexpected TLS 1.2 suite {suite:#06x}"
        );
        tls.write_all(b"ping").unwrap();
        let data = tls.read_record().unwrap();
        assert_eq!(data, b"pong");
        tls.close_notify().unwrap();

        server.join().unwrap();
    }

    /// Full session-resumption round trip (RFC 8446 §4.6.1): the first
    /// handshake issues a NewSessionTicket; the second reconnects with
    /// the resumption PSK (psk_dhe_ke) and is resumed.
    #[test]
    fn tls13_session_resumption_roundtrip() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let ticket_key = [0x5au8; 32];

        let server = std::thread::spawn(move || {
            let acceptor = TlsAcceptor::new(ServerConfig {
                identity: testdata::server_identity(),
                alpn: vec![b"h2".to_vec()],
                min_version: TlsVersion::Tls13,
                max_version: TlsVersion::Tls13,
                session_ticket_key: Some(ticket_key),

                client_auth: None,
            });
            for _ in 0..2 {
                let (stream, _) = listener.accept().unwrap();
                let mut tls = acceptor.accept(&stream, &stream).unwrap();
                let data = tls.read_record().unwrap();
                assert_eq!(data, b"ping");
                tls.write_all(b"pong").unwrap();
                tls.close_notify().unwrap();
            }
        });

        let connector = TlsConnector::new(ClientConfig {
            roots: testdata::root_store(),
            verify: true,
            alpn: vec![b"h2".to_vec()],
            now: testdata::NOW,
            min_version: TlsVersion::Tls13,
            max_version: TlsVersion::Tls13,

            identity: None,
        });

        // First connection: full handshake, ticket captured on connect.
        let stream = TcpStream::connect(addr).unwrap();
        stream
            .set_read_timeout(Some(std::time::Duration::from_secs(5)))
            .unwrap();
        let mut tls = connector.connect("localhost", &stream, &stream).unwrap();
        assert!(!tls.resumed(), "first handshake must be full");
        tls.write_all(b"ping").unwrap();
        match tls.read_record() {
            Ok(p) if p == b"pong" => {}
            other => panic!("bad first read: {other:?}"),
        }
        tls.close_notify().unwrap();

        // Second connection: must resume via the PSK.
        let stream = TcpStream::connect(addr).unwrap();
        stream
            .set_read_timeout(Some(std::time::Duration::from_secs(5)))
            .unwrap();
        let mut tls = connector.connect("localhost", &stream, &stream).unwrap();
        assert!(tls.resumed(), "second handshake must resume from the PSK");
        tls.write_all(b"ping").unwrap();
        assert_eq!(tls.read_record().unwrap(), b"pong");
        tls.close_notify().unwrap();

        server.join().unwrap();
    }

    /// A ticket that cannot be decrypted (or whose PSK does not match)
    /// must not resume: the server falls back to a full handshake and
    /// the connection still works (RFC 8446 §4.2.11 — unknown PSKs are
    /// ignored). The client must also accept the non-resumed ServerHello.
    #[test]
    fn tls13_session_resumption_tampered_ticket_falls_back() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let ticket_key = [0x5bu8; 32];

        let server = std::thread::spawn(move || {
            let acceptor = TlsAcceptor::new(ServerConfig {
                identity: testdata::server_identity(),
                alpn: vec![b"h2".to_vec()],
                min_version: TlsVersion::Tls13,
                max_version: TlsVersion::Tls13,
                session_ticket_key: Some(ticket_key),

                client_auth: None,
            });
            for _ in 0..2 {
                let (stream, _) = listener.accept().unwrap();
                let mut tls = acceptor.accept(&stream, &stream).unwrap();
                assert_eq!(tls.read_record().unwrap(), b"ping");
                tls.write_all(b"pong").unwrap();
                tls.close_notify().unwrap();
            }
        });

        let connector = TlsConnector::new(ClientConfig {
            roots: testdata::root_store(),
            verify: true,
            alpn: vec![b"h2".to_vec()],
            now: testdata::NOW,
            min_version: TlsVersion::Tls13,
            max_version: TlsVersion::Tls13,

            identity: None,
        });

        // First connection: full handshake, captures a ticket.
        let stream = TcpStream::connect(addr).unwrap();
        stream
            .set_read_timeout(Some(std::time::Duration::from_secs(5)))
            .unwrap();
        let mut tls = connector.connect("localhost", &stream, &stream).unwrap();
        assert!(!tls.resumed());
        tls.write_all(b"ping").unwrap();
        assert_eq!(tls.read_record().unwrap(), b"pong");
        tls.close_notify().unwrap();

        // Corrupt the cached ticket so the server cannot decrypt it.
        {
            let mut sessions = connector.sessions.lock().unwrap();
            let s = sessions.last_mut().unwrap();
            let i = s.ticket.len() - 1;
            s.ticket[i] ^= 0x01;
        }

        // Second connection: offer is made but must not resume.
        let stream = TcpStream::connect(addr).unwrap();
        stream
            .set_read_timeout(Some(std::time::Duration::from_secs(5)))
            .unwrap();
        let mut tls = connector.connect("localhost", &stream, &stream).unwrap();
        assert!(
            !tls.resumed(),
            "tampered ticket must fall back to a full handshake"
        );
        tls.write_all(b"ping").unwrap();
        assert_eq!(tls.read_record().unwrap(), b"pong");
        tls.close_notify().unwrap();

        server.join().unwrap();
    }

    /// A client that supports X25519 but offers no key share (empty
    /// `client_shares`, RFC 8446 §4.2.8) receives a HelloRetryRequest;
    /// the retried ClientHello with an X25519 share then completes a full
    /// handshake whose transcript carries `message_hash(Hash(CH1)) || HRR
    /// || CH2` (RFC 8446 §4.4.1).
    #[test]
    fn tls13_server_sends_hello_retry_request_and_completes() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let server = std::thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            let acceptor = TlsAcceptor::new(ServerConfig {
                identity: testdata::server_identity(),
                alpn: vec![b"h2".to_vec()],
                min_version: TlsVersion::Tls13,
                max_version: TlsVersion::Tls13,
                session_ticket_key: None,

                client_auth: None,
            });
            let mut tls = acceptor.accept(&stream, &stream).unwrap();
            assert_eq!(tls.read_record().unwrap(), b"ping");
            tls.write_all(b"pong").unwrap();
            tls.close_notify().unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        stream
            .set_read_timeout(Some(std::time::Duration::from_secs(5)))
            .unwrap();
        let mut io = TlsIo::new(&stream, &stream);

        // CH1 requests group selection (empty key_share).
        let mut random = [0u8; 32];
        handshake::fill_entropy(&mut random).unwrap();
        let ch1 = handshake::build_client_hello_negotiated(
            &random,
            None,
            &[b"h2".to_vec()],
            Some("localhost"),
            None,
            true,
            false,
        );
        io.write_plaintext_record_v(tls12::VERSION_12, record::CONTENT_HANDSHAKE, &ch1)
            .unwrap();

        // The server must answer with a HelloRetryRequest for X25519.
        let (ct, hrr_payload) = io.read_plaintext_record().unwrap();
        assert_eq!(ct, record::CONTENT_HANDSHAKE);
        assert!(handshake::is_hello_retry_request(&hrr_payload[4..]));
        let hrr = handshake::parse_hello_retry_request(&hrr_payload[4..]).unwrap();
        assert_eq!(hrr.selected_group, handshake::GROUP_X25519);

        // CH2: fresh X25519 share, same random.
        let mut priv2 = [0u8; 32];
        handshake::fill_entropy(&mut priv2).unwrap();
        let pub2 = crypto::x25519::x25519(&priv2, &crypto::x25519::BASE_POINT);
        let ch2 = handshake::build_client_hello_negotiated(
            &random,
            Some(&pub2),
            &[b"h2".to_vec()],
            Some("localhost"),
            None,
            true,
            false,
        );
        io.write_plaintext_record_v(tls12::VERSION_12, record::CONTENT_HANDSHAKE, &ch2)
            .unwrap();

        // Real ServerHello follows.
        let (ct, sh_payload) = io.read_plaintext_record().unwrap();
        assert_eq!(ct, record::CONTENT_HANDSHAKE);
        let sh_body = &sh_payload[4..];
        assert!(handshake::server_hello_negotiates_tls13(sh_body));

        let hs = handshake::ClientHandshake {
            server_name: Some("localhost".to_string()),
            verify: true,
            psk: None,
            identity: None,
        };
        let result = hs
            .run_from_server_hello(
                &mut io,
                &testdata::root_store(),
                testdata::NOW,
                &ch2,
                &random,
                &priv2,
                sh_body,
                Some((&ch1, &hrr_payload, &ch2)),
            )
            .unwrap();
        io.reset_sequences();

        let mut tls = TlsStream {
            io,
            version: TlsVersion::Tls13,
            suite: result.suite,
            suite12: None,
            write_keys: result.keys.write,
            read_keys: result.keys.read,
            negotiated_alpn: result.alpn,
            server_name: result.server_name,
            peer_certificate: result.peer_cert,
            closed: false,
            pending: Vec::new(),
            pending_pos: 0,
            rec: RecState::Idle,
            resumption_master: None,
            resumed: result.resumed,
            session_store: None,
            hostname: "localhost".to_string(),
            now: testdata::NOW,
            write_app_secret: Some(result.keys.write_secret),
            read_app_secret: Some(result.keys.read_secret),
            pending_key_update: false,
            write_records: 0,
            key_use_limit: key_use_limit(result.suite),
            key_read_gen: 0,
            key_write_gen: 0,
        };
        tls.write_all(b"ping").unwrap();
        assert_eq!(tls.read_record().unwrap(), b"pong");
        tls.close_notify().unwrap();

        server.join().unwrap();
    }
}