nbreq 0.3.1

Runtime-independent cancellable HTTP client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
#![cfg_attr(not(test), allow(dead_code))]

//! Private sans-I/O rustls client state.
//!
//! The native HTTP owner supplies encrypted bytes and owns the socket. This module owns only the
//! per-request TLS state and configuration. Handshake packet processing may block in platform
//! verification; the HTTP owner runs those steps through the bounded worker service.

pub(super) mod worker;

#[cfg(test)]
mod portable_tests;

use std::fmt;
use std::io::{self, Cursor, Read, Write};
use std::sync::Arc;

#[cfg(test)]
use std::collections::VecDeque;
#[cfg(test)]
use std::sync::Mutex;
#[cfg(test)]
use std::sync::mpsc::{Receiver, Sender};
#[cfg(test)]
use std::time::Duration;

use rustls::client::ClientConnection;
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::crypto::{
    CryptoProvider, WebPkiSupportedAlgorithms, verify_tls12_signature, verify_tls13_signature,
};
use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
use rustls::{
    CertificateError, ClientConfig, DigitallySignedStruct, Error as RustlsError, SignatureScheme,
};
use rustls_platform_verifier::BuilderVerifierExt;

use crate::{
    EngineConfig, Error, ErrorKind, TlsFailure, TlsTrust, TlsVerification, TransportStage,
};

pub(super) const TLS_FLIGHT_LIMIT: usize = 512 * 1024;
pub(super) const STANDALONE_TLS_OUTPUT_LIMIT: usize = 64 * 1024;
pub(super) const STANDALONE_TLS_WIRE_WINDOW: usize = 18 * 1024;
pub(super) const STANDALONE_TLS_PLAINTEXT_WINDOW: usize = STANDALONE_TLS_WIRE_WINDOW + 16 * 1024;
const TLS_PLAINTEXT_CHUNK: usize = 16 * 1024;
// TLS application records carry at most 16 KiB of plaintext. This includes generous wire
// overhead without teaching the HTTP owner how to parse TLS records itself. A streaming socket
// grants at most this much encrypted input before returning to its owner.
const TLS_STREAM_WIRE_ALLOWANCE: usize = 18 * 1024;
// A new wire window can finish a record partially buffered by the previous window before
// decoding further records. TLS has no application-data compression: at most one extra
// 16 KiB record of plaintext can come from that carry. Keep socket input at 18 KiB.
const TLS_STREAM_PLAINTEXT_LIMIT: usize = TLS_STREAM_WIRE_ALLOWANCE + TLS_PLAINTEXT_CHUNK;

#[derive(Clone)]
pub(super) struct NativeTlsConfigs {
    verified: Arc<ClientConfig>,
    unverified: Arc<ClientConfig>,
    configured_trust: Option<TlsTrust>,
}

fn supplied_roots(config: &EngineConfig) -> Result<rustls::RootCertStore, Error> {
    let mut roots = rustls::RootCertStore::empty();
    for root in config.additional_tls_root_certificates() {
        roots
            .add(CertificateDer::from(root.to_vec()))
            .map_err(|error| tls_config_error("supplied trust root", error))?;
    }
    Ok(roots)
}

fn portable_verifier(
    config: &EngineConfig,
    provider: Arc<CryptoProvider>,
) -> Result<Arc<rustls::client::WebPkiServerVerifier>, Error> {
    if config.tls_trust() == TlsTrust::BundledMozilla && !cfg!(feature = "bundled-roots") {
        return Err(Error::new(
            ErrorKind::Unsupported,
            "Mozilla TLS roots require the bundled-roots feature",
        ));
    }
    let roots = supplied_roots(config)?;
    let roots = match config.tls_trust() {
        TlsTrust::SuppliedRootsOnly => {
            if roots.is_empty() {
                return Err(tls_config_error(
                    "supplied trust roots",
                    "no roots supplied",
                ));
            }
            roots
        }
        TlsTrust::BundledMozilla => {
            #[cfg(feature = "bundled-roots")]
            {
                let mut roots = roots;
                roots
                    .roots
                    .extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
                roots
            }
            #[cfg(not(feature = "bundled-roots"))]
            return Err(Error::new(
                ErrorKind::Unsupported,
                "Mozilla TLS roots require the bundled-roots feature",
            ));
        }
        TlsTrust::Platform => {
            return Err(Error::new(
                ErrorKind::Unsupported,
                "portable verifier requires portable trust",
            ));
        }
    };
    rustls::client::WebPkiServerVerifier::builder_with_provider(Arc::new(roots), provider)
        .build()
        .map_err(|error| tls_config_error("portable verifier", error))
}

impl NativeTlsConfigs {
    pub(super) fn from_config(config: &EngineConfig) -> Result<Self, Error> {
        let mut tls = match config.tls_trust() {
            TlsTrust::Platform => {
                // Validate every input with the same DER parser before passing roots to
                // platform-specific APIs, some of which otherwise skip malformed roots.
                supplied_roots(config)?;
                Self::platform_with_extra_roots(config.additional_tls_root_certificates())?
            }
            TlsTrust::SuppliedRootsOnly | TlsTrust::BundledMozilla => {
                let provider = Arc::new(rustls::crypto::ring::default_provider());
                let verifier = portable_verifier(config, Arc::clone(&provider))?;
                let verified = ClientConfig::builder_with_provider(Arc::clone(&provider))
                    .with_safe_default_protocol_versions()
                    .map_err(|error| tls_config_error("protocol versions", error))?
                    .dangerous()
                    .with_custom_certificate_verifier(verifier)
                    .with_no_client_auth();
                Self::from_verified(provider, verified)?
            }
        };
        tls.configured_trust = Some(config.tls_trust());
        Ok(tls)
    }

    pub(super) fn configured_trust(&self) -> Option<TlsTrust> {
        self.configured_trust
    }

    pub(super) fn platform() -> Result<Self, Error> {
        let provider = Arc::new(rustls::crypto::ring::default_provider());
        let builder = ClientConfig::builder_with_provider(Arc::clone(&provider))
            .with_safe_default_protocol_versions()
            .map_err(|error| tls_config_error("protocol versions", error))?;
        let verified = builder
            .with_platform_verifier()
            .map_err(|error| tls_config_error("platform verifier", error))?
            .with_no_client_auth();
        Self::from_verified(provider, verified)
    }

    pub(super) fn platform_with_extra_roots(roots: &[Arc<[u8]>]) -> Result<Self, Error> {
        if roots.is_empty() {
            return Self::platform();
        }
        #[cfg(target_os = "android")]
        {
            // The pinned verifier delegates Android trust to application/network policy and
            // does not expose additional per-verifier roots. Never silently ignore this input.
            Err(Error::new(
                ErrorKind::Unsupported,
                "additional TLS roots are not supported by the Android platform verifier",
            ))
        }
        #[cfg(not(target_os = "android"))]
        {
            let provider = Arc::new(rustls::crypto::ring::default_provider());
            let verifier = rustls_platform_verifier::Verifier::new_with_extra_roots(
                roots.iter().map(|root| CertificateDer::from(root.to_vec())),
                Arc::clone(&provider),
            )
            .map_err(|error| tls_config_error("additional trust roots", error))?;
            let verified = ClientConfig::builder_with_provider(Arc::clone(&provider))
                .with_safe_default_protocol_versions()
                .map_err(|error| tls_config_error("protocol versions", error))?
                .dangerous()
                .with_custom_certificate_verifier(Arc::new(verifier))
                .with_no_client_auth();
            Self::from_verified(provider, verified)
        }
    }

