eggfetch-core 0.3.0

Async-first Rust HTTP client engine (tokio + hyper) with connection pooling, phase-aware timeouts, TLS, proxies, and compression
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
//! TLS configuration for the eggfetch client.
//!
//! Provides [`TlsConfig`] and [`TlsConfigBuilder`] for controlling TLS
//! behavior: trust stores, custom CA bundles, client certificates,
//! verification policy, TLS version bounds, and SNI.
//!
//! # Defaults
//!
//! - Hostname verification is enabled.
//! - Certificate-chain verification is enabled.
//! - When `tls-native-roots` is enabled, native system roots are preferred and
//!   packaged `WebPKI` roots are used as a construction fallback when native
//!   roots are unavailable. Without that feature, packaged `WebPKI` roots are
//!   the default.
//! - TLS 1.2 and 1.3 are supported.
//! - SNI is enabled by default.
//!
//! # Custom CA bundles
//!
//! A custom CA bundle replaces the default root store (it does not
//! augment). The bundle is loaded at construction time; malformed or
//! empty bundles are rejected immediately.
//!
//! # Safety
//!
//! Disabling certificate verification (`verify = false`) weakens TLS
//! guarantees. It should only be used for testing or against known
//! trusted targets. The Python binding documents this in the `verify`
//! parameter docstring.

use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::sync::OnceLock;

use rustls::pki_types::{CertificateDer, PrivateKeyDer};

use crate::error::{Error, Result};

/// Monotonic source for opaque TLS connection-policy tokens.
///
/// Each independently built `TlsConfig` mints a fresh token; `Clone` shares
/// the token. The value is never rendered in diagnostics and carries no key
/// material — it is only an equality token for reusable-client caches. `0`
/// is reserved for "no TLS config" in route keys, so issuance starts at `1`.
static TLS_POLICY_TOKEN_NEXT: AtomicU64 = AtomicU64::new(1);

/// Mint a fresh opaque policy token for a newly built or mutated `TlsConfig`.
fn mint_tls_policy_token() -> Arc<u64> {
    // Skip `0` (reserved for "no TLS config"). Each `fetch_add` return value
    // is distinct, so retrying on `0` cannot collide with a concurrent minter.
    loop {
        let id = TLS_POLICY_TOKEN_NEXT.fetch_add(1, Ordering::Relaxed);
        if id != 0 {
            return Arc::new(id);
        }
    }
}

/// Trust store source for certificate verification.
#[derive(Debug, Clone, Default)]
pub enum TrustStore {
    /// Use native system roots with packaged `WebPKI` roots as a construction
    /// fallback when `tls-native-roots` is enabled. Without that feature, the
    /// default builder uses packaged `WebPKI` roots directly.
    ///
    /// When native loading fails, construction succeeds on `WebPKI` roots.
    /// Per-path causes are emitted only via `tracing::warn` with feature
    /// `tracing`; without it the substitution is silent. Callers who must
    /// detect the fallback should build with [`TrustStore::NativeOnly`],
    /// which fails closed, or enable `tracing`.
    #[default]
    NativeWithWebPkiFallback,
    /// Use only native system roots. Fails at construction if the
    /// platform root store is unavailable.
    NativeOnly,
    /// Use only packaged Mozilla/WebPKI roots. Does not consult the
    /// operating system trust store.
    WebPkiOnly,
    /// Use the provided CA certificates as the sole trust anchor.
    /// These replace all other roots.
    Custom(Vec<CertificateDer<'static>>),
}

/// A client certificate and private key for mTLS.
#[derive(Clone)]
pub enum ClientIdentity {
    /// A certificate chain and private key in DER format.
    Pem {
        /// The certificate chain, in DER bytes.
        cert_chain: Vec<CertificateDer<'static>>,
        /// The private key, as raw DER bytes.
        private_key_der: Vec<u8>,
        /// The label from the PEM block (e.g., "PRIVATE KEY", "RSA PRIVATE KEY").
        key_label: String,
    },
}

impl std::fmt::Debug for ClientIdentity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Pem {
                cert_chain,
                key_label,
                ..
            } => f
                .debug_struct("ClientIdentity::Pem")
                .field("cert_count", &cert_chain.len())
                .field("key_label", key_label)
                .finish_non_exhaustive(),
        }
    }
}

/// Minimum or maximum TLS protocol version.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum TlsVersion {
    /// TLS 1.2.
    Tls12,
    /// TLS 1.3.
    Tls13,
}

impl TlsVersion {
    fn to_rustls(self) -> &'static rustls::SupportedProtocolVersion {
        match self {
            Self::Tls12 => &rustls::version::TLS12,
            Self::Tls13 => &rustls::version::TLS13,
        }
    }
}

/// Immutable shared TLS configuration for a client.
///
/// Construct via [`TlsConfig::builder()`] or [`TlsConfig::builder_with_defaults()`].
#[derive(Clone)]
pub struct TlsConfig {
    trust_store: TrustStore,
    custom_ca_roots: Vec<CertificateDer<'static>>,
    additional_ca_roots: Vec<CertificateDer<'static>>,
    crypto_provider: Option<Arc<rustls::crypto::CryptoProvider>>,
    client_identity: Option<ClientIdentity>,
    verify_hostname: bool,
    verify_certificate: bool,
    min_version: Option<TlsVersion>,
    max_version: Option<TlsVersion>,
    sni_enabled: bool,
    root_store: Arc<OnceLock<Result<rustls::RootCertStore>>>,
    /// Opaque connection-policy identity shared by unchanged clones.
    ///
    /// Any operation that creates a `TlsConfig` with changed
    /// connection-affecting semantics mints a new token. The token is
    /// crate-private, never rendered, and carries no key material. The
    /// lazily built `root_store` cache is an implementation cache only and
    /// never participates in identity on its own.
    policy_token: Arc<u64>,
}

impl std::fmt::Debug for TlsConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TlsConfig")
            .field("trust_store", &self.trust_store)
            .field("has_custom_ca", &!self.custom_ca_roots.is_empty())
            .field("additional_ca_count", &self.additional_ca_roots.len())
            .field(
                "has_explicit_crypto_provider",
                &self.crypto_provider.is_some(),
            )
            .field("has_client_identity", &self.client_identity.is_some())
            .field("verify_hostname", &self.verify_hostname)
            .field("verify_certificate", &self.verify_certificate)
            .field("min_version", &self.min_version)
            .field("max_version", &self.max_version)
            .field("sni_enabled", &self.sni_enabled)
            .finish_non_exhaustive()
    }
}

impl Default for TlsConfig {
    fn default() -> Self {
        Self::builder().build()
    }
}

impl TlsConfig {
    /// Return an opaque identity for internal connection-client caches.
    ///
    /// Cloned configurations share this identity; separately constructed
    /// configurations do not pool together even when their visible settings
    /// happen to match, and any consuming mutator that changes
    /// connection-affecting policy mints a new token. The value is never
    /// exposed in diagnostics and carries no key material.
    ///
    /// Field/mutator inventory (all connection-affecting): trust-store
    /// selection and custom/additional CA roots, explicit crypto provider,
    /// mTLS client identity, `verify_hostname` / `verify_certificate`
    /// (including `danger_accept_invalid_certs`), min/max TLS versions, and
    /// SNI enablement. The lazily built `root_store` cache is explicitly
    /// excluded: clones share it, but sharing it no longer implies
    /// compatibility.
    #[cfg(all(feature = "proxy", feature = "tls-rustls"))]
    pub(crate) fn connection_identity(&self) -> u64 {
        *self.policy_token
    }

