asupersync 0.3.4

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

use super::error::TlsError;
use super::stream::TlsStream;
use super::types::{Certificate, CertificateChain, CertificatePinSet, PrivateKey, RootCertStore};
use crate::io::{AsyncRead, AsyncWrite};

#[cfg(feature = "tls")]
use rustls::ClientConfig;
#[cfg(feature = "tls")]
use rustls::ClientConnection;
#[cfg(feature = "tls")]
use rustls::pki_types::ServerName;

#[cfg(feature = "tls")]
use std::future::poll_fn;
use std::sync::Arc;

#[cfg(not(feature = "tls"))]
const TLS_FEATURE_HINT: &str = "rebuild with --features tls";

#[cfg(not(feature = "tls"))]
fn tls_feature_disabled(operation: &'static str) -> TlsError {
    TlsError::FeatureDisabled {
        operation,
        hint: TLS_FEATURE_HINT,
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
struct TlsCertificateLoadCounts {
    loaded: usize,
    rejected_non_ca: usize,
}

/// Client-side TLS connector.
///
/// This is typically configured once and reused for many connections.
/// Cloning is cheap (Arc-based).
///
/// # Example
///
/// ```ignore
/// let connector = TlsConnector::builder()
///     .with_webpki_roots()
///     .alpn_http()
///     .build()?;
///
/// let tls_stream = connector.connect("example.com", tcp_stream).await?;
/// ```
#[derive(Clone)]
pub struct TlsConnector {
    #[cfg(feature = "tls")]
    config: Arc<ClientConfig>,
    handshake_timeout: Option<std::time::Duration>,
    alpn_required: bool,
    /// br-asupersync-v24lvi: certificate-pinning set. When `Some`,
    /// `connect()` validates the peer leaf certificate against
    /// these pins after the rustls handshake completes; failure
    /// aborts the connection. `None` (the default) skips pinning
    /// — webpki / native roots remain the only check.
    pin_set: Option<Arc<CertificatePinSet>>,
    #[cfg(not(feature = "tls"))]
    _marker: std::marker::PhantomData<()>,
}

impl TlsConnector {
    /// Create a connector from a raw rustls `ClientConfig`.
    #[cfg(feature = "tls")]
    pub fn new(config: ClientConfig) -> Self {
        Self {
            config: Arc::new(config),
            handshake_timeout: None,
            alpn_required: false,
            pin_set: None,
        }
    }

    /// Create a builder for constructing a `TlsConnector`.
    pub fn builder() -> TlsConnectorBuilder {
        TlsConnectorBuilder::new()
    }

    /// Get the handshake timeout, if configured.
    #[must_use]
    pub fn handshake_timeout(&self) -> Option<std::time::Duration> {
        self.handshake_timeout
    }

    /// br-asupersync-m209nx — Attach a `CertificatePinSet` to a
    /// connector built from a raw `ClientConfig` (i.e., one that
    /// did not flow through `TlsConnectorBuilder::with_certificate_pins`).
    /// Useful for tests that need to combine a custom rustls
    /// `ClientConfig` (e.g., a permissive `ServerCertVerifier` for
    /// self-signed fixtures) with the v24lvi pinning gate; also
    /// useful for production callers that bring their own
    /// `ClientConfig` and want to layer pinning on top.
    #[cfg(feature = "tls")]
    #[must_use]
    pub fn with_pin_set(mut self, pin_set: CertificatePinSet) -> Self {
        self.pin_set = Some(Arc::new(pin_set));
        self
    }

    /// br-asupersync-m209nx — Attach a handshake timeout to a
    /// connector built from a raw `ClientConfig`. Mirrors the
    /// builder-side `TlsConnectorBuilder::handshake_timeout`.
    #[must_use]
    pub fn with_handshake_timeout(mut self, timeout: std::time::Duration) -> Self {
        self.handshake_timeout = Some(timeout);
        self
    }

    /// Get the inner configuration (for advanced use).
    #[cfg(feature = "tls")]
    pub fn config(&self) -> &Arc<ClientConfig> {
        &self.config
    }

    /// Establish a TLS connection over the provided I/O stream.
    ///
    /// # Cancel-Safety
    /// Handshake is NOT cancel-safe. If cancelled mid-handshake, drop the stream.
    #[cfg(feature = "tls")]
    pub async fn connect<IO>(&self, domain: &str, io: IO) -> Result<TlsStream<IO>, TlsError>
    where
        IO: AsyncRead + AsyncWrite + Unpin,
    {
        let server_name = ServerName::try_from(domain.to_string())
            .map_err(|_| TlsError::InvalidDnsName(domain.to_string()))?;
        let conn = ClientConnection::new(Arc::clone(&self.config), server_name)
            .map_err(|e| TlsError::Configuration(e.to_string()))?;
        let mut stream = TlsStream::new_client(io, conn);
        if let Some(timeout) = self.handshake_timeout {
            match crate::time::timeout(
                super::timeout_now(),
                timeout,
                poll_fn(|cx| stream.poll_handshake(cx)),
            )
            .await
            {
                Ok(result) => result?,
                Err(_) => return Err(TlsError::Timeout(timeout)),
            }
        } else {
            poll_fn(|cx| stream.poll_handshake(cx)).await?;
        }
        if self.alpn_required {
            let expected = self.config.alpn_protocols.clone();
            let negotiated = stream.alpn_protocol().map(<[u8]>::to_vec);
            let ok = negotiated
                .as_deref()
                .is_some_and(|p| expected.iter().any(|e| e.as_slice() == p));
            if !ok {
                return Err(TlsError::AlpnNegotiationFailed {
                    expected,
                    negotiated,
                });
            }
        }

        // br-asupersync-v24lvi: certificate-pinning enforcement.
        // After the rustls handshake completes (which validated the
        // chain against the configured root store), additionally
        // validate the peer leaf cert against the pinned hashes.
        // This catches CA-issued attack certs that would otherwise
        // pass webpki / native-roots validation. On enforcement
        // failure the stream is dropped immediately so no
        // application data flows over the un-pinned connection.
        if let Some(pin_set) = self.pin_set.as_ref() {
            let leaf_der = stream.peer_leaf_certificate_der().ok_or_else(|| {
                TlsError::Certificate(
                    "certificate-pinning enabled but peer presented no \
                     leaf certificate after handshake (br-asupersync-v24lvi)"
                        .to_string(),
                )
            })?;
            let leaf = Certificate::from_der(leaf_der);
            match pin_set.validate(&leaf) {
                Ok(true) => {
                    // Pin matched (or set was empty) — proceed.
                }
                Ok(false) => {
                    // Report-only mode: no match but enforcement
                    // disabled; let the connection through. The
                    // pin_set.validate impl already records the
                    // miss for diagnostic logging.
                }
                Err(err) => {
                    // Enforcement on + no match: abort the
                    // connection. Drop the stream explicitly so the
                    // FIN reaches the peer before we surface the
                    // error to the caller.
                    drop(stream);
                    return Err(err);
                }
            }
        }

        Ok(stream)
    }

    /// Establish a TLS connection (disabled-mode fallback when TLS is disabled).
    #[cfg(not(feature = "tls"))]
    pub async fn connect<IO>(&self, _domain: &str, _io: IO) -> Result<TlsStream<IO>, TlsError>
    where
        IO: AsyncRead + AsyncWrite + Unpin,
    {
        let _ = (self.alpn_required, self.pin_set.as_ref());
        Err(tls_feature_disabled("connect TLS stream"))
    }

    /// Validate a domain name for use with TLS.
    ///
    /// Returns an error if the domain is not a valid DNS name.
    #[cfg(feature = "tls")]
    pub fn validate_domain(domain: &str) -> Result<(), TlsError> {
        ServerName::try_from(domain.to_string())
            .map_err(|_| TlsError::InvalidDnsName(domain.to_string()))?;
        Ok(())
    }

    /// Validate a domain name for use with TLS (disabled-mode fallback when TLS is disabled).
    #[cfg(not(feature = "tls"))]
    pub fn validate_domain(domain: &str) -> Result<(), TlsError> {
        // Basic validation: not empty and no spaces
        if domain.is_empty() || domain.contains(' ') {
            return Err(TlsError::InvalidDnsName(domain.to_string()));
        }
        Ok(())
    }
}

impl std::fmt::Debug for TlsConnector {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TlsConnector").finish_non_exhaustive()
    }
}

/// Builder for `TlsConnector`.
///
/// # Example
///
/// ```ignore
/// let connector = TlsConnectorBuilder::new()
///     .with_native_roots()?
///     .alpn_protocols(vec![b"h2".to_vec(), b"http/1.1".to_vec()])
///     .build()?;
/// ```
#[derive(Debug, Default)]
pub struct TlsConnectorBuilder {
    root_certs: RootCertStore,
    client_identity: Option<(CertificateChain, PrivateKey)>,
    alpn_protocols: Vec<Vec<u8>>,
    alpn_required: bool,
    enable_sni: bool,
    handshake_timeout: Option<std::time::Duration>,
    /// br-asupersync-v24lvi: certificate-pinning set. See
    /// [`Self::with_certificate_pins`].
    pin_set: Option<CertificatePinSet>,
    /// br-asupersync-gq7l9i: when `true`, `with_native_roots` also
    /// honours `SSL_CERT_FILE` / `REQUESTS_CA_BUNDLE` / `CURL_CA_BUNDLE`
    /// / `SSL_CERT_DIR` env vars and adds every cert it finds as a
    /// trust anchor. Default is `false` — the env-var path is a known
    /// trust-injection vector in CI, container, and shared-host
    /// deployments, so callers must opt in via
    /// [`Self::enable_env_cert_loading`].
    enable_env_certs: bool,
    /// br-asupersync-p7369s: PEM-encoded CRL bodies the verifier will
    /// consult when validating the peer certificate chain. When
    /// non-empty, `build()` swaps the rustls default verifier for a
    /// `WebPkiServerVerifier` built with these CRLs.
    #[cfg(feature = "tls")]
    crl_pems: Vec<Vec<u8>>,
    #[cfg(feature = "tls")]
    min_protocol: Option<rustls::ProtocolVersion>,
    #[cfg(feature = "tls")]
    max_protocol: Option<rustls::ProtocolVersion>,
    #[cfg(feature = "tls")]
    resumption: Option<rustls::client::Resumption>,
    /// br-asupersync-y0gm5q: TLS 1.3 0-RTT (early data) opt-in on
    /// the client side. Defaults to `false` (matches rustls default
    /// and prevents accidental replay-vulnerable 0-RTT). See
    /// [`Self::enable_early_data`] for the explicit opt-in.
    early_data_enabled: bool,
    /// br-asupersync-h41wya — operator acknowledgement that combining
    /// session resumption with 0-RTT exposes the application to
    /// replay attacks on the early-data payload. When `false`,
    /// `build()` rejects the combination of `early_data_enabled =
    /// true` + non-disabled session resumption so a misconfiguration
    /// cannot ship by accident. The operator must call
    /// [`Self::acknowledge_zero_rtt_replay_risk`] to opt in,
    /// signalling that the application layer enforces idempotency
    /// for every request that could carry early data.
    acknowledge_zero_rtt_replay_risk: bool,
    /// br-asupersync-sx6j9y — when `true`, `add_root_certificate` and
    /// `add_root_certificates` apply the same `BasicConstraints
    /// CA:TRUE` gate that `enable_env_cert_loading` uses, instead of
    /// admitting any cert into the trust store. Set via
    /// [`Self::with_strict_ca_validation`]; automatically set as a
    /// side effect of [`Self::enable_env_cert_loading`].
    validate_ca_constraints: bool,
}

impl TlsConnectorBuilder {
    /// Create a new builder with default settings.
    ///
    /// By default:
    /// - No root certificates (you must add some)
    /// - No client certificate
    /// - No ALPN protocols
    /// - SNI enabled
    pub fn new() -> Self {
        Self {
            root_certs: RootCertStore::empty(),
            client_identity: None,
            alpn_protocols: Vec::new(),
            alpn_required: false,
            enable_sni: true,
            handshake_timeout: None,
            pin_set: None,
            enable_env_certs: false,
            #[cfg(feature = "tls")]
            crl_pems: Vec::new(),
            #[cfg(feature = "tls")]
            min_protocol: None,
            #[cfg(feature = "tls")]
            max_protocol: None,
            #[cfg(feature = "tls")]
            resumption: None,
            // br-asupersync-y0gm5q: secure-by-default. 0-RTT off
            // until the operator opts in via enable_early_data(true).
            early_data_enabled: false,
            // br-asupersync-h41wya: 0-RTT replay risk is unacknowledged
            // by default; build() rejects 0-RTT + resumption until the
            // operator calls acknowledge_zero_rtt_replay_risk().
            acknowledge_zero_rtt_replay_risk: false,
            // br-asupersync-sx6j9y: BasicConstraints CA:TRUE gate is
            // off by default for backward compat (tests use self-
            // signed leaf certs as roots). Production callers should
            // chain with_strict_ca_validation(); enable_env_cert_loading
            // also sets it as a side effect because env-loaded certs
            // are unconditionally CA-gated by br-asupersync-0owoem.
            validate_ca_constraints: false,
        }
    }

    /// Attach a [`CertificatePinSet`] for post-handshake leaf-cert
    /// validation.
    ///
    /// br-asupersync-v24lvi: when set, every connection produced by
    /// the resulting `TlsConnector` will, after the rustls handshake
    /// completes, extract the peer leaf certificate and call
    /// [`CertificatePinSet::validate`]. If validation fails AND the
    /// set is in enforcement mode, the handshake is rolled back —
    /// the stream is dropped before any application bytes flow.
    /// Report-only sets (`CertificatePinSet::report_only`) log the
    /// miss but allow the connection through.
    ///
    /// Pre-fix: `CertificatePinSet` existed in `tls/types.rs` but had
    /// no path into the connector handshake, so any caller who
    /// configured pins thought they were enforced when in fact
    /// rustls's CA-based validation was the only check.
    #[must_use]
    pub fn with_certificate_pins(mut self, pin_set: CertificatePinSet) -> Self {
        self.pin_set = Some(pin_set);
        self
    }

    /// Add platform/native root certificates.
    ///
    /// On Linux, this typically reads from /etc/ssl/certs.
    /// On macOS, this uses the system keychain.
    /// On Windows, this uses the Windows certificate store.
    ///
    /// # Environment-variable trust anchors (br-asupersync-gq7l9i)
    ///
    /// `with_native_roots` does **not** consult the OpenSSL-style
    /// `SSL_CERT_FILE`, `REQUESTS_CA_BUNDLE`, `CURL_CA_BUNDLE`, or
    /// `SSL_CERT_DIR` environment variables. Honouring those vars
    /// silently allows any process able to set the environment (a
    /// container layer, a CI step, a sibling shell user) to inject
    /// arbitrary CAs into the trust store — a known root cause of
    /// supply-chain attacks. Callers who knowingly need the corporate-
    /// proxy CA pickup must opt in by chaining
    /// [`enable_env_cert_loading`](Self::enable_env_cert_loading)
    /// before `with_native_roots`. When that flag is set, every file
    /// added from an env-var path is logged at `warn!` (not `debug!`)
    /// with the source path and rejected-vs-loaded count.
    ///
    /// Requires the `tls-native-roots` feature.
    #[cfg(feature = "tls-native-roots")]
    pub fn with_native_roots(mut self) -> Result<Self, TlsError> {
        let result = rustls_native_certs::load_native_certs();

        // Log any errors but continue with successfully loaded certs
        #[cfg(feature = "tracing-integration")]
        for err in &result.errors {
            tracing::warn!(error = %err, "Error loading native certificate");
        }

        for cert in result.certs {
            // Ignore individual cert add errors
            let _ = self.root_certs.add(&Certificate::from_der(cert.to_vec()));
        }

        #[cfg(feature = "tracing-integration")]
        tracing::debug!(
            count = self.root_certs.len(),
            "Loaded native root certificates"
        );

        // br-asupersync-gq7l9i: load custom CA certs from
        // SSL_CERT_FILE / SSL_CERT_DIR / REQUESTS_CA_BUNDLE /
        // CURL_CA_BUNDLE only when the caller has explicitly opted in.
        // Default is no — silent env-var trust injection is a known
        // supply-chain attack vector.
        if self.enable_env_certs {
            self.load_env_certs();
        }

        Ok(self)
    }

    /// Opt in to OpenSSL-style env-var trust-anchor loading
    /// (br-asupersync-gq7l9i).
    ///
    /// When enabled, the next call to
    /// [`with_native_roots`](Self::with_native_roots) will also read
    /// CA certs from these environment variables (in priority order):
    ///
    /// * `SSL_CERT_FILE` / `REQUESTS_CA_BUNDLE` / `CURL_CA_BUNDLE` —
    ///   a single PEM bundle file
    /// * `SSL_CERT_DIR` — a directory of `*.pem` / `*.crt` / `*.cer`
    ///   files; each file is loaded individually
    ///
    /// Each candidate cert is also subjected to the
    /// br-asupersync-0owoem `BasicConstraints CA:TRUE` gate before
    /// insertion: leaf certs and otherwise-non-CA certs are rejected
    /// even when present in the file.
    ///
    /// **Security note**: enabling this lets any caller able to set
    /// the process environment inject arbitrary trust anchors. Use
    /// only in deployments where the environment is part of your
    /// trust boundary (e.g., explicitly-configured corporate-proxy
    /// images), and prefer
    /// [`add_root_certificate`](Self::add_root_certificate) for
    /// known-good CA pinning.
    #[must_use]
    pub fn enable_env_cert_loading(mut self) -> Self {
        self.enable_env_certs = true;
        // br-asupersync-sx6j9y — env-loaded certs are unconditionally
        // CA-gated (br-asupersync-0owoem). Mirror that gate to all
        // other root-cert insertion paths so the operator who opted
        // into env-cert loading also gets the same protection on
        // direct add_root_certificate / add_root_certificates calls.
        self.validate_ca_constraints = true;
        self
    }

    /// br-asupersync-sx6j9y — turn on the `BasicConstraints CA:TRUE`
    /// gate for all root-cert insertion paths. With this flag set,
    /// `add_root_certificate` and `add_root_certificates` skip any
    /// cert that does not assert `cA=TRUE`. Without it, the gate is
    /// applied only to env-loaded certs (the legacy behavior),
    /// leaving direct `add_root_certificate(<leaf>)` as a silent
    /// trust bypass — exactly the failure mode this method exists to
    /// close. Set as a side effect of
    /// [`Self::enable_env_cert_loading`]. Production callers SHOULD
    /// set this explicitly. Use
    /// [`Self::insecure_add_root_certificate`] for the rare cases
    /// where you intentionally want a non-CA cert in the trust
    /// store (e.g., pinning a self-signed test cert in a sandbox).
    #[must_use]
    pub fn with_strict_ca_validation(mut self) -> Self {
        self.validate_ca_constraints = true;
        self
    }

    /// br-asupersync-h41wya — explicitly acknowledge the 0-RTT
    /// (early data) replay-attack risk. TLS 1.3 0-RTT is by-spec
    /// replay-vulnerable (RFC 8446 §8): an attacker who captures the
    /// early-data wire bytes can replay them to the same server
    /// within the resumption ticket window, and rustls's in-memory
    /// session store provides no anti-replay window. The application
    /// layer MUST enforce idempotency for every request that could
    /// carry early data (idempotency keys, per-request nonces, or
    /// restriction of 0-RTT to safe HTTP methods).
    ///
    /// `build()` rejects the combination of `enable_early_data(true)`
    /// plus non-disabled session resumption when this acknowledgement
    /// has not been made — preventing a misconfiguration from
    /// shipping silently. Call this only after wiring up the
    /// application-level idempotency layer.
    #[must_use]
    pub fn acknowledge_zero_rtt_replay_risk(mut self) -> Self {
        self.acknowledge_zero_rtt_replay_risk = true;
        self
    }

    /// Add platform/native root certificates (fallback when feature is disabled).
    #[cfg(not(feature = "tls-native-roots"))]
    pub fn with_native_roots(self) -> Result<Self, TlsError> {
        #[cfg(not(feature = "tls"))]
        {
            Err(tls_feature_disabled("load native root certificates"))
        }
        #[cfg(feature = "tls")]
        Err(TlsError::Configuration(
            "tls-native-roots feature not enabled".into(),
        ))
    }

    /// Load additional CA certificates from the OpenSSL-style env vars.
    ///
    /// br-asupersync-gq7l9i: only invoked from `with_native_roots` when
    /// `self.enable_env_certs == true` (caller-set via
    /// [`Self::enable_env_cert_loading`]). Logs every loaded file and
    /// loaded/rejected count at `warn!` so the trust-anchor injection
    /// is visible in production logs.
    #[allow(dead_code)]
    fn load_env_certs(&mut self) {
        // Check multiple env vars that various tools use for custom CA
        // bundles. SSL_CERT_FILE is the most standard (OpenSSL),
        // REQUESTS_CA_BUNDLE (Python) and CURL_CA_BUNDLE (curl) are
        // also common in corporate envs.
        let cert_file = std::env::var("SSL_CERT_FILE")
            .or_else(|_| std::env::var("REQUESTS_CA_BUNDLE"))
            .or_else(|_| std::env::var("CURL_CA_BUNDLE"));
        if let Ok(cert_file) = cert_file {
            let path = std::path::Path::new(&cert_file);
            if path.exists() {
                let load_result = self.load_pem_file(path);
                // br-asupersync-gq7l9i: warn level (not debug) so this
                // shows up in default-config production logs.
                #[cfg(feature = "tracing-integration")]
                match &load_result {
                    Ok(counts) if counts.loaded > 0 || counts.rejected_non_ca > 0 => {
                        tracing::warn!(
                            path = %cert_file,
                            loaded = counts.loaded,
                            rejected_non_ca = counts.rejected_non_ca,
                            "TLS: env-var CA bundle merged into trust store \
                             (br-asupersync-gq7l9i opt-in is active)"
                        );
                    }
                    Err(error) => {
                        tracing::warn!(
                            path = %cert_file,
                            error = %error,
                            "TLS: env-var CA bundle requested but certificate loading failed"
                        );
                    }
                    _ => {}
                }
                let _ = load_result;
            }
        }

        if let Ok(cert_dir) = std::env::var("SSL_CERT_DIR") {
            let dir = std::path::Path::new(&cert_dir);
            if dir.is_dir() {
                // br-asupersync-s0nwli: only accumulate per-file
                // counters when the tracing-integration feature is on
                // — they are exclusively read by the tracing::warn!
                // block below. Without the feature, the totals were
                // dead-write which trips clippy's unused_assignments
                // lint at -D warnings.
                #[cfg(feature = "tracing-integration")]
                let mut loaded_total = 0usize;
                #[cfg(feature = "tracing-integration")]
                let mut rejected_total = 0usize;
                if let Ok(entries) = std::fs::read_dir(dir) {
                    for entry in entries.filter_map(Result::ok) {
                        let path = entry.path();
                        if path.is_file() {
                            if is_env_cert_bundle_path(&path) {
                                let load_result = self.load_pem_file(&path);
                                #[cfg(feature = "tracing-integration")]
                                match &load_result {
                                    Ok(counts) => {
                                        loaded_total = loaded_total.saturating_add(counts.loaded);
                                        rejected_total =
                                            rejected_total.saturating_add(counts.rejected_non_ca);
                                    }
                                    Err(error) => {
                                        tracing::warn!(
                                            path = %path.display(),
                                            error = %error,
                                            "TLS: SSL_CERT_DIR file requested but certificate loading failed"
                                        );
                                    }
                                }
                                let _ = load_result;
                            }
                        } else if path.is_dir() {
                            // Ignore subdirectories.
                        }
                    }
                }
                #[cfg(feature = "tracing-integration")]
                if loaded_total > 0 || rejected_total > 0 {
                    tracing::warn!(
                        path = %cert_dir,
                        loaded = loaded_total,
                        rejected_non_ca = rejected_total,
                        "TLS: SSL_CERT_DIR merged into trust store \
                         (br-asupersync-gq7l9i opt-in is active)"
                    );
                }
            }
        }
    }

    /// Parse PEM-encoded certificates from a file and add CAs to the
    /// root store. Returns explicit load counters.
    ///
    /// br-asupersync-0owoem: previously this used a hand-rolled
    /// splitter (`split("-----BEGIN CERTIFICATE-----")`) that did not
    /// require line-boundary anchoring — a crafted PEM file with the
    /// marker inside a comment could be split into spurious blocks
    /// whose base64 decoded to attacker-chosen DER, and the resulting
    /// `Certificate` was added to the trust store with no further
    /// validation. Worse, a non-CA leaf certificate would be accepted
    /// as a trust anchor (any cert it had "signed" would then
    /// validate). The implementation below now (a) parses via
    /// `rustls_pemfile::certs`, the same path used by
    /// `Certificate::from_pem`, and (b) gates each candidate on the
    /// `BasicConstraints CA:TRUE` extension via `x509-parser`. Certs
    /// that lack the extension or carry `cA=false` are rejected and
    /// counted in the second return value.
    #[allow(dead_code)]
    #[cfg(feature = "tls")]
    fn load_pem_file(
        &mut self,
        path: &std::path::Path,
    ) -> Result<TlsCertificateLoadCounts, TlsError> {
        let Ok(pem_data) = std::fs::read(path) else {
            return Ok(TlsCertificateLoadCounts::default());
        };

        let mut reader = std::io::BufReader::new(&pem_data[..]);
        let der_certs: Vec<Vec<u8>> =
            match rustls_pemfile::certs(&mut reader).collect::<Result<Vec<_>, _>>() {
                Ok(certs) => certs.into_iter().map(|c| c.to_vec()).collect(),
                Err(_e) => {
                    #[cfg(feature = "tracing-integration")]
                    tracing::warn!(
                        path = %path.display(),
                        error = %_e,
                        "TLS: PEM bundle parse failed; skipping file (br-asupersync-0owoem)"
                    );
                    return Ok(TlsCertificateLoadCounts::default());
                }
            };

        let mut loaded = 0usize;
        let mut rejected = 0usize;
        for der in der_certs {
            if !is_ca_certificate(&der) {
                rejected = rejected.saturating_add(1);
                #[cfg(feature = "tracing-integration")]
                tracing::warn!(
                    path = %path.display(),
                    "TLS: rejecting non-CA certificate from trust-anchor file \
                     (basicConstraints CA:TRUE missing or absent — br-asupersync-0owoem)"
                );
                continue;
            }
            if self.root_certs.add(&Certificate::from_der(der)).is_ok() {
                loaded = loaded.saturating_add(1);
            }
        }
        Ok(TlsCertificateLoadCounts {
            loaded,
            rejected_non_ca: rejected,
        })
    }

    /// Disabled-mode PEM loading fails explicitly instead of reporting zero counts.
    #[allow(dead_code)]
    #[cfg(not(feature = "tls"))]
    fn load_pem_file(
        &mut self,
        _path: &std::path::Path,
    ) -> Result<TlsCertificateLoadCounts, TlsError> {
        Err(tls_feature_disabled("load PEM trust anchors"))
    }

    /// Add the standard webpki root certificates.
    ///
    /// These are the Mozilla root certificates, embedded at compile time.
    ///
    /// Requires the `tls-webpki-roots` feature.
    #[cfg(feature = "tls-webpki-roots")]
    pub fn with_webpki_roots(mut self) -> Self {
        self.root_certs.extend_from_webpki_roots();
        #[cfg(feature = "tracing-integration")]
        tracing::debug!(
            count = self.root_certs.len(),
            "Added webpki root certificates"
        );
        self
    }

    /// Add the standard webpki root certificates (fallback when feature is disabled).
    #[cfg(not(feature = "tls-webpki-roots"))]
    pub fn with_webpki_roots(self) -> Self {
        #[cfg(feature = "tracing-integration")]
        tracing::warn!("tls-webpki-roots feature not enabled, no roots added");
        self
    }

    /// Add a single root certificate.
    ///
    /// br-asupersync-sx6j9y — when [`Self::with_strict_ca_validation`]
    /// is set (or has been set as a side effect of
    /// [`Self::enable_env_cert_loading`]), the cert is gated by the
    /// `BasicConstraints CA:TRUE` predicate. A cert without that
    /// extension — most commonly a self-signed leaf — is rejected
    /// (logged at warn) and **not** inserted. This closes the
    /// silent-trust-bypass vector where a misconfigured operator
    /// adds their own server's leaf cert to the trust store.
    ///
    /// Use [`Self::insecure_add_root_certificate`] to bypass the
    /// gate when you intentionally want a non-CA cert in the trust
    /// store (rare; only legitimate for pinning a self-signed test
    /// cert in a sandbox).
    pub fn add_root_certificate(mut self, cert: &Certificate) -> Self {
        if !self.admit_root_certificate(cert) {
            return self;
        }
        if let Err(e) = self.root_certs.add(cert) {
            #[cfg(feature = "tracing-integration")]
            tracing::warn!(error = %e, "Failed to add root certificate");
            let _ = e; // Suppress unused warning when tracing is disabled
        }
        self
    }

    /// Add multiple root certificates.
    ///
    /// br-asupersync-sx6j9y — each cert is independently gated; see
    /// the doc on [`Self::add_root_certificate`] for the gate
    /// semantics.
    pub fn add_root_certificates(mut self, certs: impl IntoIterator<Item = Certificate>) -> Self {
        for cert in certs {
            if !self.admit_root_certificate(&cert) {
                continue;
            }
            if let Err(e) = self.root_certs.add(&cert) {
                #[cfg(feature = "tracing-integration")]
                tracing::warn!(error = %e, "Failed to add root certificate");
                let _ = e;
            }
        }
        self
    }

    /// br-asupersync-sx6j9y — bypass the `BasicConstraints CA:TRUE`
    /// gate and insert the cert into the trust store unconditionally.
    /// Reserved for the rare cases where a non-CA cert is
    /// intentionally trusted as a root (e.g., pinning a self-signed
    /// test cert in a sandbox).
    ///
    /// **SECURITY**: This method is restricted to test builds only to prevent
    /// production deployments from accidentally bypassing certificate validation
    /// and enabling MITM attacks. Use `add_root_certificate()` with
    /// `with_strict_ca_validation()` in production instead.
    #[cfg(test)]
    pub fn insecure_add_root_certificate(mut self, cert: &Certificate) -> Self {
        #[cfg(feature = "tracing-integration")]
        tracing::debug!(
            "TLS: insecure_add_root_certificate called in test build — \
             BasicConstraints CA:TRUE gate bypassed (br-asupersync-sx6j9y)"
        );
        if let Err(e) = self.root_certs.add(cert) {
            #[cfg(feature = "tracing-integration")]
            tracing::warn!(error = %e, "Failed to add root certificate");
            let _ = e;
        }
        self
    }

    /// br-asupersync-sx6j9y — apply the strict-CA gate when the
    /// builder has opted in. Returns `true` to admit the cert,
    /// `false` to reject it. Always emits a warn-level log on
    /// rejection so a silent trust bypass cannot occur even when
    /// the gate fires invisibly.
    #[cfg(feature = "tls")]
    fn admit_root_certificate(&self, cert: &Certificate) -> bool {
        if !self.validate_ca_constraints {
            return true;
        }
        let der = cert.as_der();
        if is_ca_certificate(der) {
            return true;
        }
        #[cfg(feature = "tracing-integration")]
        tracing::warn!(
            "TLS: rejecting non-CA cert from add_root_certificate / \
             add_root_certificates — basicConstraints CA:TRUE missing or \
             absent (br-asupersync-sx6j9y; with_strict_ca_validation is on)"
        );
        false
    }

    /// Fallback for the `tls`-disabled build — strict-CA gate is a no-op
    /// because there is no x509 parser available.
    #[cfg(not(feature = "tls"))]
    fn admit_root_certificate(&self, _cert: &Certificate) -> bool {
        true
    }

    /// Set client certificate for mutual TLS (mTLS).
    pub fn identity(mut self, chain: CertificateChain, key: PrivateKey) -> Self {
        self.client_identity = Some((chain, key));
        self
    }

    /// Set ALPN protocols (e.g., `["h2", "http/1.1"]`).
    ///
    /// Protocols are tried in order of preference (first is most preferred).
    ///
    /// # Advertise vs. require
    ///
    /// This setter **advertises** the listed protocols to the peer but does
    /// NOT require the peer to negotiate one. Per RFC 7301 a server that
    /// omits the ALPN extension entirely is still accepted, and
    /// `connect()` returns `Ok` with `negotiated_alpn = None`. If the caller
    /// is an HTTP/2-only or gRPC-only client (where a non-ALPN HTTP/1.1
    /// peer is a protocol mismatch rather than a valid fallback), pair this
    /// call with [`require_alpn`](Self::require_alpn), or — more concisely —
    /// use [`alpn_protocols_required`](Self::alpn_protocols_required),
    /// [`alpn_h2`](Self::alpn_h2), or [`alpn_grpc`](Self::alpn_grpc),
    /// which set the require-ALPN flag for you.
    ///
    /// [`alpn_http`](Self::alpn_http) intentionally keeps the require flag
    /// off because HTTP/1.1 fallback on no-ALPN is the correct behavior for
    /// dual-stack clients. Use this raw setter only when you need that
    /// precise advertise-but-don't-require semantic.
    pub fn alpn_protocols(mut self, protocols: Vec<Vec<u8>>) -> Self {
        self.alpn_protocols = protocols;
        self
    }

    /// Require that the peer negotiates an ALPN protocol.
    ///
    /// If the peer does not negotiate any protocol (or negotiates something
    /// unexpected), `connect()` returns `TlsError::AlpnNegotiationFailed`.
    pub fn require_alpn(mut self) -> Self {
        self.alpn_required = true;
        self
    }

    /// Set ALPN protocols and require successful negotiation.
    pub fn alpn_protocols_required(self, protocols: Vec<Vec<u8>>) -> Self {
        self.alpn_protocols(protocols).require_alpn()
    }

    /// Convenience method for HTTP/2 ALPN only.
    pub fn alpn_h2(self) -> Self {
        self.alpn_protocols_required(vec![b"h2".to_vec()])
    }

    /// Convenience method for gRPC (HTTP/2-only) ALPN.
    pub fn alpn_grpc(self) -> Self {
        self.alpn_h2()
    }

    /// Convenience method for HTTP/1.1 and HTTP/2 ALPN.
    ///
    /// HTTP/2 is preferred over HTTP/1.1. Unlike [`alpn_h2`](Self::alpn_h2)
    /// and [`alpn_grpc`](Self::alpn_grpc), this does **not** set
    /// `alpn_required`: servers that omit the ALPN extension fall back to
    /// HTTP/1.1, which is the correct behavior per RFC 7301 for clients
    /// that support both protocols.
    pub fn alpn_http(self) -> Self {
        self.alpn_protocols(vec![b"h2".to_vec(), b"http/1.1".to_vec()])
    }

    /// Disable Server Name Indication (SNI).
    ///
    /// SNI is required by many servers. Only disable if you know what you're doing.
    pub fn disable_sni(mut self) -> Self {
        self.enable_sni = false;
        self
    }

    /// Set a timeout for the TLS handshake.
    pub fn handshake_timeout(mut self, timeout: std::time::Duration) -> Self {
        self.handshake_timeout = Some(timeout);
        self
    }

    /// Set minimum TLS protocol version.
    #[cfg(feature = "tls")]
    pub fn min_protocol_version(mut self, version: rustls::ProtocolVersion) -> Self {
        self.min_protocol = Some(version);
        self
    }

    /// Set maximum TLS protocol version.
    #[cfg(feature = "tls")]
    pub fn max_protocol_version(mut self, version: rustls::ProtocolVersion) -> Self {
        self.max_protocol = Some(version);
        self
    }

    /// Configure TLS session resumption.
    ///
    /// By default, rustls enables in-memory session storage (256 sessions).
    /// Use this to customize the resumption strategy.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use rustls::client::Resumption;
    ///
    /// let connector = TlsConnectorBuilder::new()
    ///     .session_resumption(Resumption::in_memory_sessions(512))
    ///     .build()?;
    /// ```
    #[cfg(feature = "tls")]
    pub fn session_resumption(mut self, resumption: rustls::client::Resumption) -> Self {
        self.resumption = Some(resumption);
        self
    }

    /// Disable TLS session resumption entirely.
    ///
    /// This forces a full handshake on every connection. Use for testing
    /// or when session tickets are a security concern.
    #[cfg(feature = "tls")]
    pub fn disable_session_resumption(mut self) -> Self {
        self.resumption = Some(rustls::client::Resumption::disabled());
        self
    }

    /// **DANGEROUS**: send TLS 1.3 0-RTT (early data) on resumed
    /// handshakes when the server's resumption ticket allows it.
    ///
    /// br-asupersync-y0gm5q: 0-RTT is OFF by default on the
    /// client side — rustls's `enable_early_data` defaults to
    /// `false` and we leave it that way unless the operator opts
    /// in via this method. The corresponding acceptor-side
    /// opt-in is [`crate::tls::TlsAcceptorBuilder::enable_early_data`].
    ///
    /// # Replay vulnerability (RFC 8446 §8)
    ///
    /// 0-RTT data is replay-vulnerable BY SPEC. An attacker who
    /// captures the early-data record can replay it to the same
    /// server within the ticket window; the server has no
    /// transport-level mechanism to detect or reject the replay.
    /// Even read-only requests can leak — a replayed GET hits the
    /// origin (and any downstream metering / rate-limit / audit
    /// log) again. Only enable on the client when:
    ///
    /// 1. The application enforces idempotency for every
    ///    request that could carry early data, AND
    /// 2. The server side has a corresponding anti-replay store
    ///    bound to the resumption ticket.
    ///
    /// Pass `false` to explicitly disable (the default).
    #[cfg(feature = "tls")]
    #[must_use]
    pub fn enable_early_data(mut self, enabled: bool) -> Self {
        self.early_data_enabled = enabled;
        self
    }

    /// Add a PEM-encoded Certificate Revocation List
    /// (br-asupersync-p7369s).
    ///
    /// When at least one CRL is configured, `build()` constructs a
    /// `WebPkiServerVerifier` that consults the CRLs during peer-cert
    /// validation. A peer cert whose serial number appears in any CRL
    /// is rejected with a typed verification error and the connection
    /// fails before any application bytes flow.
    ///
    /// # Tradeoffs
    ///
    /// * **Freshness**: rustls only consults the CRLs that were
    ///   present at `build()` time. CRL refresh requires constructing
    ///   a fresh `TlsConnector`. Long-lived processes connecting to
    ///   slowly-rotating PKIs should periodically rebuild the
    ///   connector with a current CRL.
    /// * **Coverage**: a CRL covers only the certs issued by the
    ///   matching CA. Mixing CRLs from multiple CAs is supported;
    ///   each CRL applies to its issuer. CRLs for CAs that do not
    ///   appear in the configured roots are silently inert.
    /// * **OCSP**: rustls 0.23 does not surface OCSP-stapling
    ///   *enforcement*, only OCSP-response *acceptance* during the
    ///   handshake. CRL is the more reliable revocation primitive
    ///   here. When OCSP-must-staple is required, deploy a sidecar
    ///   that pre-validates the OCSP response and blocklists revoked
    ///   serials into the CRL set.
    #[cfg(feature = "tls")]
    pub fn with_crl_pem(mut self, pem: impl Into<Vec<u8>>) -> Self {
        self.crl_pems.push(pem.into());
        self
    }

    /// Add multiple PEM-encoded CRLs in one call
    /// (br-asupersync-p7369s).
    #[cfg(feature = "tls")]
    pub fn with_crl_pems<I, P>(mut self, pems: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: Into<Vec<u8>>,
    {
        for pem in pems {
            self.crl_pems.push(pem.into());
        }
        self
    }

    /// Build the `TlsConnector`.
    ///
    /// # Errors
    ///
    /// Returns an error if the configuration is invalid (e.g., invalid client certificate).
    #[cfg(feature = "tls")]
    pub fn build(self) -> Result<TlsConnector, TlsError> {
        use rustls::crypto::ring::default_provider;

        if self.alpn_required && self.alpn_protocols.is_empty() {
            return Err(TlsError::Configuration(
                "require_alpn set but no ALPN protocols configured".into(),
            ));
        }

        if self.root_certs.is_empty() {
            return Err(TlsError::Certificate(
                "no root certificates configured — server certificates cannot be verified"
                    .to_string(),
            ));
        }

        // br-asupersync-h41wya — fail-closed on the silent
        // 0-RTT-replay misconfiguration. Combining session
        // resumption (client default: in-memory store of 256
        // sessions) with TLS 1.3 0-RTT exposes the application to
        // replay attacks on the early-data payload (RFC 8446 §8).
        // The operator must explicitly acknowledge the risk by
        // calling acknowledge_zero_rtt_replay_risk(); otherwise
        // build() rejects the combination so it cannot ship by
        // accident.
        if self.early_data_enabled && !self.acknowledge_zero_rtt_replay_risk {
            return Err(TlsError::Configuration(
                "enable_early_data(true) requires \
                 acknowledge_zero_rtt_replay_risk() — TLS 1.3 0-RTT is replay-vulnerable \
                 by spec (RFC 8446 §8) and rustls's in-memory session store provides \
                 no anti-replay window. Wire up application-level idempotency for every \
                 request that could carry early data, then call \
                 acknowledge_zero_rtt_replay_risk() to confirm"
                    .into(),
            ));
        }

        // Create the config builder with the crypto provider and protocol versions.
        let builder = ClientConfig::builder_with_provider(Arc::new(default_provider()));
        let builder = if self.min_protocol.is_some() || self.max_protocol.is_some() {
            // Convert protocol versions to ordinals for comparison.
            // TLS 1.2 = 0x0303, TLS 1.3 = 0x0304
            fn version_ordinal(v: rustls::ProtocolVersion) -> u16 {
                match v {
                    rustls::ProtocolVersion::TLSv1_2 => 0x0303,
                    rustls::ProtocolVersion::TLSv1_3 => 0x0304,
                    // For unknown versions, use a high value so they're excluded by default
                    _ => 0xFFFF,
                }
            }

            let min = self.min_protocol.map(version_ordinal);
            let max = self.max_protocol.map(version_ordinal);

            if let (Some(min_ord), Some(max_ord)) = (min, max) {
                if min_ord > max_ord {
                    return Err(TlsError::Configuration(
                        "min_protocol_version is greater than max_protocol_version".into(),
                    ));
                }
            }

            let versions: Vec<&'static rustls::SupportedProtocolVersion> = rustls::ALL_VERSIONS
                .iter()
                .filter(|v| {
                    let ordinal = version_ordinal(v.version);
                    let within_min = min.is_none_or(|m| ordinal >= m);
                    let within_max = max.is_none_or(|m| ordinal <= m);
                    within_min && within_max
                })
                .copied()
                .collect();

            if versions.is_empty() {
                return Err(TlsError::Configuration(
                    "no supported TLS protocol versions within requested range".into(),
                ));
            }

            builder
                .with_protocol_versions(&versions)
                .map_err(|e| TlsError::Configuration(e.to_string()))?
        } else {
            builder
                .with_safe_default_protocol_versions()
                .map_err(|e| TlsError::Configuration(e.to_string()))?
        };

        // br-asupersync-p7369s: when at least one CRL is configured,
        // swap the rustls default verifier for a
        // `WebPkiServerVerifier` built with the CRLs. The resulting
        // verifier still uses the same trust roots; CRLs apply per-
        // issuer at validation time. With no CRLs, the rustls default
        // verifier path is used (existing behavior preserved).
        let roots = self.root_certs.into_inner();
        let builder = if self.crl_pems.is_empty() {
            builder.with_root_certificates(roots)
        } else {
            let mut crl_ders: Vec<rustls::pki_types::CertificateRevocationListDer<'static>> =
                Vec::new();
            for pem in &self.crl_pems {
                let mut reader = std::io::BufReader::new(&pem[..]);
                let der_iter = rustls_pemfile::crls(&mut reader);
                for der in der_iter {
                    let der = der.map_err(|e| {
                        TlsError::Configuration(format!("CRL PEM parse error: {e}"))
                    })?;
                    crl_ders.push(der);
                }
            }
            if crl_ders.is_empty() {
                return Err(TlsError::Configuration(
                    "with_crl_pem called but no CRL blocks were parsed from the supplied PEM(s)"
                        .into(),
                ));
            }
            let verifier = rustls::client::WebPkiServerVerifier::builder(Arc::new(roots))
                .with_crls(crl_ders)
                .build()
                .map_err(|e| TlsError::Configuration(format!("CRL verifier build: {e}")))?;
            // The dangerous() name reflects that callers can plug in
            // an arbitrary verifier — here we plug in webpki's own
            // verifier with CRLs attached, which is *strictly more*
            // strict than the default. This is the documented escape
            // hatch for adding CRL/OCSP enforcement on top of
            // standard validation.
            builder
                .dangerous()
                .with_custom_certificate_verifier(verifier)
        };

        // Set client identity if provided
        let mut config = if let Some((chain, key)) = self.client_identity {
            builder
                .with_client_auth_cert(chain.into_inner(), key.clone_inner())
                .map_err(|e| TlsError::Configuration(e.to_string()))?
        } else {
            builder.with_no_client_auth()
        };

        // Set ALPN if specified
        if !self.alpn_protocols.is_empty() {
            config.alpn_protocols = self.alpn_protocols;
        }

        // SNI is enabled by default in rustls
        config.enable_sni = self.enable_sni;

        // Configure session resumption if explicitly set.
        // Default: rustls uses in-memory storage for 256 sessions.
        if let Some(resumption) = self.resumption {
            config.resumption = resumption;
        }

        // br-asupersync-y0gm5q: explicit early-data write. rustls's
        // own default is `false` (0-RTT off) but we set it
        // explicitly so a future rustls API change cannot silently
        // flip the default to "on" without us noticing. The value
        // here is the operator's choice from `enable_early_data(...)`
        // (default false).
        config.enable_early_data = self.early_data_enabled;

        #[cfg(feature = "tracing-integration")]
        tracing::debug!(
            alpn = ?config.alpn_protocols,
            sni = config.enable_sni,
            enable_early_data = config.enable_early_data,
            "TlsConnector built"
        );

        Ok(TlsConnector {
            config: Arc::new(config),
            handshake_timeout: self.handshake_timeout,
            alpn_required: self.alpn_required,
            pin_set: self.pin_set.map(Arc::new),
        })
    }

    /// Build the `TlsConnector` (disabled-mode fallback when TLS is disabled).
    #[cfg(not(feature = "tls"))]
    pub fn build(self) -> Result<TlsConnector, TlsError> {
        let _ = (
            self.alpn_required,
            self.pin_set.as_ref(),
            self.early_data_enabled,
        );
        Err(tls_feature_disabled("build TLS connector"))
    }
}

fn is_env_cert_bundle_path(path: &std::path::Path) -> bool {
    path.extension()
        .and_then(std::ffi::OsStr::to_str)
        .is_some_and(|ext| {
            ext.eq_ignore_ascii_case("pem")
                || ext.eq_ignore_ascii_case("crt")
                || ext.eq_ignore_ascii_case("cer")
        })
}

/// Return `true` iff the DER-encoded certificate bears
/// `BasicConstraints CA:TRUE` and is therefore eligible to act as a
/// trust anchor (br-asupersync-0owoem).
///
/// A cert without the BasicConstraints extension, or with `cA=false`,
/// is **not** a CA per RFC 5280 §4.2.1.9 and must not be inserted
/// into the root-cert store: doing so would let any cert chained
/// underneath it be accepted by webpki — a complete trust bypass.
/// Self-signed leaf certs (very common in misconfigured deployments)
/// fall in this category and are rejected.
#[cfg(feature = "tls")]
fn is_ca_certificate(der: &[u8]) -> bool {
    // x509-parser is already an optional dep enabled by the `tls`
    // feature; reuse it rather than rolling a bespoke ASN.1 walker.
    let parsed = match x509_parser::parse_x509_certificate(der) {
        Ok((_, cert)) => cert,
        Err(_) => return false,
    };
    parsed
        .basic_constraints()
        .ok()
        .flatten()
        .is_some_and(|bc| bc.value.ca)
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::pedantic,
        clippy::nursery,
        clippy::expect_fun_call,
        clippy::map_unwrap_or,
        clippy::cast_possible_wrap,
        clippy::future_not_send
    )]
    use super::*;

    #[cfg(feature = "tls")]
    const TEST_CERT_PEM: &[u8] = include_bytes!("../../tests/fixtures/tls/server.crt");
    #[cfg(feature = "tls")]
    const TEST_KEY_PEM: &[u8] = include_bytes!("../../tests/fixtures/tls/server.key");

    #[cfg(not(feature = "tls"))]
    fn tls_error_kind(error: &TlsError) -> &'static str {
        match error {
            TlsError::InvalidDnsName(_) => "InvalidDnsName",
            TlsError::Handshake(_) => "Handshake",
            TlsError::Certificate(_) => "Certificate",
            TlsError::CertificateExpired { .. } => "CertificateExpired",
            TlsError::CertificateNotYetValid { .. } => "CertificateNotYetValid",
            TlsError::ChainValidation(_) => "ChainValidation",
            TlsError::PinMismatch { .. } => "PinMismatch",
            TlsError::Configuration(_) => "Configuration",
            TlsError::FeatureDisabled { .. } => "FeatureDisabled",
            TlsError::Io(_) => "Io",
            TlsError::Timeout(_) => "Timeout",
            TlsError::AlpnNegotiationFailed { .. } => "AlpnNegotiationFailed",
            #[cfg(feature = "tls")]
            TlsError::Rustls(_) => "Rustls",
        }
    }

    #[test]
    fn test_builder_default() {
        let builder = TlsConnectorBuilder::new();
        assert!(builder.root_certs.is_empty());
        assert!(builder.alpn_protocols.is_empty());
        assert!(builder.enable_sni);
    }

    #[test]
    fn test_builder_alpn_http() {
        let builder = TlsConnectorBuilder::new().alpn_http();
        assert_eq!(
            builder.alpn_protocols,
            vec![b"h2".to_vec(), b"http/1.1".to_vec()]
        );
    }

    #[test]
    fn test_builder_alpn_h2() {
        let builder = TlsConnectorBuilder::new().alpn_h2();
        assert_eq!(builder.alpn_protocols, vec![b"h2".to_vec()]);
        assert!(builder.alpn_required);
    }

    #[test]
    fn test_builder_alpn_grpc() {
        let builder = TlsConnectorBuilder::new().alpn_grpc();
        assert_eq!(builder.alpn_protocols, vec![b"h2".to_vec()]);
        assert!(builder.alpn_required);
    }

    #[test]
    fn test_builder_disable_sni() {
        let builder = TlsConnectorBuilder::new().disable_sni();
        assert!(!builder.enable_sni);
    }

    #[test]
    fn test_validate_domain_valid() {
        assert!(TlsConnector::validate_domain("example.com").is_ok());
        assert!(TlsConnector::validate_domain("sub.example.com").is_ok());
        assert!(TlsConnector::validate_domain("localhost").is_ok());
    }

    #[test]
    fn test_validate_domain_invalid() {
        assert!(TlsConnector::validate_domain("").is_err());
        assert!(TlsConnector::validate_domain("invalid domain with spaces").is_err());
    }

    #[cfg(feature = "tls")]
    #[test]
    fn test_validate_domain_rfc3492_punycode_vector() {
        // RFC 3492 / IDNA-style A-label for "bücher.example".
        let punycode = "xn--bcher-kva.example";

        assert!(TlsConnector::validate_domain(punycode).is_ok());
        assert!(TlsConnector::validate_domain("bücher.example").is_err());
    }

    // br-asupersync-7wnl2l: previously this test asserted that
    // `TlsConnectorBuilder::new().build()` *succeeded* with no roots
    // configured — directly contradicting the explicit empty-roots
    // rejection at the top of `build()` (which exists precisely so a
    // misconfigured caller doesn't open a no-roots connection that
    // would skip server-cert validation entirely). The test was dead
    // (silently failing the .unwrap() in any environment that
    // exercised it). Inverted to assert the rejection, plus a paired
    // positive test below using the test fixture's CA.
    #[cfg(feature = "tls")]
    #[test]
    fn test_build_empty_roots_rejected() {
        let err = TlsConnectorBuilder::new()
            .build()
            .expect_err("empty roots must be rejected by build()");
        match err {
            TlsError::Certificate(msg) => {
                assert!(
                    msg.contains("no root certificates configured"),
                    "expected empty-roots rejection message, got: {msg}"
                );
            }
            other => panic!("expected TlsError::Certificate, got {other:?}"),
        }
    }

    #[cfg(feature = "tls")]
    #[test]
    fn test_build_with_test_root_succeeds() {
        // Positive control for the empty-roots rejection above. Uses
        // the test-fixture CA so build() succeeds. Pins the success
        // path so a future agent removing the empty-roots check
        // cannot land it without also breaking this test.
        let certs = Certificate::from_pem(TEST_CERT_PEM).unwrap();
        let connector = TlsConnectorBuilder::new()
            .add_root_certificates(certs)
            .build()
            .expect("builder with one root should succeed");
        assert!(connector.config().alpn_protocols.is_empty());
    }

    // --- br-asupersync-gq7l9i: env-var trust anchors are opt-in ----

    #[test]
    fn test_env_cert_loading_disabled_by_default() {
        // br-asupersync-gq7l9i: TlsConnectorBuilder::new() must leave
        // env-var trust-anchor loading disabled. A caller who sets
        // SSL_CERT_FILE in their environment must NOT have those
        // certs silently injected; explicit opt-in via
        // enable_env_cert_loading() is required.
        let builder = TlsConnectorBuilder::new();
        assert!(
            !builder.enable_env_certs,
            "env-var cert loading must be off by default"
        );
    }

    #[test]
    fn test_enable_env_cert_loading_sets_flag() {
        // br-asupersync-gq7l9i: explicit opt-in flips the flag.
        let builder = TlsConnectorBuilder::new().enable_env_cert_loading();
        assert!(
            builder.enable_env_certs,
            "enable_env_cert_loading must flip the opt-in flag"
        );
    }

    #[test]
    fn test_ssl_cert_dir_bundle_extension_match_is_case_insensitive() {
        assert!(super::is_env_cert_bundle_path(std::path::Path::new(
            "/tmp/corp-root.pem"
        )));
        assert!(super::is_env_cert_bundle_path(std::path::Path::new(
            "/tmp/corp-root.PEM"
        )));
        assert!(super::is_env_cert_bundle_path(std::path::Path::new(
            "/tmp/corp-root.CrT"
        )));
        assert!(super::is_env_cert_bundle_path(std::path::Path::new(
            "/tmp/corp-root.cEr"
        )));
        assert!(!super::is_env_cert_bundle_path(std::path::Path::new(
            "/tmp/corp-root.pem.bak"
        )));
        assert!(!super::is_env_cert_bundle_path(std::path::Path::new(
            "/tmp/corp-root"
        )));
    }

    // --- br-asupersync-0owoem: BasicConstraints CA:TRUE gate -------

    #[cfg(feature = "tls")]
    #[test]
    fn test_is_ca_certificate_rejects_self_signed_leaf() {
        // br-asupersync-0owoem: the test fixture server cert is a
        // *leaf* — it lacks `basicConstraints CA:TRUE` (it carries
        // server-auth EKU and is signed by a real CA in test
        // setups). Adding it to the trust store as a *trust anchor*
        // would let any cert it "signed" validate, which is exactly
        // the trust-bypass the gate prevents.
        let certs = Certificate::from_pem(TEST_CERT_PEM).expect("parse test cert");
        let cert = certs.first().expect("at least one cert in fixture");
        let der: &[u8] = cert.as_der();
        let is_ca = super::is_ca_certificate(der);
        // The test fixture is a leaf cert (CA:FALSE or BC missing),
        // so the gate must reject it. If a future fixture rotation
        // ships a CA cert here, this assertion will fail loudly and
        // surface the regression — that's the intent.
        assert!(
            !is_ca,
            "test fixture leaf cert must be rejected by CA-gate (br-asupersync-0owoem); \
             if the fixture was rotated to a CA, update this test"
        );
    }

    // --- br-asupersync-p7369s: CRL configuration -------------------

    #[cfg(feature = "tls")]
    #[test]
    fn test_with_crl_pem_with_garbage_pem_rejected_at_build() {
        // br-asupersync-p7369s: garbage that doesn't parse as CRL
        // PEM must surface a typed Configuration error, not a panic
        // and not a silent skip-the-CRL.
        let certs = Certificate::from_pem(TEST_CERT_PEM).unwrap();
        let err = TlsConnectorBuilder::new()
            .add_root_certificates(certs)
            .with_crl_pem(b"not a valid CRL".to_vec())
            .build()
            .expect_err("garbage CRL PEM must reject at build()");
        match err {
            TlsError::Configuration(msg) => {
                assert!(
                    msg.contains("CRL"),
                    "expected CRL-related Configuration error, got: {msg}"
                );
            }
            other => panic!("expected TlsError::Configuration, got {other:?}"),
        }
    }

    #[cfg(feature = "tls")]
    #[test]
    fn test_no_crl_means_default_verifier_path() {
        // br-asupersync-p7369s: callers that don't configure any CRL
        // must continue to land on the rustls default-verifier code
        // path (i.e., build() must not regress to requiring CRL
        // configuration). This test pins the no-CRL no-op behaviour.
        let certs = Certificate::from_pem(TEST_CERT_PEM).unwrap();
        let connector = TlsConnectorBuilder::new()
            .add_root_certificates(certs)
            .build()
            .expect("no-CRL build must succeed");
        let _ = connector.config(); // smoke-check the inner config materialised
    }

    #[cfg(feature = "tls")]
    #[test]
    fn test_build_with_alpn() {
        let connector = TlsConnectorBuilder::new().alpn_http().build().unwrap();

        assert_eq!(
            connector.config().alpn_protocols,
            vec![b"h2".to_vec(), b"http/1.1".to_vec()]
        );
    }

    #[cfg(feature = "tls")]
    #[test]
    fn test_handshake_timeout_builder() {
        let timeout = std::time::Duration::from_secs(1);
        let connector = TlsConnectorBuilder::new()
            .handshake_timeout(timeout)
            .build()
            .unwrap();
        assert_eq!(connector.handshake_timeout(), Some(timeout));
    }

    #[cfg(feature = "tls")]
    #[test]
    fn test_connector_clone_is_cheap() {
        let connector = TlsConnectorBuilder::new().build().unwrap();

        let start = std::time::Instant::now();
        for _ in 0..10000 {
            let _clone = connector.clone();
        }
        let elapsed = start.elapsed();

        // Should be very fast (Arc clone)
        assert!(elapsed.as_millis() < 100);
    }

    #[cfg(feature = "tls")]
    #[test]
    fn test_connect_invalid_dns() {
        use crate::net::tcp::VirtualTcpStream;
        use crate::test_utils::run_test_with_cx;

        run_test_with_cx(|_cx| async move {
            let connector = TlsConnectorBuilder::new().build().unwrap();
            let (client_io, _server_io) = VirtualTcpStream::pair(
                "127.0.0.1:5100".parse().unwrap(),
                "127.0.0.1:5101".parse().unwrap(),
            );
            let err = connector
                .connect("invalid domain with spaces", client_io)
                .await
                .unwrap_err();
            assert!(matches!(err, TlsError::InvalidDnsName(_)));
        });
    }

    #[cfg(feature = "tls")]
    #[test]
    fn test_connect_completes_under_lab_runtime() {
        use crate::conformance::{ConformanceTarget, LabRuntimeTarget, TestConfig};
        use crate::cx::Cx;
        use crate::net::tcp::VirtualTcpStream;
        use crate::test_utils::init_test_logging;
        use crate::tls::TlsAcceptorBuilder;
        use futures_lite::future::zip;

        init_test_logging();
        let config = TestConfig::new()
            .with_seed(0x715A_CCE9)
            .with_tracing(true)
            .with_max_steps(20_000);
        let mut runtime = LabRuntimeTarget::create_runtime(config);

        let (ready, protocol_present, alpn, checkpoints) = LabRuntimeTarget::block_on(
            &mut runtime,
            async move {
                let _cx = Cx::current().expect("lab runtime should install a current Cx");

                let chain = CertificateChain::from_pem(TEST_CERT_PEM).unwrap();
                let key = PrivateKey::from_pem(TEST_KEY_PEM).unwrap();
                let acceptor = TlsAcceptorBuilder::new(chain, key)
                    .alpn_http()
                    .build()
                    .unwrap();

                let certs = Certificate::from_pem(TEST_CERT_PEM).unwrap();
                let connector = TlsConnectorBuilder::new()
                    .add_root_certificates(certs)
                    .alpn_http()
                    .handshake_timeout(std::time::Duration::from_secs(1))
                    .build()
                    .unwrap();

                let (client_io, server_io) = VirtualTcpStream::pair(
                    "127.0.0.1:5300".parse().unwrap(),
                    "127.0.0.1:5301".parse().unwrap(),
                );

                let checkpoints = vec![serde_json::json!({
                    "phase": "connector_pair_created",
                    "client_addr": "127.0.0.1:5300",
                    "server_addr": "127.0.0.1:5301",
                    "handshake_timeout_ms": 1000,
                })];
                tracing::info!(event = %checkpoints[0], "tls_connector_lab_checkpoint");

                let (client_res, server_res) = zip(
                    connector.connect("localhost", client_io),
                    acceptor.accept(server_io),
                )
                .await;
                let client = client_res.expect("connector handshake should succeed");
                let server = server_res.expect("server handshake should succeed");

                let ready = client.is_ready() && server.is_ready();
                let protocol_present =
                    client.protocol_version().is_some() && server.protocol_version().is_some();
                let alpn = client.alpn_protocol().map(|protocol| protocol.to_vec());

                let mut checkpoints = checkpoints;
                checkpoints.push(serde_json::json!({
                    "phase": "connector_handshake_completed",
                    "ready": ready,
                    "protocol_present": protocol_present,
                    "client_alpn": alpn.as_ref().map(|protocol| String::from_utf8_lossy(protocol).to_string()),
                    "server_alpn": server.alpn_protocol().map(|protocol| String::from_utf8_lossy(protocol).to_string()),
                }));
                tracing::info!(event = %checkpoints[1], "tls_connector_lab_checkpoint");

                (ready, protocol_present, alpn, checkpoints)
            },
        );

        assert!(ready);
        assert!(protocol_present);
        assert_eq!(alpn.as_deref(), Some(b"h2".as_slice()));
        assert_eq!(checkpoints.len(), 2);
        assert!(runtime.is_quiescent());
    }

    #[cfg(feature = "tls")]
    #[test]
    fn test_session_resumption_custom() {
        let connector = TlsConnectorBuilder::new()
            .session_resumption(rustls::client::Resumption::in_memory_sessions(512))
            .build()
            .unwrap();
        // Connector builds successfully with custom resumption config.
        assert!(connector.handshake_timeout().is_none());
    }

    #[cfg(feature = "tls")]
    #[test]
    fn test_session_resumption_disabled() {
        let connector = TlsConnectorBuilder::new()
            .disable_session_resumption()
            .build()
            .unwrap();
        assert!(connector.handshake_timeout().is_none());
    }

    #[cfg(not(feature = "tls"))]
    #[test]
    fn test_build_without_tls_feature() {
        let err = match TlsConnectorBuilder::new().build() {
            Err(err) => err,
            Ok(_) => panic!("TLS-disabled build must reject connector construction"),
        };
        match err {
            TlsError::FeatureDisabled { operation, hint } => {
                assert_eq!(operation, "build TLS connector");
                assert!(hint.contains("--features tls"), "got: {hint}");
            }
            other => panic!("expected FeatureDisabled, got {other:?}"),
        }
    }

    #[cfg(not(feature = "tls"))]
    #[test]
    fn tls_feature_disabled_with_requested_config_logs_redacted_diagnostic() {
        let sensitive_path = "/etc/ssl/private/corp-root-secret.pem";
        let redacted_path = "<redacted>";
        let mut builder = TlsConnectorBuilder::new()
            .enable_env_cert_loading()
            .add_root_certificate(&Certificate::from_der(b"test-root".to_vec()))
            .alpn_h2();

        let load_error = builder
            .load_pem_file(std::path::Path::new(sensitive_path))
            .expect_err("TLS-disabled PEM loading must fail explicitly");
        let requested_root_count = builder.root_certs.len();
        let build_error = match builder.build() {
            Err(err) => err,
            Ok(_) => panic!("TLS-disabled build must reject requested TLS config"),
        };

        let artifact = serde_json::json!({
            "schema_version": "tls-feature-disabled-diagnostic-v1",
            "feature_flags": {
                "tls": cfg!(feature = "tls")
            },
            "config_source": {
                "kind": "env-cert-file",
                "path": redacted_path
            },
            "requested_root_source_count": requested_root_count,
            "env_cert_loading": true,
            "alpn_required": true,
            "load_error_kind": tls_error_kind(&load_error),
            "build_error_kind": tls_error_kind(&build_error),
            "operator_hint": TLS_FEATURE_HINT,
            "final_verdict": "pass"
        });
        let artifact_text = artifact.to_string();
        println!("{artifact_text}");

        assert_eq!(artifact["feature_flags"]["tls"], false);
        assert_eq!(artifact["requested_root_source_count"], 1);
        assert_eq!(artifact["load_error_kind"], "FeatureDisabled");
        assert_eq!(artifact["build_error_kind"], "FeatureDisabled");
        assert_eq!(artifact["operator_hint"], TLS_FEATURE_HINT);
        assert_eq!(artifact["final_verdict"], "pass");
        assert!(
            !artifact_text.contains(sensitive_path),
            "diagnostic artifact leaked TLS config path: {artifact_text}"
        );
    }

    #[cfg(not(feature = "tls"))]
    #[test]
    fn tls_feature_disabled_native_roots_reports_operator_hint() {
        let err = TlsConnectorBuilder::new()
            .with_native_roots()
            .expect_err("TLS-disabled native-root loading must fail explicitly");
        match err {
            TlsError::FeatureDisabled { operation, hint } => {
                assert_eq!(operation, "load native root certificates");
                assert!(hint.contains("--features tls"), "got: {hint}");
            }
            other => panic!("expected FeatureDisabled, got {other:?}"),
        }
    }

    #[cfg(feature = "tls")]
    #[test]
    fn tls_enabled_pem_load_reports_certificate_counters() {
        let mut builder = TlsConnectorBuilder::new().enable_env_cert_loading();
        let counts = builder
            .load_pem_file(std::path::Path::new("tests/fixtures/tls/server.crt"))
            .expect("TLS-enabled PEM loading should report counters");

        assert_eq!(
            counts.loaded + counts.rejected_non_ca,
            1,
            "fixture should contain exactly one cert; got {counts:?}"
        );
        assert_eq!(
            counts.rejected_non_ca, 1,
            "server fixture is a leaf and must be rejected as a trust anchor"
        );
        assert!(builder.root_certs.is_empty());
    }

    // ── br-asupersync-v24lvi: certificate-pinning wiring tests ────────

    #[cfg(feature = "tls")]
    #[test]
    fn v24lvi_with_certificate_pins_attaches_pin_set_to_connector() {
        // Builder accepts a pin set; the resulting connector carries
        // it. Pre-fix there was no such builder method — the only
        // way to "use" pins was to call them manually after connect()
        // returned, which 99% of callers never did.
        let mut pins = CertificatePinSet::new();
        pins.add_spki_sha256_base64("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
            .expect("valid base64");
        let connector = TlsConnectorBuilder::new()
            .add_root_certificate(&Certificate::from_der(TEST_CERT_PEM.to_vec()))
            .with_certificate_pins(pins)
            .build()
            .expect("build with pins");
        assert!(
            connector.pin_set.is_some(),
            "with_certificate_pins must populate the connector's pin_set"
        );
        assert_eq!(
            connector.pin_set.as_ref().unwrap().len(),
            1,
            "all attached pins must reach the connector"
        );
    }

    #[cfg(feature = "tls")]
    #[test]
    fn v24lvi_default_connector_has_no_pin_set() {
        // Back-compat: a connector built WITHOUT calling
        // with_certificate_pins() carries no pin set, so existing
        // callers that rely on rustls-only validation are unaffected.
        let connector = TlsConnectorBuilder::new()
            .add_root_certificate(&Certificate::from_der(TEST_CERT_PEM.to_vec()))
            .build()
            .expect("build without pins");
        assert!(
            connector.pin_set.is_none(),
            "default connector must not have an implicit pin set"
        );
    }

    #[cfg(feature = "tls")]
    #[test]
    fn v24lvi_mismatched_pin_returns_error_via_pin_set_validate() {
        // The connector wires CertificatePinSet::validate into the
        // post-handshake gate. We verify the validate semantics here
        // (the unit-of-fix for the connector's gate logic) — the
        // gate's *invocation* is exercised end-to-end by integration
        // tests that need a real TLS handshake. Without a synthetic
        // stream the connect() path can't run in a unit test, so
        // pinning the validate semantics + the wiring (above) is
        // the maximal regression we can land here.
        let cert = Certificate::from_der(TEST_CERT_PEM.to_vec());
        let mut mismatched = CertificatePinSet::new();
        mismatched
            .add_spki_sha256_base64("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
            .expect("valid base64");
        let result = mismatched.validate(&cert);
        assert!(
            result.is_err(),
            "mismatched-pin enforcement-on validation must Err; \
             got {result:?}. This is the failure that the connector \
             gate now propagates as TlsError to abort the connection."
        );
    }

    #[cfg(feature = "tls")]
    #[test]
    fn v24lvi_report_only_mismatched_pin_does_not_error() {
        // Symmetry check: report-only sets surface as Ok(false) (not
        // Err) which the connector gate explicitly treats as
        // "log-and-continue" — verifies the connector's match-arm
        // handles the no-enforcement code path correctly without
        // tearing down the connection.
        let cert = Certificate::from_der(TEST_CERT_PEM.to_vec());
        let mut report_only = CertificatePinSet::report_only();
        report_only
            .add_spki_sha256_base64("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
            .expect("valid base64");
        let result = report_only.validate(&cert);
        assert!(
            matches!(result, Ok(false)),
            "report-only mismatched pin must return Ok(false) (not Err); \
             got {result:?}"
        );
    }

    // ── br-asupersync-y0gm5q: 0-RTT secure-by-default ────────────────

    #[cfg(feature = "tls")]
    #[test]
    fn y0gm5q_default_connector_disables_0rtt_early_data() {
        let connector = TlsConnectorBuilder::new()
            .add_root_certificate(&Certificate::from_der(TEST_CERT_PEM.to_vec()))
            .build()
            .expect("build default connector");
        assert!(
            !connector.config.enable_early_data,
            "default connector must have enable_early_data=false \
             (TLS 1.3 0-RTT disabled — replay defense)"
        );
    }

    #[cfg(feature = "tls")]
    #[test]
    fn y0gm5q_enable_early_data_opt_in_sets_flag() {
        let connector = TlsConnectorBuilder::new()
            .add_root_certificate(&Certificate::from_der(TEST_CERT_PEM.to_vec()))
            .enable_early_data(true)
            .build()
            .expect("build with early data enabled");
        assert!(
            connector.config.enable_early_data,
            "enable_early_data(true) must propagate to ClientConfig"
        );
    }

    #[cfg(feature = "tls")]
    #[test]
    fn y0gm5q_enable_early_data_false_disables_flag() {
        let connector = TlsConnectorBuilder::new()
            .add_root_certificate(&Certificate::from_der(TEST_CERT_PEM.to_vec()))
            .enable_early_data(true)
            .enable_early_data(false)
            .build()
            .expect("build with early data toggled off");
        assert!(
            !connector.config.enable_early_data,
            "enable_early_data(false) must reset enable_early_data flag"
        );
    }

    /// br-asupersync-h41wya — `enable_early_data(true)` without
    /// `acknowledge_zero_rtt_replay_risk()` MUST cause `build()` to
    /// return a Configuration error.
    #[cfg(feature = "tls")]
    #[test]
    fn build_rejects_zero_rtt_without_risk_acknowledgement() {
        let certs = Certificate::from_pem(TEST_CERT_PEM).unwrap();
        let err = TlsConnectorBuilder::new()
            .insecure_add_root_certificate(&certs[0])
            .enable_early_data(true)
            .build()
            .expect_err("0-RTT without risk ack must be rejected");
        match err {
            TlsError::Configuration(msg) => assert!(
                msg.contains("acknowledge_zero_rtt_replay_risk"),
                "unexpected error message: {msg}"
            ),
            other => panic!("expected Configuration error, got {other:?}"),
        }
    }

    /// br-asupersync-h41wya — once acknowledged, 0-RTT enables
    /// successfully on the produced connector.
    #[cfg(feature = "tls")]
    #[test]
    fn build_accepts_zero_rtt_with_risk_acknowledgement() {
        let certs = Certificate::from_pem(TEST_CERT_PEM).unwrap();
        let connector = TlsConnectorBuilder::new()
            .insecure_add_root_certificate(&certs[0])
            .enable_early_data(true)
            .acknowledge_zero_rtt_replay_risk()
            .build()
            .expect("build should succeed once risk is acknowledged");
        assert!(
            connector.config.enable_early_data,
            "0-RTT must be enabled when both flags are set"
        );
    }

    /// br-asupersync-sx6j9y — `with_strict_ca_validation` rejects a
    /// non-CA leaf cert from `add_root_certificate`. Without the
    /// flag, the same cert is accepted (legacy behavior preserved).
    #[cfg(feature = "tls")]
    #[test]
    fn add_root_certificate_strict_ca_rejects_self_signed_leaf() {
        let leaf_certs = Certificate::from_pem(TEST_CERT_PEM).unwrap();
        let leaf = leaf_certs.into_iter().next().unwrap();

        // Strict mode: rejected.
        let strict = TlsConnectorBuilder::new()
            .with_strict_ca_validation()
            .add_root_certificate(&leaf);
        assert!(
            strict.root_certs.is_empty(),
            "strict-CA mode must reject the self-signed leaf"
        );

        // Permissive default: accepted (legacy).
        let permissive = TlsConnectorBuilder::new().add_root_certificate(&leaf);
        assert_eq!(
            permissive.root_certs.len(),
            1,
            "permissive default must still accept the cert"
        );

        // Insecure bypass: accepted even in strict mode.
        let bypassed = TlsConnectorBuilder::new()
            .with_strict_ca_validation()
            .insecure_add_root_certificate(&leaf);
        assert_eq!(
            bypassed.root_certs.len(),
            1,
            "insecure_add_root_certificate must bypass the strict gate"
        );
    }

    /// br-asupersync-sx6j9y — `enable_env_cert_loading` flips the
    /// strict-CA gate as a side effect, so the operator who opts
    /// into env-cert loading does NOT silently leave the direct
    /// add_root_certificate path ungated.
    #[cfg(feature = "tls")]
    #[test]
    fn enable_env_cert_loading_implies_strict_ca_validation() {
        let builder = TlsConnectorBuilder::new().enable_env_cert_loading();
        assert!(
            builder.validate_ca_constraints,
            "enable_env_cert_loading must set validate_ca_constraints=true"
        );
    }

    /// Regression test for asupersync-2o602p: Verify that production builds
    /// properly reject leaf certificates when strict validation is enabled,
    /// preventing MITM attacks via misconfigured trust stores.
    #[cfg(feature = "tls")]
    #[test]
    fn production_cert_validation_rejects_leaf_certificates() {
        let leaf_certs = Certificate::from_pem(TEST_CERT_PEM).unwrap();
        let leaf = leaf_certs.into_iter().next().unwrap();

        // Production mode with strict validation: must reject leaf certificates
        let builder = TlsConnectorBuilder::new()
            .with_strict_ca_validation()
            .add_root_certificate(&leaf);

        assert!(
            builder.root_certs.is_empty(),
            "Production builds with strict validation must reject leaf certificates"
        );

        // Should succeed to build even with empty root store (will use system roots)
        // The key is that the leaf cert was properly rejected
        let result = builder.build();
        assert!(result.is_ok(), "Builder should succeed with system roots");
    }

    /// Regression test for asupersync-2o602p: Verify that the insecure bypass
    /// method is only available in test builds, not production.
    #[cfg(feature = "tls")]
    #[test]
    fn insecure_add_root_certificate_restricted_to_tests() {
        // This test verifies the method exists in test builds (where this test runs)
        let leaf_certs = Certificate::from_pem(TEST_CERT_PEM).unwrap();
        let leaf = leaf_certs.into_iter().next().unwrap();

        let builder = TlsConnectorBuilder::new().insecure_add_root_certificate(&leaf);

        assert_eq!(
            builder.root_certs.len(),
            1,
            "insecure_add_root_certificate should work in test builds"
        );

        // In production builds, this method should not be available
        // This is enforced at compile time by #[cfg(test)]
        // If someone tries to use it in production, they'll get a compile error:
        // "cannot find method `insecure_add_root_certificate`"
    }
}