    pub(super) fn with_test_root(root: CertificateDer<'static>) -> Result<Self, Error> {
        let provider = Arc::new(rustls::crypto::ring::default_provider());
        let mut roots = rustls::RootCertStore::empty();
        roots
            .add(root)
            .map_err(|error| tls_config_error("test trust root", error))?;
        let verified = ClientConfig::builder_with_provider(Arc::clone(&provider))
            .with_safe_default_protocol_versions()
            .map_err(|error| tls_config_error("protocol versions", error))?
            .with_root_certificates(roots)
            .with_no_client_auth();
        Self::from_verified(provider, verified)
    }

    #[cfg(test)]
    pub(super) fn with_test_root_and_verification_gate(
        root: CertificateDer<'static>,
        entered: Sender<()>,
        release: Receiver<()>,
    ) -> Result<Self, Error> {
        Self::with_test_root_and_verification_gates(root, vec![(entered, release)])
    }

    #[cfg(test)]
    pub(super) fn with_test_root_and_verification_gates(
        root: CertificateDer<'static>,
        gates: Vec<(Sender<()>, Receiver<()>)>,
    ) -> Result<Self, Error> {
        let provider = Arc::new(rustls::crypto::ring::default_provider());
        let mut roots = rustls::RootCertStore::empty();
        roots
            .add(root)
            .map_err(|error| tls_config_error("test trust root", error))?;
        let verifier = rustls::client::WebPkiServerVerifier::builder_with_provider(
            Arc::new(roots),
            Arc::clone(&provider),
        )
        .build()
        .map_err(|error| tls_config_error("test verifier", error))?;
        let verifier = Arc::new(GatedVerification {
            inner: verifier,
            gates: Mutex::new(gates.into()),
        });
        let verified = ClientConfig::builder_with_provider(Arc::clone(&provider))
            .with_safe_default_protocol_versions()
            .map_err(|error| tls_config_error("protocol versions", error))?
            .dangerous()
            .with_custom_certificate_verifier(verifier)
            .with_no_client_auth();
        Self::from_verified(provider, verified)
    }

    fn from_verified(
        provider: Arc<CryptoProvider>,
        mut verified: ClientConfig,
    ) -> Result<Self, Error> {
        verified.alpn_protocols = vec![b"http/1.1".to_vec()];
        let verifier = Arc::new(NoCertificateVerification {
            algorithms: provider.signature_verification_algorithms,
        });
        let mut unverified = ClientConfig::builder_with_provider(provider)
            .with_safe_default_protocol_versions()
            .map_err(|error| tls_config_error("protocol versions", error))?
            .dangerous()
            .with_custom_certificate_verifier(verifier)
            .with_no_client_auth();
        unverified.alpn_protocols = vec![b"http/1.1".to_vec()];
        Ok(Self {
            verified: Arc::new(verified),
            unverified: Arc::new(unverified),
            configured_trust: None,
        })
    }

    pub(super) fn standalone_connection(&self, server_name: &str) -> Result<StandaloneTls, Error> {
        let name = ServerName::try_from(server_name.to_owned()).map_err(|_| {
            Error::new(
                ErrorKind::InvalidRequest,
                "TLS server name cannot be represented as a peer identity",
            )
        })?;
        let mut config = (*self.verified).clone();
        config.alpn_protocols.clear();
        let mut connection = ClientConnection::new(Arc::new(config), name).map_err(|error| {
            Error::tls(
                TransportStage::Tls,
                classify_rustls_error(&error),
                "standalone TLS client setup failed",
            )
        })?;
        connection.set_buffer_limit(Some(STANDALONE_TLS_OUTPUT_LIMIT));
        Ok(StandaloneTls {
            session: Some(TlsSession {
                connection,
                handshake_received: 0,
                body_budget: None,
                outbound_limit: STANDALONE_TLS_OUTPUT_LIMIT,
            }),
        })
    }

    pub(super) fn connection(
        &self,
        host: &str,
        policy: TlsVerification,
        request: Vec<u8>,
    ) -> Result<NativeTls, Error> {
        let name = ServerName::try_from(host.to_owned()).map_err(|_| {
            Error::transport(
                TransportStage::Tls,
                "the HTTPS hostname cannot be represented as a TLS server name",
            )
        })?;
        let config = match policy {
            TlsVerification::Verify => Arc::clone(&self.verified),
            TlsVerification::DangerouslyDisableCertificateVerification => {
                Arc::clone(&self.unverified)
            }
        };
        let connection = ClientConnection::new(config, name).map_err(|error| {
            Error::tls(
                TransportStage::Tls,
                classify_rustls_error(&error),
                "native TLS client setup failed",
            )
        })?;
        Ok(NativeTls {
            session: Some(TlsSession {
                connection,
                handshake_received: 0,
                body_budget: None,
                outbound_limit: TLS_FLIGHT_LIMIT,
            }),
            request: Some(PendingPlaintext {
                bytes: request,
                offset: 0,
            }),
            retained_response: PendingPlaintext {
                bytes: Vec::new(),
                offset: 0,
            },
        })
    }
}

pub(super) struct NativeTls {
    session: Option<TlsSession>,
    request: Option<PendingPlaintext>,
    retained_response: PendingPlaintext,
}

/// The standalone TCP owner holds this sans-I/O client until verified establishment and beyond.
pub(super) struct StandaloneTls {
    session: Option<TlsSession>,
}

impl StandaloneTls {
    pub(super) fn promote_control(&mut self) -> Result<Vec<u8>, Error> {
        let session = self.session.as_mut().expect("established TLS session");
        if session.connection.is_handshaking() {
            return Ok(Vec::new());
        }
        session
            .connection
            .writer()
            .write(&[])
            .map_err(|error| tls_io_error(false, "control output", error))?;
        session.take_outbound()
    }

    pub(super) fn start(&mut self) -> Result<Vec<u8>, Error> {
        self.session
            .as_mut()
            .expect("TLS session at start")
            .take_outbound()
    }

    pub(super) fn is_handshaking(&self) -> bool {
        self.session
            .as_ref()
            .is_none_or(|session| session.connection.is_handshaking())
    }

    pub(super) fn handshake_in_worker(&self) -> bool {
        self.session.is_none()
    }

    pub(super) fn take_handshake(&mut self) -> Option<TlsSession> {
        if self.is_handshaking() {
            self.session.take()
        } else {
            None
        }
    }

    #[cfg(test)]
    pub(super) fn take_session_for_test(&mut self) -> TlsSession {
        self.session.take().expect("test TLS session must exist")
    }

    pub(super) fn restore_handshake(&mut self, session: TlsSession) {
        debug_assert!(self.session.is_none());
        self.session = Some(session);
    }

    pub(super) fn receive(&mut self, encrypted: &[u8]) -> Result<TlsProgress, Error> {
        // The owner stages this flight before calling promote_control, so a queued
        // KeyUpdate response never forces two 64 KiB Vecs into a merged third Vec.
        self.session
            .as_mut()
            .expect("TLS session outside worker")
            .receive(encrypted)
    }

    pub(super) fn drain_wire(&mut self, limit: usize) -> Result<Vec<u8>, Error> {
        let session = self.session.as_mut().expect("established TLS session");
        let mut output = exact_capacity_buffer(limit);
        session.drain_outbound_up_to(limit, &mut output)?;
        Ok(output)
    }

    pub(super) fn encrypt(
        &mut self,
        plaintext: &[u8],
        limit: usize,
    ) -> Result<(usize, Vec<u8>), Error> {
        let session = self.session.as_mut().expect("established TLS session");
        if session.connection.is_handshaking() {
            return Err(Error::new(
                ErrorKind::Internal,
                "application data before TLS verification",
            ));
        }
        let mut output = exact_capacity_buffer(limit);
        session.drain_outbound_up_to(limit, &mut output)?;
        if !output.is_empty() || session.connection.wants_write() || output.len() >= limit {
            return Ok((0, output));
        }
        let count = session
            .connection
            .writer()
            .write(plaintext)
            .map_err(|error| tls_io_error(false, "plaintext encryption", error))?;
        session.drain_outbound_up_to(limit, &mut output)?;
        if session.connection.wants_write() {
            return Err(Error::new(
                ErrorKind::Internal,
                "one TLS application record exceeded the bounded wire window",
            ));
        }
        Ok((count, output))
    }