    /// Create a builder with secure defaults (verification enabled, native
    /// roots preferred, SNI enabled).
    #[must_use]
    pub fn builder() -> TlsConfigBuilder {
        TlsConfigBuilder::new()
    }

    /// Create a builder from the default configuration.
    ///
    /// This is identical to [`TlsConfig::builder()`] and exists for
    /// discoverability.
    #[must_use]
    pub fn builder_with_defaults() -> TlsConfigBuilder {
        Self::builder()
    }

    /// Enable or disable certificate and hostname verification while
    /// retaining the rest of this configuration.
    ///
    /// This mints a fresh opaque connection identity: a clone modified this
    /// way must never compare as cache-compatible with its parent, even
    /// though both share the same lazily built root-store cache.
    #[must_use]
    pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
        self.verify_certificate = !accept;
        self.verify_hostname = !accept;
        self.policy_token = mint_tls_policy_token();
        self
    }

    /// Build a `tokio_rustls::TlsConnector` from this TLS configuration.
    ///
    /// This is the convenience entry point for
    /// [`crate::network_stream::UpgradedStream::start_tls`] and other
    /// contexts where a generic TLS upgrade must reflect the full
    /// configured policy (custom CA, verification, SNI, version bounds,
    /// client identity).
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying rustls configuration cannot be
    /// built (see [`Self::build_rustls_config`]).
    pub fn tls_connector(&self) -> Result<tokio_rustls::TlsConnector> {
        let config = self.build_rustls_config()?;
        Ok(tokio_rustls::TlsConnector::from(Arc::new(config)))
    }

    /// Build a `rustls::ClientConfig` from this TLS configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if the trust store, client certificates, or
    /// protocol versions cannot be configured.
    pub fn build_rustls_config(&self) -> Result<rustls::ClientConfig> {
        let root_store = self.build_root_store()?;

        let mut protocol_versions = Vec::new();
        match (self.min_version, self.max_version) {
            (Some(min), Some(max)) => {
                if min > max {
                    return Err(Error::TlsConfig(format!(
                        "invalid TLS version range: min ({min:?}) > max ({max:?})"
                    )));
                }
                for v in Self::supported_versions() {
                    if v >= min && v <= max {
                        protocol_versions.push(v.to_rustls());
                    }
                }
            }
            (Some(min), None) => {
                for v in Self::supported_versions() {
                    if v >= min {
                        protocol_versions.push(v.to_rustls());
                    }
                }
            }
            (None, Some(max)) => {
                for v in Self::supported_versions() {
                    if v <= max {
                        protocol_versions.push(v.to_rustls());
                    }
                }
            }
            (None, None) => {
                for v in Self::supported_versions() {
                    protocol_versions.push(v.to_rustls());
                }
            }
        }

        if protocol_versions.is_empty() {
            return Err(Error::TlsConfig(
                "no supported TLS versions in configured range".into(),
            ));
        }

        let provider = self.resolve_crypto_provider()?;
        let supported_schemes = provider
            .signature_verification_algorithms
            .supported_schemes();
        let mut config = if self.verify_certificate && self.verify_hostname {
            rustls::ClientConfig::builder_with_provider(provider.clone())
                .with_protocol_versions(&protocol_versions)
                .map_err(|e| Error::TlsConfig(format!("TLS version config: {e}")))?
                .with_root_certificates(root_store)
                .with_no_client_auth()
        } else if self.verify_certificate {
            rustls::ClientConfig::builder_with_provider(provider.clone())
                .with_protocol_versions(&protocol_versions)
                .map_err(|e| Error::TlsConfig(format!("TLS version config: {e}")))?
                .dangerous()
                .with_custom_certificate_verifier(no_hostname_verifier(
                    &root_store,
                    provider.clone(),
                )?)
                .with_no_client_auth()
        } else {
            rustls::ClientConfig::builder_with_provider(provider.clone())
                .with_protocol_versions(&protocol_versions)
                .map_err(|e| Error::TlsConfig(format!("TLS version config: {e}")))?
                .dangerous()
                .with_custom_certificate_verifier(Arc::new(NoVerifier { supported_schemes }))
                .with_no_client_auth()
        };

        // Default ALPN advertises both protocols when HTTP/2 is compiled in.
        // Callers enforcing `HttpVersionPolicy` must override via
        // `crate::client::configure_tls_alpn` (used by all client paths).
        // Direct use of `build_rustls_config` without override intentionally
        // retains this default; an empty default would silently downgrade
        // `tls_connector`/`start_tls` users to HTTP/1.1.
        #[cfg(feature = "transport-http2")]
        {
            config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
        }
        #[cfg(not(feature = "transport-http2"))]
        {
            config.alpn_protocols = vec![b"http/1.1".to_vec()];
        }
        config.enable_sni = self.sni_enabled;

        if let Some(identity) = &self.client_identity {
            config.client_auth_cert_resolver = Arc::new(SingleCertResolver::new(
                identity.clone(),
                provider.as_ref(),
            )?);
        }

        Ok(config)
    }

    /// Build the root certificate store from the configured trust policy.
    fn build_root_store(&self) -> Result<rustls::RootCertStore> {
        self.root_store
            .get_or_init(|| self.build_root_store_uncached())
            .clone()
    }

    fn build_root_store_uncached(&self) -> Result<rustls::RootCertStore> {
        let mut roots = match &self.trust_store {
            // Explicit opt-in fallback: `NativeWithWebPkiFallback` silently
            // uses WebPKI roots when native loading fails or yields empty
            // (silent without the `tracing` feature). Fail-closed callers
            // must select `NativeOnly` instead.
            TrustStore::NativeWithWebPkiFallback => match Self::try_native_roots() {
                Ok(store) if !store.is_empty() => Ok(store),
                _ => Ok(Self::webpki_roots()),
            },
            TrustStore::NativeOnly => Self::try_native_roots(),
            TrustStore::WebPkiOnly => Ok(Self::webpki_roots()),
            TrustStore::Custom(certs) => {
                if certs.is_empty() {
                    return Err(Error::CaBundle("custom CA bundle is empty".into()));
                }
                let mut store = rustls::RootCertStore::empty();
                for cert in certs {
                    store
                        .add(cert.clone())
                        .map_err(|e| Error::CaBundle(format!("invalid CA certificate: {e}")))?;
                }
                Ok(store)
            }
        }?;

        for cert in &self.additional_ca_roots {
            roots
                .add(cert.clone())
                .map_err(|e| Error::CaBundle(format!("invalid additional CA certificate: {e}")))?;
        }
        Ok(roots)
    }

    #[cfg(not(feature = "tls-native-roots"))]
    fn try_native_roots() -> Result<rustls::RootCertStore> {
        Err(Error::TlsConfig(
            "native root certificates are disabled; enable tls-native-roots".into(),
        ))
    }

    #[cfg(feature = "tls-native-roots")]
    fn try_native_roots() -> Result<rustls::RootCertStore> {
        let mut roots = rustls::RootCertStore::empty();

        #[cfg(target_os = "linux")]
        let pem_paths: &[&str] = &[
            "/etc/ssl/certs/ca-certificates.crt",
            "/etc/pki/tls/certs/ca-bundle.crt",
            "/etc/ssl/ca-bundle.pem",
        ];

        #[cfg(target_os = "macos")]
        let pem_paths: &[&str] = &["/etc/ssl/cert.pem", "/usr/local/etc/openssl/cert.pem"];

        #[cfg(any(target_os = "linux", target_os = "macos"))]
        for path in pem_paths {
            match load_pem_certs_from_path(Path::new(path)) {
                Ok(certs) => {
                    for cert in certs {
                        if let Err(e) = roots.add(cert) {
                            #[cfg(feature = "tracing")]
                            tracing::warn!(
                                "eggfetch: skipped invalid CA certificate in {path}: {e}"
                            );
                            #[cfg(not(feature = "tracing"))]
                            let _ = (path, &e);
                        }
                    }
                }
                Err(e) => {
                    // A missing or unreadable system bundle silently falls
                    // back toward WebPKI roots below; log it so operators
                    // have a signal instead of a silent trust change.
                    #[cfg(feature = "tracing")]
                    tracing::warn!("eggfetch: failed to load native CA bundle {path}: {e}");
                    #[cfg(not(feature = "tracing"))]
                    let _ = (path, &e);
                }
            }
        }

        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
        {
            for cert in rustls_native_certs::load_native_certs().certs {
                if let Err(e) = roots.add(cert) {
                    #[cfg(feature = "tracing")]
                    tracing::warn!("eggfetch: skipped invalid native CA certificate: {e}");
                    #[cfg(not(feature = "tracing"))]
                    let _ = &e;
                }
            }
        }

        if roots.is_empty() {
            return Err(Error::TlsConfig(
                "native root certificates not available".into(),
            ));
        }
        Ok(roots)
    }

    fn webpki_roots() -> rustls::RootCertStore {
        let mut roots = rustls::RootCertStore::empty();
        roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
        roots
    }

    fn supported_versions() -> impl Iterator<Item = TlsVersion> {
        [TlsVersion::Tls12, TlsVersion::Tls13].into_iter()
    }

    /// Returns `true` if hostname verification is enabled.
    #[must_use]
    pub fn verify_hostname(&self) -> bool {
        self.verify_hostname
    }

    /// Returns `true` if certificate verification is enabled.
    #[must_use]
    pub fn verify_certificate(&self) -> bool {
        self.verify_certificate
    }

    /// Returns `true` if SNI is enabled.
    #[must_use]
    pub fn sni_enabled(&self) -> bool {
        self.sni_enabled
    }

    /// Returns whether this configuration carries an explicitly selected
    /// Rustls crypto provider.
    #[must_use]
    pub fn has_explicit_crypto_provider(&self) -> bool {
        self.crypto_provider.is_some()
    }

    /// Build the provider used by this configuration without changing the
    /// process-wide Rustls provider.
    fn resolve_crypto_provider(&self) -> Result<Arc<rustls::crypto::CryptoProvider>> {
        if let Some(provider) = &self.crypto_provider {
            return Ok(provider.clone());
        }
        process_crypto_provider()
    }

    /// Build a `rustls::ClientConfig` for QUIC (TLS 1.3 only, ALPN `h3`).
    ///
    /// This differs from [`build_rustls_config`](Self::build_rustls_config)
    /// by restricting to TLS 1.3 and using the `h3` ALPN.
    ///
    /// # Errors
    ///
    /// Returns an error if the trust store, client certificates, or
    /// protocol versions cannot be configured.
    #[allow(
        dead_code,
        reason = "the QUIC client config is only built by the HTTP/3 transport, which is compiled out when the http3 feature is disabled"
    )]
    pub(crate) fn build_quic_rustls_config(&self) -> Result<rustls::ClientConfig> {
        let root_store = self.build_root_store()?;

        let provider = self.resolve_crypto_provider()?;
        let supported_schemes = provider
            .signature_verification_algorithms
            .supported_schemes();
        let mut config = if self.verify_certificate && self.verify_hostname {
            rustls::ClientConfig::builder_with_provider(provider.clone())
                .with_protocol_versions(&[&rustls::version::TLS13])
                .map_err(|e| Error::Tls(format!("TLS version config: {e}")))?
                .with_root_certificates(root_store)
                .with_no_client_auth()
        } else if self.verify_certificate {
            rustls::ClientConfig::builder_with_provider(provider.clone())
                .with_protocol_versions(&[&rustls::version::TLS13])
                .map_err(|e| Error::Tls(format!("TLS version config: {e}")))?
                .dangerous()
                .with_custom_certificate_verifier(no_hostname_verifier(
                    &root_store,
                    provider.clone(),
                )?)
                .with_no_client_auth()
        } else {
            rustls::ClientConfig::builder_with_provider(provider.clone())
                .with_protocol_versions(&[&rustls::version::TLS13])
                .map_err(|e| Error::Tls(format!("TLS version config: {e}")))?
                .dangerous()
                .with_custom_certificate_verifier(Arc::new(NoVerifier { supported_schemes }))
                .with_no_client_auth()
        };

        config.alpn_protocols = vec![b"h3".to_vec()];
        config.enable_sni = self.sni_enabled;

        if let Some(identity) = &self.client_identity {
            config.client_auth_cert_resolver = Arc::new(SingleCertResolver::new(
                identity.clone(),
                provider.as_ref(),
            )?);
        }

        Ok(config)
    }
}