    pub(super) fn wants_write(&self) -> bool {
        self.session
            .as_ref()
            .is_some_and(|session| session.connection.wants_write())
    }

    pub(super) fn send_close_notify(&mut self) -> Result<Vec<u8>, Error> {
        let session = self.session.as_mut().expect("established TLS session");
        session.connection.send_close_notify();
        session.take_outbound()
    }

    pub(super) fn protocol_version(&self) -> Option<rustls::ProtocolVersion> {
        self.session
            .as_ref()
            .and_then(|session| session.connection.protocol_version())
    }
}

// Worker ownership excludes HTTP request bytes and response delivery state.
pub(super) struct TlsSession {
    connection: ClientConnection,
    handshake_received: usize,
    body_budget: Option<Arc<crate::body_budget::BodyBudget>>,
    outbound_limit: usize,
}

impl TlsSession {
    pub(super) fn receive(&mut self, encrypted: &[u8]) -> Result<TlsProgress, Error> {
        let started_handshaking = self.connection.is_handshaking();
        if started_handshaking {
            self.handshake_received = self
                .handshake_received
                .checked_add(encrypted.len())
                .ok_or_else(tls_handshake_flight_limit)?;
            if self.handshake_received > TLS_FLIGHT_LIMIT {
                return Err(tls_handshake_flight_limit());
            }
        }
        let mut input = Cursor::new(encrypted);
        let mut plaintext = crate::body_budget::BodyBuffer::new(self.body_budget.clone());
        let mut peer_closed = false;
        while usize::try_from(input.position()).unwrap_or(usize::MAX) < encrypted.len() {
            let was_handshaking = self.connection.is_handshaking();
            let consumed = self
                .connection
                .read_tls(&mut input)
                .map_err(|error| tls_io_error(was_handshaking, "record input", error))?;
            if consumed == 0 {
                return Err(Error::new(
                    ErrorKind::Internal,
                    "native TLS made no progress while consuming a reactor event",
                ));
            }
            let state = self.connection.process_new_packets().map_err(|error| {
                let stage = if was_handshaking {
                    TransportStage::Tls
                } else {
                    TransportStage::Receive
                };
                Error::tls(
                    stage,
                    classify_rustls_error(&error),
                    "native TLS packet processing failed",
                )
            })?;
            peer_closed |= state.peer_has_closed();
            self.drain_plaintext(&mut plaintext)?;
        }
        Ok(TlsProgress {
            outbound: if started_handshaking {
                self.take_outbound()?
            } else {
                Vec::new()
            },
            plaintext,
            handshake_complete: !self.connection.is_handshaking(),
            peer_closed,
        })
    }

    fn drain_plaintext(
        &mut self,
        plaintext: &mut crate::body_budget::BodyBuffer,
    ) -> Result<(), Error> {
        let mut buffer = [0_u8; TLS_PLAINTEXT_CHUNK];
        let standalone_limit = (self.outbound_limit == STANDALONE_TLS_OUTPUT_LIMIT)
            .then_some(STANDALONE_TLS_PLAINTEXT_WINDOW);
        loop {
            match self.connection.reader().read(&mut buffer) {
                Ok(0) => break,
                Ok(read) => {
                    if let Some(limit) = standalone_limit {
                        // A standalone event can contain one 18 KiB wire window and at most
                        // one rustls record carry. Keep the owned Vec at its exact bound;
                        // BodyBuffer's unbudgeted geometric growth would retain 64 KiB.
                        if plaintext.capacity() == 0 {
                            plaintext.reserve_capacity(limit)?;
                        }
                    }
                    plaintext.extend(&buffer[..read], standalone_limit.unwrap_or(usize::MAX))?;
                }
                Err(error) if error.kind() == io::ErrorKind::WouldBlock => break,
                Err(error) => return Err(tls_io_error(false, "plaintext read", error)),
            }
        }
        Ok(())
    }

    fn drain_outbound_up_to(
        &mut self,
        ciphertext_limit: usize,
        output: &mut Vec<u8>,
    ) -> Result<(), Error> {
        while self.connection.wants_write() && output.len() < ciphertext_limit {
            let mut writer = CappedWriter::new(output, ciphertext_limit);
            let written = self.connection.write_tls(&mut writer).map_err(|_| {
                Error::tls(
                    TransportStage::Send,
                    TlsFailure::Io,
                    "native TLS record output failed",
                )
            })?;
            if written == 0 {
                break;
            }
        }
        Ok(())
    }

    fn take_outbound(&mut self) -> Result<Vec<u8>, Error> {
        let mut output = BoundedWriter::new(self.outbound_limit);
        while self.connection.wants_write() {
            let stage = if self.connection.is_handshaking() {
                TransportStage::Tls
            } else {
                TransportStage::Send
            };
            let written = self.connection.write_tls(&mut output).map_err(|_| {
                Error::tls(stage, TlsFailure::Io, "native TLS record output failed")
            })?;
            if written == 0 {
                break;
            }
        }
        Ok(output.into_inner())
    }
}

struct PendingPlaintext {
    bytes: Vec<u8>,
    offset: usize,
}

impl PendingPlaintext {
    fn remaining(&self) -> &[u8] {
        &self.bytes[self.offset..]
    }

    fn is_empty(&self) -> bool {
        self.offset == self.bytes.len()
    }
}

#[derive(Debug)]
pub(super) struct TlsProgress {
    pub(super) outbound: Vec<u8>,
    pub(super) plaintext: crate::body_budget::BodyBuffer,
    pub(super) handshake_complete: bool,
    pub(super) peer_closed: bool,
}

#[derive(Debug)]
pub(super) struct TlsStreamProgress {
    pub(super) outbound: Vec<u8>,
    pub(super) handshake_complete: bool,
    pub(super) peer_closed: bool,
}

pub(super) struct TlsWriteProgress {
    pub(super) outbound: Vec<u8>,
    pub(super) consumed_body: usize,
}

impl NativeTls {
    pub(super) fn set_body_budget(&mut self, budget: Option<Arc<crate::body_budget::BodyBudget>>) {
        self.session
            .as_mut()
            .expect("TLS session owned before exchange")
            .body_budget = budget;
    }
    #[cfg(test)]
    pub(super) fn request_plaintext_capacity(&self) -> usize {
        self.request
            .as_ref()
            .map_or(0, |request| request.bytes.capacity())
    }

    pub(super) fn start(&mut self) -> Result<Vec<u8>, Error> {
        self.session
            .as_mut()
            .expect("TLS session owned at start")
            .take_outbound()
    }

    pub(super) fn receive(&mut self, encrypted: &[u8]) -> Result<TlsProgress, Error> {
        self.session
            .as_mut()
            .expect("TLS receive owns session")
            .receive(encrypted)
    }

    pub(super) fn take_handshake(&mut self) -> Option<TlsSession> {
        if self.is_handshaking() {
            self.session.take()
        } else {
            None
        }
    }

    pub(super) fn restore_handshake(&mut self, session: TlsSession) {
        debug_assert!(self.session.is_none());
        self.session = Some(session);
    }

    pub(super) fn handshake_in_worker(&self) -> bool {
        self.session.is_none()
    }