/// Builder for constructing a [`TlsConfig`].
pub struct TlsConfigBuilder {
    trust_store: TrustStore,
    custom_ca_roots: Vec<CertificateDer<'static>>,
    additional_ca_roots: Vec<CertificateDer<'static>>,
    crypto_provider: Option<Arc<rustls::crypto::CryptoProvider>>,
    client_identity: Option<ClientIdentity>,
    verify_hostname: bool,
    verify_certificate: bool,
    min_version: Option<TlsVersion>,
    max_version: Option<TlsVersion>,
    sni_enabled: bool,
}

impl Default for TlsConfigBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl TlsConfigBuilder {
    /// Create a new builder with secure defaults.
    #[must_use]
    pub fn new() -> Self {
        Self {
            trust_store: TrustStore::NativeWithWebPkiFallback,
            custom_ca_roots: Vec::new(),
            additional_ca_roots: Vec::new(),
            crypto_provider: None,
            client_identity: None,
            verify_hostname: true,
            verify_certificate: true,
            min_version: None,
            max_version: None,
            sni_enabled: true,
        }
    }

    /// Set the trust store source.
    #[must_use]
    pub fn trust_store(mut self, store: TrustStore) -> Self {
        self.trust_store = store;
        self
    }

    /// Load CA certificates from a PEM file, replacing any existing trust
    /// store configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be read or the PEM data is
    /// malformed.
    pub fn ca_certificate_path(mut self, path: impl AsRef<Path>) -> Result<Self> {
        let certs = load_pem_certs_from_path(path.as_ref())?;
        if certs.is_empty() {
            // Fail closed for the replace variant: a typo'd empty directory
            // must not silently leave the previous trust store in place.
            return Err(Error::CaBundle(format!(
                "no certificates found in {}",
                path.as_ref().display()
            )));
        }
        self.custom_ca_roots = certs;
        self.trust_store = TrustStore::Custom(self.custom_ca_roots.clone());
        Ok(self)
    }

    /// Add CA certificates from a PEM file or certificate directory to the
    /// configured custom trust store, replacing the default trust store if
    /// this is the first custom source.
    ///
    /// Duplicate certificates are ignored. This is useful when multiple
    /// environment-provided CA sources are combined.
    ///
    /// # Errors
    ///
    /// Returns an error if the path cannot be read or contains no PEM
    /// certificates. Empty directories are ignored.
    pub fn add_ca_certificate_path(mut self, path: impl AsRef<Path>) -> Result<Self> {
        let certs = load_pem_certs_from_path(path.as_ref())?;
        if certs.is_empty() {
            if path.as_ref().is_dir() {
                return Ok(self);
            }
            return Err(Error::CaBundle(format!(
                "no certificates found in {}",
                path.as_ref().display()
            )));
        }
        if !matches!(&self.trust_store, TrustStore::Custom(_)) {
            self.custom_ca_roots.clear();
        }
        for cert in certs {
            if !self
                .custom_ca_roots
                .iter()
                .any(|existing| existing.as_ref() == cert.as_ref())
            {
                self.custom_ca_roots.push(cert);
            }
        }
        self.trust_store = TrustStore::Custom(self.custom_ca_roots.clone());
        Ok(self)
    }

    /// Load additional CA certificates from a PEM file or certificate
    /// directory. Additional roots augment the selected base trust store;
    /// unlike [`Self::ca_certificate_path`], they do not replace it.
    ///
    /// Existing [`Self::add_ca_certificate_path`] behavior is intentionally
    /// unchanged: that method continues to build a replacement custom set.
    ///
    /// # Errors
    ///
    /// Returns an error if the path cannot be read or contains malformed
    /// certificate data. Empty directories are ignored, matching the
    /// existing path-based CA API.
    pub fn additional_ca_certificate_path(mut self, path: impl AsRef<Path>) -> Result<Self> {
        let certs = load_pem_certs_from_path(path.as_ref())?;
        if certs.is_empty() {
            if path.as_ref().is_dir() {
                return Ok(self);
            }
            return Err(Error::CaBundle(format!(
                "no certificates found in {}",
                path.as_ref().display()
            )));
        }
        append_unique_certs(&mut self.additional_ca_roots, certs);
        Ok(self)
    }

    /// Load CA certificates from PEM bytes, replacing any existing trust
    /// store configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if the PEM data is malformed or empty.
    pub fn ca_certificate_pem(mut self, pem_bytes: &[u8]) -> Result<Self> {
        let certs = parse_pem_certificates(pem_bytes)?;
        if certs.is_empty() {
            return Err(Error::CaBundle("no certificates found in PEM data".into()));
        }
        self.custom_ca_roots = certs;
        self.trust_store = TrustStore::Custom(self.custom_ca_roots.clone());
        Ok(self)
    }

    /// Load CA certificates from DER bytes, replacing any existing trust
    /// store configuration.
    ///
    /// Each certificate is expected as raw DER-encoded X.509 data
    /// (without PEM framing).
    ///
    /// # Errors
    ///
    /// Returns an error if no certificates are provided.
    pub fn ca_certificate_der(mut self, der_certs: Vec<Vec<u8>>) -> Result<Self> {
        let certs: Vec<CertificateDer<'static>> =
            der_certs.into_iter().map(CertificateDer::from).collect();
        if certs.is_empty() {
            return Err(Error::CaBundle("no DER certificates provided".into()));
        }
        self.custom_ca_roots = certs;
        self.trust_store = TrustStore::Custom(self.custom_ca_roots.clone());
        Ok(self)
    }

    /// Load additional CA certificates from PEM bytes. The certificates are
    /// added to the selected base trust store rather than replacing it.
    ///
    /// # Errors
    ///
    /// Returns an error if the PEM data is malformed or contains no
    /// certificates.
    pub fn additional_ca_certificate_pem(mut self, pem_bytes: &[u8]) -> Result<Self> {
        let certs = parse_pem_certificates(pem_bytes)?;
        if certs.is_empty() {
            return Err(Error::CaBundle(
                "no certificates found in additional PEM data".into(),
            ));
        }
        append_unique_certs(&mut self.additional_ca_roots, certs);
        Ok(self)
    }

    /// Load additional CA certificates from raw DER values. The certificates
    /// are added to the selected base trust store rather than replacing it.
    ///
    /// # Errors
    ///
    /// Returns an error if no certificates are supplied.
    pub fn additional_ca_certificate_der(mut self, der_certs: Vec<Vec<u8>>) -> Result<Self> {
        if der_certs.is_empty() {
            return Err(Error::CaBundle(
                "no additional DER certificates provided".into(),
            ));
        }
        append_unique_certs(
            &mut self.additional_ca_roots,
            der_certs.into_iter().map(CertificateDer::from),
        );
        Ok(self)
    }

    /// Use an explicitly supplied Rustls crypto provider for this
    /// configuration. The provider is local to the resulting [`TlsConfig`]
    /// and is never installed as the process-wide default.
    #[must_use]
    pub fn crypto_provider(mut self, provider: Arc<rustls::crypto::CryptoProvider>) -> Self {
        self.crypto_provider = Some(provider);
        self
    }

    /// Set the client identity for mTLS.
    #[must_use]
    pub fn client_identity(mut self, identity: ClientIdentity) -> Self {
        self.client_identity = Some(identity);
        self
    }

    /// Load a client certificate and private key from PEM files.
    ///
    /// # Errors
    ///
    /// Returns an error if the files cannot be read or the PEM data is
    /// malformed.
    pub fn client_cert_path(
        self,
        cert_path: impl AsRef<Path>,
        key_path: impl AsRef<Path>,
    ) -> Result<Self> {
        let certs = load_pem_certs_from_path(cert_path.as_ref())?;
        if certs.is_empty() {
            return Err(Error::ClientCert(format!(
                "no certificates found in {}",
                cert_path.as_ref().display()
            )));
        }

        let key_bytes = std::fs::read(key_path.as_ref()).map_err(|e| {
            Error::PrivateKey(format!(
                "failed to read private key {}: {e}",
                key_path.as_ref().display()
            ))
        })?;
        let (key_data, key_label) = parse_private_key(&key_bytes)?;

        Ok(self.client_identity(ClientIdentity::Pem {
            cert_chain: certs,
            private_key_der: key_data,
            key_label,
        }))
    }

    /// Enable or disable hostname verification.
    ///
    /// When disabled, the client does not verify that the server's
    /// certificate matches the requested hostname. This is insecure
    /// and should only be used for testing.
    #[must_use]
    pub fn verify_hostname(mut self, enabled: bool) -> Self {
        self.verify_hostname = enabled;
        self
    }