    /// Consumes one bounded encrypted streaming window and retains any resulting application
    /// plaintext until the HTTP owner explicitly consumes it.
    ///
    /// Buffered responses may drain a large reactor event in one pass. Streaming responses must
    /// not accept a second window until reader backpressure has released all plaintext from the
    /// first.
    pub(super) fn receive_streaming(
        &mut self,
        encrypted: &[u8],
    ) -> Result<TlsStreamProgress, Error> {
        if !self.retained_response.is_empty() {
            return Err(Error::new(
                ErrorKind::Internal,
                "native TLS accepted another streaming window before retained plaintext drained",
            ));
        }
        if encrypted.len() > TLS_STREAM_WIRE_ALLOWANCE {
            return Err(Error::new(
                ErrorKind::Internal,
                "native TLS streaming input exceeded its advertised socket allowance",
            ));
        }
        let progress = self.receive(encrypted)?;
        self.retain_stream_progress(progress)
    }

    pub(super) fn retain_stream_progress(
        &mut self,
        progress: TlsProgress,
    ) -> Result<TlsStreamProgress, Error> {
        if !self.retained_response.is_empty() {
            return Err(Error::new(
                ErrorKind::Internal,
                "TLS streaming plaintext was not drained",
            ));
        }
        if progress.plaintext.len() > TLS_STREAM_PLAINTEXT_LIMIT {
            return Err(Error::new(
                ErrorKind::Internal,
                "native TLS produced more streaming plaintext than its bounded input window",
            ));
        }
        self.retained_response = PendingPlaintext {
            bytes: progress.plaintext.into_vec(),
            offset: 0,
        };
        Ok(TlsStreamProgress {
            outbound: progress.outbound,
            handshake_complete: progress.handshake_complete,
            peer_closed: progress.peer_closed,
        })
    }

    /// Returns the absolute encrypted read allowance for the next streaming socket pass.
    pub(super) fn streaming_read_allowance(&self, response_capacity: usize) -> usize {
        if self.session.is_none()
            || !self.retained_response.is_empty()
            || (!self.is_handshaking() && response_capacity == 0)
        {
            0
        } else {
            TLS_STREAM_WIRE_ALLOWANCE
        }
    }

    pub(super) fn retained_plaintext(&self) -> &[u8] {
        self.retained_response.remaining()
    }

    pub(super) fn consume_retained_plaintext(&mut self, consumed: usize) -> Result<(), Error> {
        if consumed > self.retained_response.remaining().len() {
            return Err(Error::new(
                ErrorKind::Internal,
                "native HTTP consumed beyond retained TLS plaintext",
            ));
        }
        self.retained_response.offset += consumed;
        if self.retained_response.is_empty() {
            // The next receive supplies a new Vec; this empty allocation cannot be reused.
            self.retained_response.bytes = Vec::new();
            self.retained_response.offset = 0;
        }
        Ok(())
    }

    pub(super) fn is_handshaking(&self) -> bool {
        self.session
            .as_ref()
            .is_none_or(|session| session.connection.is_handshaking())
    }

    pub(super) fn begin_request(&mut self, request: Vec<u8>) -> Result<(), Error> {
        if self.is_handshaking() {
            return Err(Error::new(
                ErrorKind::Internal,
                "native TLS tried to reuse a connection before its handshake completed",
            ));
        }
        if self.request.is_some()
            || self
                .session
                .as_ref()
                .expect("established TLS")
                .connection
                .wants_write()
        {
            return Err(Error::new(
                ErrorKind::Internal,
                "native TLS tried to begin a request while prior output remained",
            ));
        }
        self.request = Some(PendingPlaintext {
            bytes: request,
            offset: 0,
        });
        Ok(())
    }

    #[cfg(test)]
    fn pump_request(&mut self, ciphertext_limit: usize) -> Result<Vec<u8>, Error> {
        self.pump_request_body(&[], ciphertext_limit)
            .map(|progress| progress.outbound)
    }

    /// Encrypts queued headers/upload chunks before borrowing buffered body bytes. The caller
    /// advances its body cursor by exactly consumed_body; TLS never owns a copy of that body.
    pub(super) fn pump_request_body(
        &mut self,
        body: &[u8],
        ciphertext_limit: usize,
    ) -> Result<TlsWriteProgress, Error> {
        if self.is_handshaking() || ciphertext_limit == 0 {
            return Ok(TlsWriteProgress {
                outbound: Vec::new(),
                consumed_body: 0,
            });
        }
        let session = self.session.as_mut().expect("established TLS");
        let mut output = Vec::new();
        let mut consumed_body = 0;
        session.drain_outbound_up_to(ciphertext_limit, &mut output)?;
        while output.len() < ciphertext_limit {
            if session.connection.wants_write() {
                break;
            }
            if self
                .request
                .as_ref()
                .is_some_and(PendingPlaintext::is_empty)
            {
                self.request = None;
            }
            let head = self
                .request
                .as_ref()
                .map_or(&[][..], PendingPlaintext::remaining);
            let head_count = head.len().min(TLS_PLAINTEXT_CHUNK);
            let body_count = (body.len() - consumed_body).min(TLS_PLAINTEXT_CHUNK - head_count);
            if head_count == 0 && body_count == 0 {
                break;
            }
            let head = &head[..head_count];
            let body_chunk = &body[consumed_body..consumed_body + body_count];
            let mut writer = session.connection.writer();
            // Preserve a single TLS record across the head/body boundary without assembling a
            // second plaintext buffer. rustls consumes these borrowed slices synchronously.
            let written = match (head_count, body_count) {
                (0, _) => writer.write(body_chunk),
                (_, 0) => writer.write(head),
                _ => writer.write_vectored(&[io::IoSlice::new(head), io::IoSlice::new(body_chunk)]),
            }
            .map_err(|_| {
                Error::tls(
                    TransportStage::Send,
                    TlsFailure::Io,
                    "native TLS request encryption failed",
                )
            })?;
            if written == 0 {
                return Err(Error::new(
                    ErrorKind::Internal,
                    "native TLS made no progress while accepting request plaintext",
                ));
            }
            if let Some(request) = self.request.as_mut() {
                request.offset += written.min(head_count);
            }
            consumed_body += written.saturating_sub(head_count);
            session.drain_outbound_up_to(ciphertext_limit, &mut output)?;
        }
        if self
            .request
            .as_ref()
            .is_some_and(|request| request.offset == request.bytes.len())
            && !session.connection.wants_write()
        {
            self.request = None;
        }
        Ok(TlsWriteProgress {
            outbound: output,
            consumed_body,
        })
    }

    pub(super) fn request_fully_encrypted(&self) -> bool {
        self.request.is_none()
            && self
                .session
                .as_ref()
                .is_some_and(|session| !session.connection.wants_write())
    }
}

pub(super) const fn encrypted_outbound_limit() -> usize {
    TLS_FLIGHT_LIMIT
}

pub(super) fn encrypted_receive_limit(plaintext_bytes: usize) -> usize {
    plaintext_bytes.saturating_add(TLS_FLIGHT_LIMIT)
}

struct BoundedWriter {
    bytes: Vec<u8>,
    limit: usize,
}

struct CappedWriter<'a> {
    bytes: &'a mut Vec<u8>,
    limit: usize,
}

impl<'a> CappedWriter<'a> {
    fn new(bytes: &'a mut Vec<u8>, limit: usize) -> Self {
        Self { bytes, limit }
    }
}

impl Write for CappedWriter<'_> {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        let available = self.limit.saturating_sub(self.bytes.len());
        let accepted = available.min(bytes.len());
        self.bytes.extend_from_slice(&bytes[..accepted]);
        Ok(accepted)
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

impl BoundedWriter {
    fn new(limit: usize) -> Self {
        Self {
            bytes: if limit == STANDALONE_TLS_OUTPUT_LIMIT {
                exact_capacity_buffer(limit)
            } else {
                Vec::new()
            },
            limit,
        }
    }

    fn into_inner(self) -> Vec<u8> {
        self.bytes
    }
}

fn exact_capacity_buffer(capacity: usize) -> Vec<u8> {
    let mut bytes = vec![0; capacity].into_boxed_slice().into_vec();
    bytes.clear();
    bytes
}

impl Write for BoundedWriter {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        let next = self
            .bytes
            .len()
            .checked_add(bytes.len())
            .ok_or_else(|| io::Error::other("native TLS flight length overflow"))?;
        if next > self.limit {
            return Err(io::Error::other(
                "native TLS flight exceeds the private buffer limit",
            ));
        }
        self.bytes.extend_from_slice(bytes);
        Ok(bytes.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

#[derive(Debug)]
struct NoCertificateVerification {
    algorithms: WebPkiSupportedAlgorithms,
}

impl ServerCertVerifier for NoCertificateVerification {
    fn verify_server_cert(
        &self,
        _end_entity: &CertificateDer<'_>,
        _intermediates: &[CertificateDer<'_>],
        _server_name: &ServerName<'_>,
        _ocsp_response: &[u8],
        _now: UnixTime,
    ) -> Result<ServerCertVerified, rustls::Error> {
        Ok(ServerCertVerified::assertion())
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        verify_tls12_signature(message, cert, dss, &self.algorithms)
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        verify_tls13_signature(message, cert, dss, &self.algorithms)
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        self.algorithms.supported_schemes()
    }
}

#[cfg(test)]
#[derive(Debug)]
struct GatedVerification {
    inner: Arc<dyn ServerCertVerifier>,
    gates: Mutex<VecDeque<(Sender<()>, Receiver<()>)>>,
}

#[cfg(test)]
impl ServerCertVerifier for GatedVerification {
    fn verify_server_cert(
        &self,
        end_entity: &CertificateDer<'_>,
        intermediates: &[CertificateDer<'_>],
        server_name: &ServerName<'_>,
        ocsp_response: &[u8],
        now: UnixTime,
    ) -> Result<ServerCertVerified, rustls::Error> {
        let gate = self
            .gates
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .pop_front();
        if let Some((entered, release)) = gate {
            let _ignored = entered.send(());
            let _ignored = release.recv_timeout(Duration::from_secs(10));
        }
        self.inner
            .verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls12_signature(message, cert, dss)
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls13_signature(message, cert, dss)
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        self.inner.supported_verify_schemes()
    }
}

fn tls_config_error(operation: &str, _error: impl fmt::Display) -> Error {
    Error::tls(
        TransportStage::Tls,
        TlsFailure::Configuration,
        format!("native TLS {operation} configuration failed"),
    )
}

fn tls_io_error(handshaking: bool, operation: &str, _error: io::Error) -> Error {
    let stage = if handshaking {
        TransportStage::Tls
    } else {
        TransportStage::Receive
    };
    Error::tls(
        stage,
        TlsFailure::Io,
        format!("native TLS {operation} failed"),
    )
}

fn classify_rustls_error(error: &RustlsError) -> TlsFailure {
    match error {
        RustlsError::InvalidCertificate(error) => classify_certificate_error(error),
        RustlsError::NoCertificatesPresented | RustlsError::UnsupportedNameType => {
            TlsFailure::CertificateInvalid
        }
        RustlsError::AlertReceived(_) => TlsFailure::PeerAlert,
        RustlsError::InappropriateMessage { .. }
        | RustlsError::InappropriateHandshakeMessage { .. }
        | RustlsError::InvalidEncryptedClientHello(_)
        | RustlsError::InvalidMessage(_)
        | RustlsError::DecryptError
        | RustlsError::EncryptError
        | RustlsError::PeerIncompatible(_)
        | RustlsError::PeerMisbehaved(_)
        | RustlsError::HandshakeNotComplete
        | RustlsError::PeerSentOversizedRecord
        | RustlsError::NoApplicationProtocol
        | RustlsError::BadMaxFragmentSize
        | RustlsError::InconsistentKeys(_) => TlsFailure::Protocol,
        _ => TlsFailure::Unknown,
    }
}

fn classify_certificate_error(error: &CertificateError) -> TlsFailure {
    match error {
        CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. } => {
            TlsFailure::CertificateHostnameMismatch
        }
        CertificateError::UnknownIssuer => TlsFailure::CertificateUnknownIssuer,
        CertificateError::Expired | CertificateError::ExpiredContext { .. } => {
            TlsFailure::CertificateExpired
        }
        CertificateError::NotValidYet | CertificateError::NotValidYetContext { .. } => {
            TlsFailure::CertificateNotYetValid
        }
        CertificateError::Revoked => TlsFailure::CertificateRevoked,
        _ => TlsFailure::CertificateInvalid,
    }
}

fn tls_handshake_flight_limit() -> Error {
    Error::new(
        ErrorKind::Limit,
        "the native TLS peer handshake exceeded its private wire budget",
    )
}

#[cfg(test)]
mod tests {
    use rustls::ServerConfig;
    use rustls::ServerConnection;
    use rustls::pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer};

    use rcgen::{CertificateParams, DnType, KeyPair, date_time_ymd};

    use super::*;

    #[test]
    fn standalone_output_writers_keep_actual_capacity_within_flight_bounds() {
        let mut writer = BoundedWriter::new(STANDALONE_TLS_OUTPUT_LIMIT);
        writer
            .write_all(&vec![0; 40 * 1024])
            .expect("first TLS flight part");
        writer
            .write_all(&vec![0; 20 * 1024])
            .expect("second TLS flight part");
        assert_eq!(writer.bytes.len(), 60 * 1024);
        assert_eq!(writer.bytes.capacity(), STANDALONE_TLS_OUTPUT_LIMIT);

        let mut output = exact_capacity_buffer(STANDALONE_TLS_WIRE_WINDOW);
        let mut capped = CappedWriter::new(&mut output, STANDALONE_TLS_WIRE_WINDOW);
        capped
            .write_all(&vec![0; 10 * 1024])
            .expect("first record fragment");
        capped
            .write_all(&vec![0; 7 * 1024])
            .expect("second record fragment");
        assert_eq!(output.capacity(), STANDALONE_TLS_WIRE_WINDOW);
    }

    fn identity() -> (CertificateDer<'static>, PrivateKeyDer<'static>) {
        identity_for("resolved.test", false)
    }

    fn identity_for(
        host: &str,
        expired: bool,
    ) -> (CertificateDer<'static>, PrivateKeyDer<'static>) {
        let key = KeyPair::generate().expect("TLS test key must generate");
        let mut params =
            CertificateParams::new(vec![host.to_owned()]).expect("TLS test parameters must build");
        params.distinguished_name.push(DnType::CommonName, host);
        if expired {
            params.not_before = date_time_ymd(2010, 1, 1);
            params.not_after = date_time_ymd(2011, 1, 1);
        }
        let cert = params
            .self_signed(&key)
            .expect("TLS test certificate must sign");
        (
            cert.der().clone(),
            PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.serialize_der())),
        )
    }

    fn server_config(
        cert: CertificateDer<'static>,
        key: PrivateKeyDer<'static>,
    ) -> Arc<ServerConfig> {
        let mut config =
            ServerConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
                .with_safe_default_protocol_versions()
                .expect("TLS server versions must configure")
                .with_no_client_auth()
                .with_single_cert(vec![cert], key)
                .expect("TLS server identity must configure");
        config.alpn_protocols = vec![b"http/1.1".to_vec()];
        Arc::new(config)
    }

    fn first_server_flight(
        client: &mut NativeTls,
        cert: CertificateDer<'static>,
        key: PrivateKeyDer<'static>,
    ) -> Result<TlsProgress, Error> {
        let mut server =
            ServerConnection::new(server_config(cert, key)).expect("TLS server state must build");
        let client_hello = client.start().expect("ClientHello must encode");
        server
            .read_tls(&mut Cursor::new(client_hello))
            .expect("server ClientHello must read");
        server
            .process_new_packets()
            .expect("server ClientHello must process");
        let mut server_flight = Vec::new();
        while server.wants_write() {
            server
                .write_tls(&mut server_flight)
                .expect("server flight must encode");
        }
        client.receive(&server_flight)
    }