    /// Enable or disable certificate verification.
    ///
    /// When disabled (`danger_accept_invalid_certs(true)`), the client
    /// does not verify the server's certificate chain or hostname.
    /// This is **insecure** and should only be used for testing against
    /// known self-signed certificates.
    #[must_use]
    pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
        self.verify_certificate = !accept;
        self.verify_hostname = !accept;
        self
    }

    /// Set the minimum TLS version.
    #[must_use]
    pub fn min_tls_version(mut self, version: TlsVersion) -> Self {
        self.min_version = Some(version);
        self
    }

    /// Set the maximum TLS version.
    #[must_use]
    pub fn max_tls_version(mut self, version: TlsVersion) -> Self {
        self.max_version = Some(version);
        self
    }

    /// Enable or disable SNI (Server Name Indication).
    ///
    /// Disabling SNI can break hostname verification and virtual-host
    /// routing. It should rarely be necessary.
    #[must_use]
    pub fn sni(mut self, enabled: bool) -> Self {
        self.sni_enabled = enabled;
        self
    }

    /// Build the [`TlsConfig`].
    ///
    /// Each call mints a fresh opaque connection identity, even for
    /// structurally identical policy. Unchanged `Clone`s share identity;
    /// separate builds never pool together implicitly.
    #[must_use]
    pub fn build(self) -> TlsConfig {
        TlsConfig {
            trust_store: self.trust_store,
            custom_ca_roots: self.custom_ca_roots,
            additional_ca_roots: self.additional_ca_roots,
            crypto_provider: self.crypto_provider,
            client_identity: self.client_identity,
            verify_hostname: self.verify_hostname,
            verify_certificate: self.verify_certificate,
            min_version: self.min_version,
            max_version: self.max_version,
            sni_enabled: self.sni_enabled,
            root_store: Arc::new(OnceLock::new()),
            policy_token: mint_tls_policy_token(),
        }
    }
}

/// A certificate verifier that accepts all certificates (unsafe).
#[derive(Debug)]
struct NoVerifier {
    supported_schemes: Vec<rustls::SignatureScheme>,
}

pub(crate) fn process_crypto_provider() -> Result<Arc<rustls::crypto::CryptoProvider>> {
    if let Some(provider) = rustls::crypto::CryptoProvider::get_default() {
        return Ok(provider.clone());
    }

    // Explicitly install the provider implied by the selected crate features.
    // Relying on `ClientConfig::builder()` to install the provider as a side
    // effect is fragile: a future rustls change or a pre-installed custom
    // provider could leave `get_default()` as `None` or mismatched.
    #[cfg(feature = "tls-rustls")]
    {
        // `CryptoProvider::get_default` was None above, so no provider is
        // installed yet. Try to install the feature-selected provider
        // explicitly before falling back to the builder side-effect.
        let provider = rustls::crypto::ring::default_provider();
        let _ = provider.install_default();
        if let Some(provider) = rustls::crypto::CryptoProvider::get_default() {
            return Ok(provider.clone());
        }
    }
    // Fallback: ask rustls to install the provider selected by its crate
    // features, then use that same process-level provider for all custom
    // verifiers.
    let _ = rustls::ClientConfig::builder();
    rustls::crypto::CryptoProvider::get_default()
        .cloned()
        .ok_or_else(|| Error::TlsConfig("no default TLS crypto provider".into()))
}

/// Verify a certificate chain while intentionally skipping hostname matching.
///
/// This preserves certificate and signature validation for callers that need
/// to use a trusted certificate whose name is not the request hostname.
#[derive(Debug)]
struct NoHostnameVerifier {
    roots: Arc<rustls::RootCertStore>,
    delegate: Arc<rustls::client::WebPkiServerVerifier>,
    supported_algs: rustls::crypto::WebPkiSupportedAlgorithms,
}

fn no_hostname_verifier(
    roots: &rustls::RootCertStore,
    provider: Arc<rustls::crypto::CryptoProvider>,
) -> Result<Arc<dyn rustls::client::danger::ServerCertVerifier>> {
    let roots = Arc::new(roots.clone());
    let supported_algs = provider.signature_verification_algorithms;
    let delegate =
        rustls::client::WebPkiServerVerifier::builder_with_provider(roots.clone(), provider)
            .build()
            .map_err(|e| Error::TlsConfig(format!("failed to build certificate verifier: {e}")))?;
    Ok(Arc::new(NoHostnameVerifier {
        roots,
        delegate,
        supported_algs,
    }))
}

impl rustls::client::danger::ServerCertVerifier for NoHostnameVerifier {
    fn verify_server_cert(
        &self,
        end_entity: &CertificateDer<'_>,
        intermediates: &[CertificateDer<'_>],
        _server_name: &rustls::pki_types::ServerName<'_>,
        _ocsp_response: &[u8],
        now: rustls::pki_types::UnixTime,
    ) -> std::result::Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
        let cert = rustls::server::ParsedCertificate::try_from(end_entity)?;
        rustls::client::verify_server_cert_signed_by_trust_anchor(
            &cert,
            &self.roots,
            intermediates,
            now,
            self.supported_algs.all,
        )?;
        Ok(rustls::client::danger::ServerCertVerified::assertion())
    }

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

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

    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
        self.delegate.supported_verify_schemes()
    }
}

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

    fn verify_tls12_signature(
        &self,
        _message: &[u8],
        _cert: &CertificateDer<'_>,
        _dss: &rustls::DigitallySignedStruct,
    ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
    }

    fn verify_tls13_signature(
        &self,
        _message: &[u8],
        _cert: &CertificateDer<'_>,
        _dss: &rustls::DigitallySignedStruct,
    ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
    }

    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
        self.supported_schemes.clone()
    }
}

/// A resolver that returns a single certificate and key for mTLS.
struct SingleCertResolver {
    certified_key: Arc<rustls::sign::CertifiedKey>,
    key_label: String,
}

impl std::fmt::Debug for SingleCertResolver {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SingleCertResolver")
            .field("cert_count", &self.certified_key.cert.len())
            .field("key_label", &self.key_label)
            .finish_non_exhaustive()
    }
}

impl SingleCertResolver {
    fn new(identity: ClientIdentity, provider: &rustls::crypto::CryptoProvider) -> Result<Self> {
        match identity {
            ClientIdentity::Pem {
                cert_chain,
                private_key_der,
                key_label,
            } => {
                let key_der = private_key_der_from_parts(&private_key_der, &key_label);
                let certified_key = rustls::sign::CertifiedKey::from_der(
                    cert_chain, key_der, provider,
                )
                .map_err(|e| Error::PrivateKey(format!("failed to load private key: {e}")))?;
                Ok(Self {
                    certified_key: Arc::new(certified_key),
                    key_label,
                })
            }
        }
    }
}

impl rustls::client::ResolvesClientCert for SingleCertResolver {
    fn resolve(
        &self,
        _root_hint_subjects: &[&[u8]],
        _sigschemes: &[rustls::SignatureScheme],
    ) -> Option<Arc<rustls::sign::CertifiedKey>> {
        self.has_certs().then(|| self.certified_key.clone())
    }

    fn has_certs(&self) -> bool {
        !self.certified_key.cert.is_empty()
    }
}

fn private_key_der_from_parts(bytes: &[u8], label: &str) -> PrivateKeyDer<'static> {
    match label {
        "RSA PRIVATE KEY" => PrivateKeyDer::Pkcs1(rustls::pki_types::PrivatePkcs1KeyDer::from(
            bytes.to_owned(),
        )),
        "EC PRIVATE KEY" => {
            PrivateKeyDer::Sec1(rustls::pki_types::PrivateSec1KeyDer::from(bytes.to_owned()))
        }
        _ => PrivateKeyDer::Pkcs8(rustls::pki_types::PrivatePkcs8KeyDer::from(
            bytes.to_owned(),
        )),
    }
}

fn append_unique_certs(
    destination: &mut Vec<CertificateDer<'static>>,
    certificates: impl IntoIterator<Item = CertificateDer<'static>>,
) {
    for certificate in certificates {
        if !destination
            .iter()
            .any(|existing| existing.as_ref() == certificate.as_ref())
        {
            destination.push(certificate);
        }
    }
}

// PEM parsing utilities.

/// Byte sequence opening a PEM section (`-----BEGIN `).
const PEM_BEGIN: &[u8] = b"-----BEGIN ";
/// Byte sequence closing a PEM section (`-----END `).
const PEM_END: &[u8] = b"-----END ";

/// Load PEM-encoded certificates from a file.
fn load_pem_certs_from_path(path: &Path) -> Result<Vec<CertificateDer<'static>>> {
    if path.is_dir() {
        let mut entries = std::fs::read_dir(path)
            .map_err(|e| Error::CaBundle(format!("failed to read {}: {e}", path.display())))?
            .filter_map(std::result::Result::ok)
            .collect::<Vec<_>>();
        entries.sort_by_key(std::fs::DirEntry::file_name);

        let mut certs = Vec::new();
        for entry in entries {
            if !entry.metadata().is_ok_and(|metadata| metadata.is_file()) {
                continue;
            }
            if let Ok(data) = std::fs::read(entry.path()) {
                certs.extend(parse_pem_certificates(&data)?);
            }
        }
        return Ok(certs);
    }

    let data = std::fs::read(path)
        .map_err(|e| Error::CaBundle(format!("failed to read {}: {e}", path.display())))?;
    parse_pem_certificates(&data)
}

/// Parse PEM-encoded certificate data into DER certificates.
///
/// Iterates over every `-----BEGIN`/`-----END` section in the input.
/// Non-PEM content between sections is skipped. Malformed or unterminated
/// PEM sections return an error instead of silently producing a partial trust
/// store. Sections other than `CERTIFICATE` (keys, etc.) are ignored.
fn parse_pem_certificates(pem_bytes: &[u8]) -> Result<Vec<CertificateDer<'static>>> {
    let mut certs = Vec::new();
    let mut rest = pem_bytes;

    while let Some(pos) = find_pem_start(rest) {
        // Feed `decode_vec` exactly one section: it rejects input with
        // trailing content after the END marker, so handing it the whole
        // remaining bundle would fail on multi-certificate files.
        let section = &rest[pos..];
        let section_len = pem_section_len(section)
            .ok_or_else(|| Error::CaBundle("unterminated PEM block in certificate data".into()))?;
        let (label, data) = pem_rfc7468::decode_vec(&section[..section_len])
            .map_err(|e| Error::CaBundle(format!("invalid PEM block in certificate data: {e}")))?;
        if label == "CERTIFICATE" {
            certs.push(CertificateDer::from(data));
        } else {
            // CA bundles should contain only certificates; a key block here
            // likely means the user passed a private-key file as a CA path,
            // which would otherwise yield a confusing "no certificates found"
            // error. Emit a diagnostic to aid troubleshooting.
            #[cfg(feature = "tracing")]
            tracing::warn!("eggfetch: ignoring non-certificate PEM block `{label}` in CA bundle");
            #[cfg(not(feature = "tracing"))]
            let _ = &label;
        }
        rest = &section[section_len..];
    }

    Ok(certs)
}

/// Find the offset of the next `-----BEGIN ` marker in the input.
fn find_pem_start(data: &[u8]) -> Option<usize> {
    if data.len() < PEM_BEGIN.len() {
        return None;
    }
    data.windows(PEM_BEGIN.len()).position(|w| w == PEM_BEGIN)
}

/// Length of the PEM section starting at the beginning of `data` (which
/// must start with a BEGIN marker): from that marker through the end of
/// the first following END-marker line.
///
/// Returns `None` when no END marker exists (truncated block). The base64
/// body cannot contain the `-----END ` byte sequence, so the first match
/// after BEGIN closes the section.
fn pem_section_len(data: &[u8]) -> Option<usize> {
    let after_begin = &data[PEM_BEGIN.len()..];
    let end_marker = after_begin
        .windows(PEM_END.len())
        .position(|w| w == PEM_END)?
        + PEM_BEGIN.len();
    let line_end = data[end_marker..]
        .iter()
        .position(|&b| b == b'\n')
        .map_or(data.len(), |p| end_marker + p + 1);
    Some(line_end)
}