    #[test]
    fn m24_consumed_stream_plaintext_releases_storage_without_losing_partial_bytes() {
        let (cert, _) = identity();
        let configs = NativeTlsConfigs::with_test_root(cert).expect("TLS configs");
        let mut client = configs
            .connection("resolved.test", TlsVerification::Verify, Vec::new())
            .expect("TLS state");
        let mut plaintext = Vec::with_capacity(TLS_STREAM_PLAINTEXT_LIMIT * 2);
        plaintext.extend((0..TLS_PLAINTEXT_CHUNK).map(|index| (index % 251) as u8));
        let pointer = plaintext.as_ptr();
        client
            .retain_stream_progress(TlsProgress {
                outbound: Vec::new(),
                plaintext: plaintext.into(),
                handshake_complete: true,
                peer_closed: false,
            })
            .expect("retain plaintext");
        client
            .consume_retained_plaintext(7)
            .expect("partial consumption");
        assert_eq!(
            client.retained_plaintext().as_ptr(),
            pointer.wrapping_add(7)
        );
        assert!(
            client
                .retained_plaintext()
                .iter()
                .enumerate()
                .all(|(index, byte)| *byte == ((index + 7) % 251) as u8)
        );
        client
            .consume_retained_plaintext(TLS_PLAINTEXT_CHUNK - 7)
            .expect("finish consumption");
        assert!(client.retained_plaintext().is_empty());
        assert_eq!(
            client.retained_response.bytes.capacity(),
            0,
            "the next TLS window replaces this Vec; retaining its empty storage buys no reuse"
        );
        client
            .consume_retained_plaintext(0)
            .expect("empty consumption is idempotent");
        client
            .retain_stream_progress(TlsProgress {
                outbound: Vec::new(),
                plaintext: b"next window".to_vec().into(),
                handshake_complete: true,
                peer_closed: false,
            })
            .expect("next plaintext window");
        assert!(client.consume_retained_plaintext(12).is_err());
        assert_eq!(
            client.retained_plaintext(),
            b"next window",
            "invalid consumption must preserve bytes"
        );
        client
            .consume_retained_plaintext(11)
            .expect("next window consumed");
        assert_eq!(client.retained_response.bytes.capacity(), 0);
    }

    #[test]
    fn verified_sans_io_handshake_encrypts_request_and_decrypts_response() {
        let (cert, key) = identity();
        let configs =
            NativeTlsConfigs::with_test_root(cert.clone()).expect("TLS client config must build");
        let mut client = configs
            .connection(
                "resolved.test",
                TlsVerification::Verify,
                b"GET / HTTP/1.1\r\nHost: resolved.test\r\n\r\n".to_vec(),
            )
            .expect("TLS client state must build");
        let mut server =
            ServerConnection::new(server_config(cert, key)).expect("TLS server state must build");
        let mut to_server = client.start().expect("ClientHello must encode");
        let mut received_request = Vec::new();
        let mut received_response = Vec::new();
        for _ in 0..16 {
            if !to_server.is_empty() {
                server
                    .read_tls(&mut Cursor::new(&to_server))
                    .expect("server TLS bytes must read");
                server
                    .process_new_packets()
                    .expect("server TLS packets must process");
                to_server.clear();
            }
            let mut plaintext = [0_u8; 1024];
            loop {
                match server.reader().read(&mut plaintext) {
                    Ok(0) => break,
                    Ok(read) => received_request.extend_from_slice(&plaintext[..read]),
                    Err(error) if error.kind() == io::ErrorKind::WouldBlock => break,
                    Err(error) => panic!("server plaintext read failed: {error}"),
                }
            }
            if received_request.ends_with(b"\r\n\r\n") {
                server
                    .writer()
                    .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")
                    .expect("server response must buffer");
            }
            let mut to_client = Vec::new();
            while server.wants_write() {
                server
                    .write_tls(&mut to_client)
                    .expect("server TLS bytes must encode");
            }
            if !to_client.is_empty() {
                let progress = client.receive(&to_client).expect("client TLS must advance");
                to_server = progress.outbound;
                received_response.extend_from_slice(&progress.plaintext);
            }
            if !client.is_handshaking() {
                to_server.extend(
                    client
                        .pump_request(TLS_FLIGHT_LIMIT)
                        .expect("client request plaintext must pump"),
                );
            }
            if received_response.ends_with(b"ok") {
                break;
            }
        }
        assert!(received_request.starts_with(b"GET / HTTP/1.1\r\n"));
        assert!(received_response.ends_with(b"\r\n\r\nok"));
        assert!(!client.is_handshaking());
    }

    #[test]
    fn incremental_request_pump_caps_each_ciphertext_batch() {
        const PUMP_BUDGET: usize = 32 * 1024;
        let request = vec![b'x'; TLS_FLIGHT_LIMIT * 2 + 123];
        let (cert, key) = identity();
        let configs =
            NativeTlsConfigs::with_test_root(cert.clone()).expect("TLS client config must build");
        let mut client = configs
            .connection("resolved.test", TlsVerification::Verify, request.clone())
            .expect("TLS client state must build");
        let mut server =
            ServerConnection::new(server_config(cert, key)).expect("TLS server state must build");
        let mut to_server = client.start().expect("ClientHello must encode");
        let mut received = Vec::new();

        for _ in 0..256 {
            if !to_server.is_empty() {
                let mut input = Cursor::new(&to_server);
                while usize::try_from(input.position()).unwrap_or(usize::MAX) < to_server.len() {
                    let consumed = server
                        .read_tls(&mut input)
                        .expect("server TLS bytes must read");
                    assert_ne!(consumed, 0, "server TLS input must make progress");
                    server
                        .process_new_packets()
                        .expect("server TLS packets must process");
                    let mut plaintext = [0_u8; TLS_PLAINTEXT_CHUNK];
                    loop {
                        match server.reader().read(&mut plaintext) {
                            Ok(0) => break,
                            Ok(read) => received.extend_from_slice(&plaintext[..read]),
                            Err(error) if error.kind() == io::ErrorKind::WouldBlock => break,
                            Err(error) => panic!("server request plaintext failed: {error}"),
                        }
                    }
                }
                to_server.clear();
            }
            if received == request {
                break;
            }
            let mut to_client = Vec::new();
            while server.wants_write() {
                server
                    .write_tls(&mut to_client)
                    .expect("server handshake bytes must encode");
            }
            if !to_client.is_empty() {
                let progress = client.receive(&to_client).expect("client TLS must advance");
                to_server.extend(progress.outbound);
            }
            if !client.is_handshaking() {
                let pumped = client
                    .pump_request(PUMP_BUDGET)
                    .expect("request ciphertext must pump");
                assert!(
                    pumped.len() <= PUMP_BUDGET,
                    "one pump exceeded its ciphertext budget"
                );
                to_server.extend(pumped);
            }
        }

        assert_eq!(received, request);
        assert!(client.request_fully_encrypted());
    }