/// Parse a PEM-encoded private key, returning raw DER bytes and the PEM label.
///
/// Like [`parse_pem_certificates`], skips non-PEM sections between valid
/// blocks but rejects malformed or unterminated PEM sections.
fn parse_private_key(key_bytes: &[u8]) -> Result<(Vec<u8>, String)> {
    let mut rest = key_bytes;

    while let Some(pos) = find_pem_start(rest) {
        let section = &rest[pos..];
        let section_len = pem_section_len(section).ok_or_else(|| {
            Error::PrivateKey("unterminated PEM block in private key data".into())
        })?;
        let (label, data) = pem_rfc7468::decode_vec(&section[..section_len]).map_err(|e| {
            Error::PrivateKey(format!("invalid PEM block in private key data: {e}"))
        })?;
        if matches!(label, "PRIVATE KEY" | "RSA PRIVATE KEY" | "EC PRIVATE KEY") {
            return Ok((data, label.to_string()));
        }
        rest = &section[section_len..];
    }

    Err(Error::PrivateKey("no private key found in PEM data".into()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;

    #[test]
    fn default_tls_config() {
        let config = TlsConfig::default();
        assert!(config.verify_hostname());
        assert!(config.verify_certificate());
        assert!(config.sni_enabled());
    }

    #[test]
    fn explicit_provider_is_local_and_retained_by_tls_config() {
        let provider = Arc::new(rustls::crypto::ring::default_provider());
        let before = rustls::crypto::CryptoProvider::get_default().cloned();
        let config = TlsConfig::builder()
            .crypto_provider(provider.clone())
            .trust_store(TrustStore::WebPkiOnly)
            .build();
        assert!(config.has_explicit_crypto_provider());
        assert!(config.build_rustls_config().is_ok());
        let provider_ptr =
            |value: Option<&Arc<rustls::crypto::CryptoProvider>>| value.map(Arc::as_ptr);
        assert_eq!(
            provider_ptr(rustls::crypto::CryptoProvider::get_default()),
            provider_ptr(before.as_ref()),
            "explicit provider configuration must not mutate the global provider"
        );
    }

    #[test]
    fn additional_ca_roots_augment_without_changing_replacement_semantics() {
        let mut params = rcgen::CertificateParams::default();
        params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
        let key = rcgen::KeyPair::generate().unwrap();
        let cert = params.self_signed(&key).unwrap();
        let der = cert.der().to_vec();
        let config = TlsConfig::builder()
            .trust_store(TrustStore::WebPkiOnly)
            .additional_ca_certificate_der(vec![der.clone(), der])
            .unwrap()
            .build();
        let debug = format!("{config:?}");
        assert!(debug.contains("additional_ca_count: 1"));
        assert!(config.build_rustls_config().is_ok());

        let replacement = TlsConfig::builder()
            .ca_certificate_der(vec![cert.der().to_vec()])
            .unwrap()
            .build();
        assert!(replacement.build_rustls_config().is_ok());
    }

    #[test]
    fn malformed_additional_ca_fails_closed() {
        let result = TlsConfig::builder().additional_ca_certificate_pem(b"not a certificate");
        assert!(result.is_err());
        assert_eq!(
            result.err().expect("error checked above").kind(),
            "ca_bundle"
        );
    }

    #[test]
    fn builder_defaults() {
        let config = TlsConfig::builder().build();
        assert!(config.verify_hostname());
        assert!(config.verify_certificate());
        assert!(config.sni_enabled());
    }

    #[test]
    fn builder_disable_verification() {
        let config = TlsConfig::builder()
            .danger_accept_invalid_certs(true)
            .build();
        assert!(!config.verify_hostname());
        assert!(!config.verify_certificate());
    }

    #[test]
    fn config_disable_verification_preserves_other_settings() {
        let config = TlsConfig::builder()
            .sni(false)
            .min_tls_version(TlsVersion::Tls13)
            .build()
            .danger_accept_invalid_certs(true);
        assert!(!config.verify_hostname());
        assert!(!config.verify_certificate());
        assert!(!config.sni_enabled());
        assert_eq!(config.min_version, Some(TlsVersion::Tls13));
    }

    #[test]
    fn builder_custom_tls_version() {
        let config = TlsConfig::builder()
            .min_tls_version(TlsVersion::Tls13)
            .build();
        assert_eq!(config.min_version, Some(TlsVersion::Tls13));
    }

    #[test]
    fn builder_invalid_version_range() {
        let config = TlsConfig::builder()
            .min_tls_version(TlsVersion::Tls13)
            .max_tls_version(TlsVersion::Tls12)
            .build();
        let err = config.build_rustls_config().unwrap_err();
        assert_eq!(err.kind(), "tls_config");
    }

    #[test]
    fn builder_sni_disabled() {
        let config = TlsConfig::builder().sni(false).build();
        assert!(!config.sni_enabled());
    }

    #[test]
    fn trust_store_default() {
        let config = TlsConfig::builder().build();
        assert!(matches!(
            config.trust_store,
            TrustStore::NativeWithWebPkiFallback
        ));
    }

    #[test]
    fn trust_store_custom_empty_rejected() {
        let result = TlsConfig::builder()
            .ca_certificate_pem(b"")
            .map(super::TlsConfigBuilder::build);
        assert!(result.is_err());
    }

    #[test]
    fn add_ca_certificate_path_combines_files_and_directories() {
        let make_ca_pem = || {
            let mut params = rcgen::CertificateParams::default();
            params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
            let key = rcgen::KeyPair::generate().unwrap();
            params.self_signed(&key).unwrap().pem()
        };
        let first = make_ca_pem();
        let second = make_ca_pem();
        let tempdir = tempfile::tempdir().unwrap();
        let first_path = tempdir.path().join("first.pem");
        let cert_dir = tempdir.path().join("certs");
        std::fs::create_dir(&cert_dir).unwrap();
        std::fs::write(&first_path, first).unwrap();
        std::fs::write(cert_dir.join("second.pem"), second).unwrap();

        let config = TlsConfig::builder()
            .ca_certificate_path(first_path)
            .unwrap()
            .add_ca_certificate_path(cert_dir)
            .unwrap()
            .build();
        assert_eq!(config.custom_ca_roots.len(), 2);

        let empty_dir = tempdir.path().join("empty");
        std::fs::create_dir(&empty_dir).unwrap();
        let config = TlsConfig::builder()
            .ca_certificate_path(tempdir.path().join("first.pem"))
            .unwrap()
            .add_ca_certificate_path(empty_dir)
            .unwrap()
            .build();
        assert_eq!(config.custom_ca_roots.len(), 1);
    }

    #[test]
    fn tls_version_ordering() {
        assert!(TlsVersion::Tls12 < TlsVersion::Tls13);
    }

    #[test]
    fn build_rustls_config_verification() {
        let config = TlsConfig::builder().build();
        let result = config.build_rustls_config();
        assert!(result.is_ok());
    }

    #[test]
    fn webpki_only_builds_without_native_roots() {
        let config = TlsConfig::builder()
            .trust_store(TrustStore::WebPkiOnly)
            .build();
        assert!(config.build_rustls_config().is_ok());
    }

    #[cfg(not(feature = "tls-native-roots"))]
    #[test]
    fn native_only_reports_disabled_feature() {
        let config = TlsConfig::builder()
            .trust_store(TrustStore::NativeOnly)
            .build();
        let error = config.build_rustls_config().unwrap_err();
        assert!(error.to_string().contains("tls-native-roots"));
    }

    #[test]
    fn build_rustls_config_no_verify() {
        let config = TlsConfig::builder()
            .danger_accept_invalid_certs(true)
            .sni(false)
            .build();
        let rustls_config = config.build_rustls_config().unwrap();
        assert!(!rustls_config.enable_sni);
    }

    #[test]
    fn build_rustls_config_version_range() {
        let config = TlsConfig::builder()
            .min_tls_version(TlsVersion::Tls12)
            .max_tls_version(TlsVersion::Tls13)
            .build();
        let result = config.build_rustls_config();
        assert!(result.is_ok());
    }

    #[test]
    fn parse_empty_pem_certificates() {
        let result = parse_pem_certificates(b"");
        assert_eq!(result.unwrap(), []);
    }

    #[test]
    fn parse_invalid_pem_certificates() {
        let result = parse_pem_certificates(b"not valid pem data");
        assert_eq!(result.unwrap(), []);
    }

    #[test]
    fn parse_pem_certificates_skip_garbage_between_blocks() {
        // A corrupted/comment section between two certificates must not
        // silently discard the rest of the bundle.
        let valid_block = |body: &[u8]| -> Vec<u8> {
            let mut block = b"-----BEGIN CERTIFICATE-----\n".to_vec();
            block.extend_from_slice(body);
            block.extend_from_slice(b"\n-----END CERTIFICATE-----\n");
            block
        };
        // Valid base64 bodies (pem_rfc7468 validates base64 content).
        let first = valid_block(b"AAAA");
        let second = valid_block(b"BBBB");
        let mut pem = first;
        pem.extend_from_slice(b"\nthis is not valid PEM \x01\x02 data\n");
        pem.extend_from_slice(&second);

        let certs = parse_pem_certificates(&pem).unwrap();
        assert_eq!(certs.len(), 2, "both certificates must be recovered");
    }

    #[test]
    fn parse_pem_certificates_multi_block_bundle() {
        // A plain concatenated bundle (the standard CA-bundle shape)
        // must yield every certificate.
        let mut pem = b"-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n".to_vec();
        pem.extend_from_slice(b"-----BEGIN CERTIFICATE-----\nBBBB\n-----END CERTIFICATE-----\n");
        pem.extend_from_slice(b"-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----\n");

        let certs = parse_pem_certificates(&pem).unwrap();
        assert_eq!(certs.len(), 2, "both certificates, key section skipped");
    }

    #[test]
    fn parse_private_key_skips_leading_garbage() {
        let key_block = b"-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----\n";
        let mut pem = b"corrupt \x03 preamble\n".to_vec();
        pem.extend_from_slice(key_block);

        let (der, label) = parse_private_key(&pem).unwrap();
        assert_eq!(label, "PRIVATE KEY");
        // Base64 "AAAA" decodes to three NUL bytes.
        assert_eq!(der, vec![0u8, 0, 0]);
    }

    #[test]
    fn parse_pem_certificates_rejects_corrupted_blocks() {
        let pem = b"-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n\
-----BEGIN CERTIFICATE-----\n%%%\n-----END CERTIFICATE-----\n";
        let err = parse_pem_certificates(pem).unwrap_err();
        assert_eq!(err.kind(), "ca_bundle");
    }

    #[test]
    fn error_variants() {
        let err = Error::TlsConfig("test".into());
        assert_eq!(err.kind(), "tls_config");

        let err = Error::CaBundle("test".into());
        assert_eq!(err.kind(), "ca_bundle");

        let err = Error::ClientCert("test".into());
        assert_eq!(err.kind(), "client_cert");

        let err = Error::PrivateKey("test".into());
        assert_eq!(err.kind(), "private_key");

        let err = Error::CertificateVerification("test".into());
        assert_eq!(err.kind(), "certificate_verification");

        let err = Error::HostnameVerification("test".into());
        assert_eq!(err.kind(), "hostname_verification");
    }

    #[test]
    fn debug_impl_no_secrets() {
        let config = TlsConfig::builder().build();
        let debug = format!("{config:?}");
        assert!(debug.contains("verify_hostname: true"));
        assert!(debug.contains("verify_certificate: true"));
    }

    #[cfg(all(feature = "proxy", feature = "tls-rustls"))]
    #[test]
    fn unchanged_clone_shares_connection_identity() {
        let base = TlsConfig::builder().build();
        let strict = base.clone();
        assert_eq!(
            base.connection_identity(),
            strict.connection_identity(),
            "unchanged clones must remain cache-compatible"
        );
    }

    #[cfg(all(feature = "proxy", feature = "tls-rustls"))]
    #[test]
    fn danger_mutation_mints_new_connection_identity() {
        // Baseline-red regression for the proxy-TLS aliasing defect: a clone
        // modified with `danger_accept_invalid_certs(true)` previously shared
        // the root-store pointer identity with its strict parent.
        let base = TlsConfig::builder().build();
        let strict = base.clone();
        let weak = base.clone().danger_accept_invalid_certs(true);
        assert_ne!(
            strict.connection_identity(),
            weak.connection_identity(),
            "changed verification policy must not alias through clone ancestry"
        );
    }

    #[cfg(all(feature = "proxy", feature = "tls-rustls"))]
    #[test]
    fn independent_builds_never_share_connection_identity() {
        let first = TlsConfig::builder().build();
        let second = TlsConfig::builder().build();
        assert_ne!(
            first.connection_identity(),
            second.connection_identity(),
            "separate builds mint fresh identity even for identical policy"
        );
    }

    #[cfg(all(feature = "proxy", feature = "tls-rustls"))]
    #[test]
    fn connection_identity_covers_policy_dimensions() {
        // Each dimension builds an independent config; all must differ from
        // the base because every build mints a fresh opaque token. The
        // assertions document the connection-affecting surface, not structural
        // equality: false misses are acceptable, false hits are not.
        let base = TlsConfig::builder().build();
        let base_id = base.connection_identity();

        let sni_off = TlsConfig::builder().sni(false).build();
        assert_ne!(base_id, sni_off.connection_identity());

        let min_tls = TlsConfig::builder()
            .min_tls_version(TlsVersion::Tls13)
            .build();
        assert_ne!(base_id, min_tls.connection_identity());

        let max_tls = TlsConfig::builder()
            .max_tls_version(TlsVersion::Tls12)
            .build();
        assert_ne!(base_id, max_tls.connection_identity());

        let webpki = TlsConfig::builder()
            .trust_store(TrustStore::WebPkiOnly)
            .build();
        assert_ne!(base_id, webpki.connection_identity());

        let provider = Arc::new(rustls::crypto::ring::default_provider());
        let explicit_provider = TlsConfig::builder()
            .crypto_provider(provider)
            .trust_store(TrustStore::WebPkiOnly)
            .build();
        assert_ne!(base_id, explicit_provider.connection_identity());

        let custom_ca = TlsConfig::builder()
            .ca_certificate_der(vec![vec![0u8; 32]])
            .unwrap()
            .build();
        assert_ne!(base_id, custom_ca.connection_identity());

        let additional_ca = TlsConfig::builder()
            .trust_store(TrustStore::WebPkiOnly)
            .additional_ca_certificate_der(vec![vec![1u8; 32]])
            .unwrap()
            .build();
        assert_ne!(base_id, additional_ca.connection_identity());

        let identity = ClientIdentity::Pem {
            cert_chain: vec![],
            private_key_der: vec![2u8; 16],
            key_label: "PRIVATE KEY".to_string(),
        };
        let mtls = TlsConfig::builder().client_identity(identity).build();
        assert_ne!(base_id, mtls.connection_identity());
    }

    #[cfg(all(feature = "proxy", feature = "tls-rustls"))]
    #[test]
    fn connection_identity_is_opaque_and_non_renderable() {
        let config = TlsConfig::builder().build();
        let id = config.connection_identity();
        assert_ne!(id, 0, "0 is reserved for no-TLS-config keys");
        let debug = format!("{config:?}");
        assert!(
            !debug.contains(&id.to_string()),
            "opaque token must never appear in diagnostics: {debug}"
        );
    }

    #[test]
    fn client_identity_debug_no_private_key() {
        let identity = ClientIdentity::Pem {
            cert_chain: vec![],
            private_key_der: b"super-secret-private-key-data".to_vec(),
            key_label: "PRIVATE KEY".to_string(),
        };
        let debug = format!("{identity:?}");
        assert!(
            !debug.contains("super-secret"),
            "ClientIdentity Debug must not leak private key bytes: {debug}"
        );
        assert!(debug.contains("cert_count"));
        assert!(debug.contains("key_label"));
    }

    proptest::proptest! {
        #[test]
        fn parse_pem_certificates_empty_input(_ in 0u64..100) {
            let result = parse_pem_certificates(b"");
            prop_assert!(result.unwrap().is_empty());
        }

        #[test]
        fn parse_pem_certificates_garbage(input in ".{0,200}") {
            // Must not panic
            let _ = parse_pem_certificates(input.as_bytes());
        }

        #[test]
        fn tls_config_builder_round_trip(sni in prop::bool::ANY) {
            let config = TlsConfig::builder()
                .sni(sni)
                .build();
            prop_assert_eq!(config.sni_enabled(), sni);
            // Defaults are always true
            prop_assert!(config.verify_hostname());
            prop_assert!(config.verify_certificate());
        }

        #[test]
        fn build_rustls_config_valid_for_defaults(_ in 0u64..100) {
            let config = TlsConfig::default();
            let result = config.build_rustls_config();
            prop_assert!(result.is_ok());
        }
    }
}