    #[test]
    fn m23_small_borrowed_request_preserves_one_tls_record() {
        let (cert, key) = identity();
        let configs = NativeTlsConfigs::with_test_root(cert.clone()).expect("client config");
        let mut client = configs
            .connection("resolved.test", TlsVerification::Verify, Vec::new())
            .expect("client");
        let mut server = ServerConnection::new(server_config(cert, key)).expect("server");
        let mut to_server = client.start().expect("ClientHello");
        for _ in 0..16 {
            if !to_server.is_empty() {
                server
                    .read_tls(&mut Cursor::new(&to_server))
                    .expect("server handshake input");
                server
                    .process_new_packets()
                    .expect("server handshake packets");
                to_server.clear();
            }
            let mut to_client = Vec::new();
            while server.wants_write() {
                server
                    .write_tls(&mut to_client)
                    .expect("server handshake output");
            }
            if to_client.is_empty() && !client.is_handshaking() && !server.is_handshaking() {
                break;
            }
            if !to_client.is_empty() {
                to_server = client
                    .receive(&to_client)
                    .expect("client handshake")
                    .outbound;
            }
        }
        assert!(!client.is_handshaking() && !server.is_handshaking());
        assert!(
            client
                .pump_request(TLS_FLIGHT_LIMIT)
                .expect("empty initial output")
                .is_empty()
        );
        let head = b"POST / HTTP/1.1\r\nHost: resolved.test\r\nContent-Length: 1024\r\n\r\n";
        client.begin_request(head.to_vec()).expect("request head");
        let body = vec![0x5a; 1024];
        let progress = client
            .pump_request_body(&body, TLS_FLIGHT_LIMIT)
            .expect("small request");
        assert_eq!(progress.consumed_body, body.len());
        let mut wire = progress.outbound.as_slice();
        let mut records = 0;
        while !wire.is_empty() {
            assert!(wire.len() >= 5, "complete TLS record header");
            assert_eq!(wire[0], 23, "application-data record");
            let length = usize::from(u16::from_be_bytes([wire[3], wire[4]]));
            assert!(wire.len() >= 5 + length, "complete TLS record");
            wire = &wire[5 + length..];
            records += 1;
        }
        assert_eq!(
            records, 1,
            "separate header/body ownership must not fragment a small request into extra TLS records"
        );
    }

    #[test]
    fn m23_borrowed_body_progress_survives_tiny_ciphertext_windows_and_reuse() {
        let (cert, key) = identity();
        let configs = NativeTlsConfigs::with_test_root(cert.clone()).expect("client config");
        let head = b"POST /borrowed HTTP/1.1\r\nHost: resolved.test\r\n\r\n";
        let mut client = configs
            .connection("resolved.test", TlsVerification::Verify, head.to_vec())
            .expect("client");
        let mut server = ServerConnection::new(server_config(cert, key)).expect("server");
        let mut to_server = client.start().expect("ClientHello");
        for size in [128 * 1024 + 137, 50 * 1024, 0] {
            let body = (0..size)
                .map(|index| (index % 251) as u8)
                .collect::<Vec<_>>();
            let mut consumed = 0;
            let mut received = Vec::new();
            for iteration in 0..2048 {
                if !to_server.is_empty() {
                    let mut input = Cursor::new(&to_server);
                    while usize::try_from(input.position()).expect("position") < to_server.len() {
                        assert_ne!(server.read_tls(&mut input).expect("TLS input"), 0);
                        server.process_new_packets().expect("server packets");
                        let mut chunk = [0; 997];
                        loop {
                            match server.reader().read(&mut chunk) {
                                Ok(0) => break,
                                Ok(count) => received.extend_from_slice(&chunk[..count]),
                                Err(error) if error.kind() == io::ErrorKind::WouldBlock => break,
                                Err(error) => panic!("server plaintext: {error}"),
                            }
                        }
                    }
                    to_server.clear();
                }
                if received.len() == head.len() + body.len() {
                    break;
                }
                let mut to_client = Vec::new();
                while server.wants_write() {
                    server.write_tls(&mut to_client).expect("server output");
                }
                if !to_client.is_empty() {
                    to_server.extend(client.receive(&to_client).expect("client packets").outbound);
                }
                let limit = [0, 1, 7, 31, 4093, 16384][iteration % 6];
                let was_handshaking = client.is_handshaking();
                let progress = client
                    .pump_request_body(&body[consumed..], limit)
                    .expect("borrowed pump");
                assert!(progress.outbound.len() <= limit);
                assert!(progress.consumed_body <= body.len() - consumed);
                if limit == 0 || was_handshaking {
                    assert_eq!(progress.consumed_body, 0);
                }
                consumed += progress.consumed_body;
                assert!(client.request_plaintext_capacity() <= head.len());
                to_server.extend(progress.outbound);
            }
            assert_eq!(consumed, body.len());
            assert_eq!(&received[..head.len()], head);
            assert_eq!(&received[head.len()..], body);
            assert!(client.request_fully_encrypted());
            client
                .begin_request(head.to_vec())
                .expect("reusable TLS session");
        }
    }

    #[test]
    fn verified_wrong_host_fails_but_explicit_bypass_still_handshakes() {
        let (cert, key) = identity();
        let configs =
            NativeTlsConfigs::with_test_root(cert.clone()).expect("TLS client config must build");
        for (policy, should_succeed) in [
            (TlsVerification::Verify, false),
            (
                TlsVerification::DangerouslyDisableCertificateVerification,
                true,
            ),
        ] {
            let mut client = configs
                .connection("wrong.test", policy, Vec::new())
                .expect("TLS client state must build");
            let mut server = ServerConnection::new(server_config(cert.clone(), key.clone_key()))
                .expect("TLS server state must build");
            let client_hello = client.start().expect("ClientHello must encode");
            server
                .read_tls(&mut Cursor::new(client_hello))
                .expect("server ClientHello must read");
            server
                .process_new_packets()
                .expect("server ClientHello must process");
            let mut server_flight = Vec::new();
            while server.wants_write() {
                server
                    .write_tls(&mut server_flight)
                    .expect("server flight must encode");
            }
            let result = client.receive(&server_flight);
            if should_succeed {
                assert!(result.is_ok());
            } else {
                let error = result.expect_err("verified wrong host must fail");
                assert_eq!(error.transport_stage(), Some(TransportStage::Tls));
                assert_eq!(
                    error.tls_failure(),
                    Some(TlsFailure::CertificateHostnameMismatch)
                );
                assert_eq!(error.message(), "native TLS packet processing failed");
                assert!(!error.message().contains("wrong.test"));
                assert!(!error.message().contains("resolved.test"));
            }
        }
    }

    #[test]
    fn platform_verifier_config_constructs_without_global_provider_state() {
        NativeTlsConfigs::platform().expect("platform TLS configuration must construct");
    }

    #[test]
    fn verified_unknown_root_and_expired_certificate_fail_at_tls() {
        let (trusted, _) = identity_for("trusted-root.test", false);
        let configs = NativeTlsConfigs::with_test_root(trusted)
            .expect("trusted TLS client config must build");

        let (unknown, unknown_key) = identity_for("resolved.test", false);
        let mut unknown_client = configs
            .connection("resolved.test", TlsVerification::Verify, Vec::new())
            .expect("unknown-root client state must build");
        let unknown_error = first_server_flight(&mut unknown_client, unknown, unknown_key)
            .expect_err("unknown root must fail");
        assert_eq!(unknown_error.transport_stage(), Some(TransportStage::Tls));
        assert_eq!(
            unknown_error.tls_failure(),
            Some(TlsFailure::CertificateUnknownIssuer)
        );
        assert_eq!(
            unknown_error.message(),
            "native TLS packet processing failed"
        );

        let (expired, expired_key) = identity_for("resolved.test", true);
        let expired_configs = NativeTlsConfigs::with_test_root(expired.clone())
            .expect("expired-root client config must build");
        let mut expired_client = expired_configs
            .connection("resolved.test", TlsVerification::Verify, Vec::new())
            .expect("expired client state must build");
        let expired_error = first_server_flight(&mut expired_client, expired, expired_key)
            .expect_err("expired certificate must fail");
        assert_eq!(expired_error.transport_stage(), Some(TransportStage::Tls));
        assert_eq!(
            expired_error.tls_failure(),
            Some(TlsFailure::CertificateExpired)
        );
        assert_eq!(
            expired_error.message(),
            "native TLS packet processing failed"
        );
    }

    #[test]
    fn explicit_peer_alert_is_a_tls_stage_failure() {
        let (cert, _) = identity();
        let configs = NativeTlsConfigs::with_test_root(cert).expect("TLS client config must build");
        let mut client = configs
            .connection("resolved.test", TlsVerification::Verify, Vec::new())
            .expect("TLS client state must build");
        let _client_hello = client.start().expect("ClientHello must encode");

        // A plaintext TLS alert is permitted before encrypted handshake traffic begins.
        let alert = [21, 3, 3, 0, 2, 2, 40];
        let error = client
            .receive(&alert)
            .expect_err("peer handshake alert must fail");
        assert_eq!(error.kind(), ErrorKind::Transport);
        assert_eq!(error.transport_stage(), Some(TransportStage::Tls));
        assert_eq!(error.tls_failure(), Some(TlsFailure::PeerAlert));
    }

    #[test]
    fn incoming_and_outgoing_tls_flights_are_bounded_before_growth() {
        let mut writer = BoundedWriter::new(4);
        writer.write_all(b"four").expect("bounded write must fit");
        assert_eq!(writer.bytes.len(), 4);
        let error = writer
            .write_all(b"x")
            .expect_err("bounded writer must reject overflow");
        assert_eq!(error.kind(), io::ErrorKind::Other);
        assert_eq!(writer.bytes.len(), 4);

        let (cert, _) = identity();
        let configs = NativeTlsConfigs::with_test_root(cert).expect("TLS client config must build");
        let mut client = configs
            .connection("resolved.test", TlsVerification::Verify, Vec::new())
            .expect("TLS client state must build");
        let _client_hello = client.start().expect("ClientHello must encode");
        let oversized = vec![0_u8; TLS_FLIGHT_LIMIT + 1];
        let error = client
            .receive(&oversized)
            .expect_err("oversized peer handshake must fail before rustls input");
        assert_eq!(error.kind(), ErrorKind::Limit);
        assert_eq!(
            client
                .session
                .as_ref()
                .expect("TLS session")
                .handshake_received,
            TLS_FLIGHT_LIMIT + 1
        );
    }

    #[test]
    fn one_reactor_event_can_contain_more_tls_records_than_rustls_buffers_at_once() {
        let (cert, key) = identity();
        let configs =
            NativeTlsConfigs::with_test_root(cert.clone()).expect("TLS client config must build");
        let mut client = configs
            .connection("resolved.test", TlsVerification::Verify, Vec::new())
            .expect("TLS client state must build");
        let mut server =
            ServerConnection::new(server_config(cert, key)).expect("TLS server state must build");
        let mut to_server = client.start().expect("ClientHello must encode");
        for _ in 0..16 {
            if !to_server.is_empty() {
                server
                    .read_tls(&mut Cursor::new(&to_server))
                    .expect("server handshake bytes must read");
                server
                    .process_new_packets()
                    .expect("server handshake bytes must process");
            }
            let mut to_client = Vec::new();
            while server.wants_write() {
                server
                    .write_tls(&mut to_client)
                    .expect("server handshake flight must encode");
            }
            if to_client.is_empty() {
                if !client.is_handshaking() && !server.is_handshaking() {
                    break;
                }
                continue;
            }
            to_server = client
                .receive(&to_client)
                .expect("client handshake must advance")
                .outbound;
        }
        assert!(!client.is_handshaking());
        assert!(!server.is_handshaking());

        let expected = vec![b'x'; 128 * 1024];
        let mut event = Vec::new();
        for chunk in expected.chunks(TLS_PLAINTEXT_CHUNK) {
            server
                .writer()
                .write_all(chunk)
                .expect("server plaintext chunk must buffer");
            while server.wants_write() {
                server
                    .write_tls(&mut event)
                    .expect("server records must encode");
            }
        }
        let progress = client
            .receive(&event)
            .expect("one multi-record reactor event must be fully consumed");
        assert_eq!(progress.plaintext, expected);
    }

    #[test]
    fn streaming_tls_retains_one_bounded_wire_window_before_reopening_reads() {
        assert_streaming_windows(64 * 1024);
    }

    #[test]
    fn streaming_tls_partial_record_carry_can_finish_two_records_in_one_window() {
        // Four 16 KiB records never build enough wire-boundary drift to finish two records
        // in one 18 KiB read. A longer stream reaches that valid record split repeatedly.
        assert_streaming_windows(512 * 1024);
    }

    fn assert_streaming_windows(body_bytes: usize) {
        let (cert, key) = identity();
        let configs =
            NativeTlsConfigs::with_test_root(cert.clone()).expect("TLS client config must build");
        let mut client = configs
            .connection("resolved.test", TlsVerification::Verify, Vec::new())
            .expect("TLS client state must build");
        let mut server =
            ServerConnection::new(server_config(cert, key)).expect("TLS server state must build");
        let mut to_server = client.start().expect("ClientHello must encode");
        for _ in 0..16 {
            if !to_server.is_empty() {
                server
                    .read_tls(&mut Cursor::new(&to_server))
                    .expect("server handshake bytes must read");
                server
                    .process_new_packets()
                    .expect("server handshake bytes must process");
            }
            let mut to_client = Vec::new();
            while server.wants_write() {
                server
                    .write_tls(&mut to_client)
                    .expect("server handshake flight must encode");
            }
            if to_client.is_empty() {
                if !client.is_handshaking() && !server.is_handshaking() {
                    break;
                }
                continue;
            }
            to_server = client
                .receive(&to_client)
                .expect("client handshake must advance")
                .outbound;
        }
        assert!(!client.is_handshaking());
        assert!(!server.is_handshaking());

        let expected: Vec<u8> = (0..body_bytes).map(|index| (index % 251) as u8).collect();
        let mut encrypted = Vec::new();
        for chunk in expected.chunks(TLS_PLAINTEXT_CHUNK) {
            server
                .writer()
                .write_all(chunk)
                .expect("one server record must buffer");
            while server.wants_write() {
                server
                    .write_tls(&mut encrypted)
                    .expect("server records must encode");
            }
        }

        let mut received = Vec::new();
        let mut largest_plaintext = 0;
        for wire_window in encrypted.chunks(TLS_STREAM_WIRE_ALLOWANCE) {
            assert_eq!(
                client.streaming_read_allowance(100),
                TLS_STREAM_WIRE_ALLOWANCE,
                "an empty retained window must reopen exactly one bounded socket allowance"
            );
            let progress = client
                .receive_streaming(wire_window)
                .expect("bounded TLS window must decode");
            assert!(progress.outbound.is_empty());
            assert!(progress.handshake_complete);
            assert!(!progress.peer_closed);
            largest_plaintext = largest_plaintext.max(client.retained_plaintext().len());
            assert!(client.retained_plaintext().len() <= TLS_STREAM_PLAINTEXT_LIMIT);
            while !client.retained_plaintext().is_empty() {
                assert_eq!(
                    client.streaming_read_allowance(100),
                    0,
                    "retained plaintext must close the socket allowance"
                );
                let take = client.retained_plaintext().len().min(100);
                received.extend_from_slice(&client.retained_plaintext()[..take]);
                client
                    .consume_retained_plaintext(take)
                    .expect("retained plaintext consumption must stay in bounds");
            }
        }
        assert_eq!(received, expected);
        if body_bytes >= 512 * 1024 {
            assert!(
                largest_plaintext > TLS_STREAM_WIRE_ALLOWANCE,
                "the regression must exercise plaintext carried across wire windows"
            );
        }
        assert_eq!(client.streaming_read_allowance(0), 0);
        assert_eq!(
            client.streaming_read_allowance(1),
            TLS_STREAM_WIRE_ALLOWANCE
        );

        let oversized = vec![0_u8; TLS_STREAM_WIRE_ALLOWANCE + 1];
        let error = client
            .receive_streaming(&oversized)
            .expect_err("input above the advertised allowance must fail closed");
        assert_eq!(error.kind(), ErrorKind::Internal);
    }
}