Skip to main content

eggfetch_core/
tls.rs

1//! TLS configuration for the eggfetch client.
2//!
3//! Provides [`TlsConfig`] and [`TlsConfigBuilder`] for controlling TLS
4//! behavior: trust stores, custom CA bundles, client certificates,
5//! verification policy, TLS version bounds, and SNI.
6//!
7//! # Defaults
8//!
9//! - Hostname verification is enabled.
10//! - Certificate-chain verification is enabled.
11//! - Native system roots are preferred; packaged `WebPKI` roots are used
12//!   as a construction fallback when native roots are unavailable.
13//! - TLS 1.2 and 1.3 are supported.
14//! - SNI is enabled by default.
15//!
16//! # Custom CA bundles
17//!
18//! A custom CA bundle replaces the default root store (it does not
19//! augment). The bundle is loaded at construction time; malformed or
20//! empty bundles are rejected immediately.
21//!
22//! # Safety
23//!
24//! Disabling certificate verification (`verify = false`) weakens TLS
25//! guarantees. It should only be used for testing or against known
26//! trusted targets. The Python binding documents this in the `verify`
27//! parameter docstring.
28
29use std::path::Path;
30use std::sync::Arc;
31use std::sync::OnceLock;
32
33use rustls::pki_types::{CertificateDer, PrivateKeyDer};
34
35use crate::error::{Error, Result};
36
37/// Trust store source for certificate verification.
38#[derive(Debug, Clone, Default)]
39pub enum TrustStore {
40    /// Use native system roots with packaged `WebPKI` roots as a
41    /// construction fallback (default).
42    #[default]
43    NativeWithWebPkiFallback,
44    /// Use only native system roots. Fails at construction if the
45    /// platform root store is unavailable.
46    NativeOnly,
47    /// Use only packaged Mozilla/WebPKI roots. Does not consult the
48    /// operating system trust store.
49    WebPkiOnly,
50    /// Use the provided CA certificates as the sole trust anchor.
51    /// These replace all other roots.
52    Custom(Vec<CertificateDer<'static>>),
53}
54
55/// A client certificate and private key for mTLS.
56#[derive(Clone)]
57pub enum ClientIdentity {
58    /// A certificate chain and private key in DER format.
59    Pem {
60        /// The certificate chain, in DER bytes.
61        cert_chain: Vec<CertificateDer<'static>>,
62        /// The private key, as raw DER bytes.
63        private_key_der: Vec<u8>,
64        /// The label from the PEM block (e.g., "PRIVATE KEY", "RSA PRIVATE KEY").
65        key_label: String,
66    },
67}
68
69impl std::fmt::Debug for ClientIdentity {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        match self {
72            Self::Pem {
73                cert_chain,
74                key_label,
75                ..
76            } => f
77                .debug_struct("ClientIdentity::Pem")
78                .field("cert_count", &cert_chain.len())
79                .field("key_label", key_label)
80                .finish_non_exhaustive(),
81        }
82    }
83}
84
85/// Minimum or maximum TLS protocol version.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
87pub enum TlsVersion {
88    /// TLS 1.2.
89    Tls12,
90    /// TLS 1.3.
91    Tls13,
92}
93
94impl TlsVersion {
95    fn to_rustls(self) -> &'static rustls::SupportedProtocolVersion {
96        match self {
97            Self::Tls12 => &rustls::version::TLS12,
98            Self::Tls13 => &rustls::version::TLS13,
99        }
100    }
101}
102
103/// Immutable shared TLS configuration for a client.
104///
105/// Construct via [`TlsConfig::builder()`] or [`TlsConfig::builder_with_defaults()`].
106#[derive(Clone)]
107pub struct TlsConfig {
108    trust_store: TrustStore,
109    custom_ca_roots: Vec<CertificateDer<'static>>,
110    client_identity: Option<ClientIdentity>,
111    verify_hostname: bool,
112    verify_certificate: bool,
113    min_version: Option<TlsVersion>,
114    max_version: Option<TlsVersion>,
115    sni_enabled: bool,
116    root_store: Arc<OnceLock<Result<rustls::RootCertStore>>>,
117}
118
119impl std::fmt::Debug for TlsConfig {
120    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121        f.debug_struct("TlsConfig")
122            .field("trust_store", &self.trust_store)
123            .field("has_custom_ca", &!self.custom_ca_roots.is_empty())
124            .field("has_client_identity", &self.client_identity.is_some())
125            .field("verify_hostname", &self.verify_hostname)
126            .field("verify_certificate", &self.verify_certificate)
127            .field("min_version", &self.min_version)
128            .field("max_version", &self.max_version)
129            .field("sni_enabled", &self.sni_enabled)
130            .finish_non_exhaustive()
131    }
132}
133
134impl Default for TlsConfig {
135    fn default() -> Self {
136        Self::builder().build()
137    }
138}
139
140impl TlsConfig {
141    /// Create a builder with secure defaults (verification enabled, native
142    /// roots preferred, SNI enabled).
143    #[must_use]
144    pub fn builder() -> TlsConfigBuilder {
145        TlsConfigBuilder::new()
146    }
147
148    /// Create a builder from the default configuration.
149    ///
150    /// This is identical to [`TlsConfig::builder()`] and exists for
151    /// discoverability.
152    #[must_use]
153    pub fn builder_with_defaults() -> TlsConfigBuilder {
154        Self::builder()
155    }
156
157    /// Enable or disable certificate and hostname verification while
158    /// retaining the rest of this configuration.
159    #[must_use]
160    pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
161        self.verify_certificate = !accept;
162        self.verify_hostname = !accept;
163        self
164    }
165
166    /// Build a `tokio_rustls::TlsConnector` from this TLS configuration.
167    ///
168    /// This is the convenience entry point for
169    /// [`crate::network_stream::UpgradedStream::start_tls`] and other
170    /// contexts where a generic TLS upgrade must reflect the full
171    /// configured policy (custom CA, verification, SNI, version bounds,
172    /// client identity).
173    ///
174    /// # Errors
175    ///
176    /// Returns an error if the underlying rustls configuration cannot be
177    /// built (see [`Self::build_rustls_config`]).
178    pub fn tls_connector(&self) -> Result<tokio_rustls::TlsConnector> {
179        let config = self.build_rustls_config()?;
180        Ok(tokio_rustls::TlsConnector::from(Arc::new(config)))
181    }
182
183    /// Build a `rustls::ClientConfig` from this TLS configuration.
184    ///
185    /// # Errors
186    ///
187    /// Returns an error if the trust store, client certificates, or
188    /// protocol versions cannot be configured.
189    pub fn build_rustls_config(&self) -> Result<rustls::ClientConfig> {
190        let root_store = self.build_root_store()?;
191
192        let mut protocol_versions = Vec::new();
193        match (self.min_version, self.max_version) {
194            (Some(min), Some(max)) => {
195                if min > max {
196                    return Err(Error::TlsConfig(format!(
197                        "invalid TLS version range: min ({min:?}) > max ({max:?})"
198                    )));
199                }
200                for v in Self::supported_versions() {
201                    if v >= min && v <= max {
202                        protocol_versions.push(v.to_rustls());
203                    }
204                }
205            }
206            (Some(min), None) => {
207                for v in Self::supported_versions() {
208                    if v >= min {
209                        protocol_versions.push(v.to_rustls());
210                    }
211                }
212            }
213            (None, Some(max)) => {
214                for v in Self::supported_versions() {
215                    if v <= max {
216                        protocol_versions.push(v.to_rustls());
217                    }
218                }
219            }
220            (None, None) => {
221                for v in Self::supported_versions() {
222                    protocol_versions.push(v.to_rustls());
223                }
224            }
225        }
226
227        if protocol_versions.is_empty() {
228            return Err(Error::TlsConfig(
229                "no supported TLS versions in configured range".into(),
230            ));
231        }
232
233        let provider = process_crypto_provider()?;
234        let supported_schemes = provider
235            .signature_verification_algorithms
236            .supported_schemes();
237        let mut config = if self.verify_certificate && self.verify_hostname {
238            rustls::ClientConfig::builder_with_provider(provider.clone())
239                .with_protocol_versions(&protocol_versions)
240                .map_err(|e| Error::TlsConfig(format!("TLS version config: {e}")))?
241                .with_root_certificates(root_store)
242                .with_no_client_auth()
243        } else if self.verify_certificate {
244            rustls::ClientConfig::builder_with_provider(provider.clone())
245                .with_protocol_versions(&protocol_versions)
246                .map_err(|e| Error::TlsConfig(format!("TLS version config: {e}")))?
247                .dangerous()
248                .with_custom_certificate_verifier(no_hostname_verifier(&root_store, provider)?)
249                .with_no_client_auth()
250        } else {
251            rustls::ClientConfig::builder_with_provider(provider)
252                .with_protocol_versions(&protocol_versions)
253                .map_err(|e| Error::TlsConfig(format!("TLS version config: {e}")))?
254                .dangerous()
255                .with_custom_certificate_verifier(Arc::new(NoVerifier { supported_schemes }))
256                .with_no_client_auth()
257        };
258
259        // Default ALPN advertises both protocols when HTTP/2 is compiled in.
260        // Callers enforcing `HttpVersionPolicy` must override via
261        // `crate::client::configure_tls_alpn` (used by all client paths).
262        // Direct use of `build_rustls_config` without override intentionally
263        // retains this default; an empty default would silently downgrade
264        // `tls_connector`/`start_tls` users to HTTP/1.1.
265        #[cfg(feature = "http2")]
266        {
267            config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
268        }
269        #[cfg(not(feature = "http2"))]
270        {
271            config.alpn_protocols = vec![b"http/1.1".to_vec()];
272        }
273        config.enable_sni = self.sni_enabled;
274
275        if let Some(identity) = &self.client_identity {
276            config.client_auth_cert_resolver = Arc::new(SingleCertResolver::new(identity.clone()));
277        }
278
279        Ok(config)
280    }
281
282    /// Build the root certificate store from the configured trust policy.
283    fn build_root_store(&self) -> Result<rustls::RootCertStore> {
284        self.root_store
285            .get_or_init(|| self.build_root_store_uncached())
286            .clone()
287    }
288
289    fn build_root_store_uncached(&self) -> Result<rustls::RootCertStore> {
290        match &self.trust_store {
291            TrustStore::NativeWithWebPkiFallback => match Self::try_native_roots() {
292                Ok(store) if !store.is_empty() => Ok(store),
293                _ => Ok(Self::webpki_roots()),
294            },
295            TrustStore::NativeOnly => Self::try_native_roots(),
296            TrustStore::WebPkiOnly => Ok(Self::webpki_roots()),
297            TrustStore::Custom(certs) => {
298                if certs.is_empty() {
299                    return Err(Error::CaBundle("custom CA bundle is empty".into()));
300                }
301                let mut store = rustls::RootCertStore::empty();
302                for cert in certs {
303                    store
304                        .add(cert.clone())
305                        .map_err(|e| Error::CaBundle(format!("invalid CA certificate: {e}")))?;
306                }
307                Ok(store)
308            }
309        }
310    }
311
312    fn try_native_roots() -> Result<rustls::RootCertStore> {
313        let mut roots = rustls::RootCertStore::empty();
314
315        #[cfg(any(target_os = "linux", target_os = "macos"))]
316        {
317            #[cfg(target_os = "linux")]
318            let pem_paths: &[&str] = &[
319                "/etc/ssl/certs/ca-certificates.crt",
320                "/etc/pki/tls/certs/ca-bundle.crt",
321                "/etc/ssl/ca-bundle.pem",
322            ];
323
324            #[cfg(target_os = "macos")]
325            let pem_paths: &[&str] = &["/etc/ssl/cert.pem", "/usr/local/etc/openssl/cert.pem"];
326
327            for path in pem_paths {
328                if let Ok(certs) = load_pem_certs_from_path(Path::new(path)) {
329                    for cert in certs {
330                        if let Err(e) = roots.add(cert) {
331                            #[cfg(feature = "tracing")]
332                            tracing::warn!(
333                                "eggfetch: skipped invalid CA certificate in {path}: {e}"
334                            );
335                            #[cfg(not(feature = "tracing"))]
336                            let _ = (path, &e);
337                        }
338                    }
339                }
340            }
341        }
342
343        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
344        {
345            for cert in rustls_native_certs::load_native_certs().certs {
346                if let Err(e) = roots.add(cert) {
347                    #[cfg(feature = "tracing")]
348                    tracing::warn!("eggfetch: skipped invalid native CA certificate: {e}");
349                    #[cfg(not(feature = "tracing"))]
350                    let _ = &e;
351                }
352            }
353        }
354
355        if roots.is_empty() {
356            return Err(Error::TlsConfig(
357                "native root certificates not available".into(),
358            ));
359        }
360        Ok(roots)
361    }
362
363    fn webpki_roots() -> rustls::RootCertStore {
364        let mut roots = rustls::RootCertStore::empty();
365        roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
366        roots
367    }
368
369    /// Root store for proxy-leg / CONNECT-tunnel fallbacks: native system
370    /// roots when available, otherwise packaged `WebPKI` roots.
371    ///
372    /// Shares the `NativeWithWebPkiFallback` policy so corporate/private PKI
373    /// roots installed in the OS store work through `https://` proxy
374    /// endpoints and HTTPS-via-CONNECT tunnels, not just on the direct path.
375    #[cfg(feature = "proxy")]
376    pub(crate) fn fallback_root_store() -> rustls::RootCertStore {
377        match Self::try_native_roots() {
378            Ok(store) if !store.is_empty() => store,
379            _ => Self::webpki_roots(),
380        }
381    }
382
383    fn supported_versions() -> impl Iterator<Item = TlsVersion> {
384        [TlsVersion::Tls12, TlsVersion::Tls13].into_iter()
385    }
386
387    /// Returns `true` if hostname verification is enabled.
388    #[must_use]
389    pub fn verify_hostname(&self) -> bool {
390        self.verify_hostname
391    }
392
393    /// Returns `true` if certificate verification is enabled.
394    #[must_use]
395    pub fn verify_certificate(&self) -> bool {
396        self.verify_certificate
397    }
398
399    /// Returns `true` if SNI is enabled.
400    #[must_use]
401    pub fn sni_enabled(&self) -> bool {
402        self.sni_enabled
403    }
404
405    /// Build a `rustls::ClientConfig` for QUIC (TLS 1.3 only, ALPN `h3`).
406    ///
407    /// This differs from [`build_rustls_config`](Self::build_rustls_config)
408    /// by restricting to TLS 1.3 and using the `h3` ALPN.
409    ///
410    /// # Errors
411    ///
412    /// Returns an error if the trust store, client certificates, or
413    /// protocol versions cannot be configured.
414    #[allow(dead_code)]
415    pub(crate) fn build_quic_rustls_config(&self) -> Result<rustls::ClientConfig> {
416        let root_store = self.build_root_store()?;
417
418        let provider = process_crypto_provider()?;
419        let supported_schemes = provider
420            .signature_verification_algorithms
421            .supported_schemes();
422        let mut config = if self.verify_certificate && self.verify_hostname {
423            rustls::ClientConfig::builder_with_provider(provider.clone())
424                .with_protocol_versions(&[&rustls::version::TLS13])
425                .map_err(|e| Error::Tls(format!("TLS version config: {e}")))?
426                .with_root_certificates(root_store)
427                .with_no_client_auth()
428        } else if self.verify_certificate {
429            rustls::ClientConfig::builder_with_provider(provider.clone())
430                .with_protocol_versions(&[&rustls::version::TLS13])
431                .map_err(|e| Error::Tls(format!("TLS version config: {e}")))?
432                .dangerous()
433                .with_custom_certificate_verifier(no_hostname_verifier(&root_store, provider)?)
434                .with_no_client_auth()
435        } else {
436            rustls::ClientConfig::builder_with_provider(provider)
437                .with_protocol_versions(&[&rustls::version::TLS13])
438                .map_err(|e| Error::Tls(format!("TLS version config: {e}")))?
439                .dangerous()
440                .with_custom_certificate_verifier(Arc::new(NoVerifier { supported_schemes }))
441                .with_no_client_auth()
442        };
443
444        config.alpn_protocols = vec![b"h3".to_vec()];
445        config.enable_sni = self.sni_enabled;
446
447        if let Some(identity) = &self.client_identity {
448            config.client_auth_cert_resolver = Arc::new(SingleCertResolver::new(identity.clone()));
449        }
450
451        Ok(config)
452    }
453}
454
455/// Builder for constructing a [`TlsConfig`].
456pub struct TlsConfigBuilder {
457    trust_store: TrustStore,
458    custom_ca_roots: Vec<CertificateDer<'static>>,
459    client_identity: Option<ClientIdentity>,
460    verify_hostname: bool,
461    verify_certificate: bool,
462    min_version: Option<TlsVersion>,
463    max_version: Option<TlsVersion>,
464    sni_enabled: bool,
465}
466
467impl Default for TlsConfigBuilder {
468    fn default() -> Self {
469        Self::new()
470    }
471}
472
473impl TlsConfigBuilder {
474    /// Create a new builder with secure defaults.
475    #[must_use]
476    pub fn new() -> Self {
477        Self {
478            trust_store: TrustStore::NativeWithWebPkiFallback,
479            custom_ca_roots: Vec::new(),
480            client_identity: None,
481            verify_hostname: true,
482            verify_certificate: true,
483            min_version: None,
484            max_version: None,
485            sni_enabled: true,
486        }
487    }
488
489    /// Set the trust store source.
490    #[must_use]
491    pub fn trust_store(mut self, store: TrustStore) -> Self {
492        self.trust_store = store;
493        self
494    }
495
496    /// Load CA certificates from a PEM file, replacing any existing trust
497    /// store configuration.
498    ///
499    /// # Errors
500    ///
501    /// Returns an error if the file cannot be read or the PEM data is
502    /// malformed.
503    pub fn ca_certificate_path(mut self, path: impl AsRef<Path>) -> Result<Self> {
504        let certs = load_pem_certs_from_path(path.as_ref())?;
505        if certs.is_empty() {
506            if path.as_ref().is_dir() {
507                return Ok(self);
508            }
509            return Err(Error::CaBundle(format!(
510                "no certificates found in {}",
511                path.as_ref().display()
512            )));
513        }
514        self.custom_ca_roots = certs;
515        self.trust_store = TrustStore::Custom(self.custom_ca_roots.clone());
516        Ok(self)
517    }
518
519    /// Add CA certificates from a PEM file or certificate directory to the
520    /// configured custom trust store, replacing the default trust store if
521    /// this is the first custom source.
522    ///
523    /// Duplicate certificates are ignored. This is useful when multiple
524    /// environment-provided CA sources are combined.
525    ///
526    /// # Errors
527    ///
528    /// Returns an error if the path cannot be read or contains no PEM
529    /// certificates. Empty directories are ignored.
530    pub fn add_ca_certificate_path(mut self, path: impl AsRef<Path>) -> Result<Self> {
531        let certs = load_pem_certs_from_path(path.as_ref())?;
532        if certs.is_empty() {
533            if path.as_ref().is_dir() {
534                return Ok(self);
535            }
536            return Err(Error::CaBundle(format!(
537                "no certificates found in {}",
538                path.as_ref().display()
539            )));
540        }
541        if !matches!(&self.trust_store, TrustStore::Custom(_)) {
542            self.custom_ca_roots.clear();
543        }
544        for cert in certs {
545            if !self
546                .custom_ca_roots
547                .iter()
548                .any(|existing| existing.as_ref() == cert.as_ref())
549            {
550                self.custom_ca_roots.push(cert);
551            }
552        }
553        self.trust_store = TrustStore::Custom(self.custom_ca_roots.clone());
554        Ok(self)
555    }
556
557    /// Load CA certificates from PEM bytes, replacing any existing trust
558    /// store configuration.
559    ///
560    /// # Errors
561    ///
562    /// Returns an error if the PEM data is malformed or empty.
563    pub fn ca_certificate_pem(mut self, pem_bytes: &[u8]) -> Result<Self> {
564        let certs = parse_pem_certificates(pem_bytes)?;
565        if certs.is_empty() {
566            return Err(Error::CaBundle("no certificates found in PEM data".into()));
567        }
568        self.custom_ca_roots = certs;
569        self.trust_store = TrustStore::Custom(self.custom_ca_roots.clone());
570        Ok(self)
571    }
572
573    /// Load CA certificates from DER bytes, replacing any existing trust
574    /// store configuration.
575    ///
576    /// Each certificate is expected as raw DER-encoded X.509 data
577    /// (without PEM framing).
578    ///
579    /// # Errors
580    ///
581    /// Returns an error if no certificates are provided.
582    pub fn ca_certificate_der(mut self, der_certs: Vec<Vec<u8>>) -> Result<Self> {
583        let certs: Vec<CertificateDer<'static>> =
584            der_certs.into_iter().map(CertificateDer::from).collect();
585        if certs.is_empty() {
586            return Err(Error::CaBundle("no DER certificates provided".into()));
587        }
588        self.custom_ca_roots = certs;
589        self.trust_store = TrustStore::Custom(self.custom_ca_roots.clone());
590        Ok(self)
591    }
592
593    /// Set the client identity for mTLS.
594    #[must_use]
595    pub fn client_identity(mut self, identity: ClientIdentity) -> Self {
596        self.client_identity = Some(identity);
597        self
598    }
599
600    /// Load a client certificate and private key from PEM files.
601    ///
602    /// # Errors
603    ///
604    /// Returns an error if the files cannot be read or the PEM data is
605    /// malformed.
606    pub fn client_cert_path(
607        self,
608        cert_path: impl AsRef<Path>,
609        key_path: impl AsRef<Path>,
610    ) -> Result<Self> {
611        let certs = load_pem_certs_from_path(cert_path.as_ref())?;
612        if certs.is_empty() {
613            return Err(Error::ClientCert(format!(
614                "no certificates found in {}",
615                cert_path.as_ref().display()
616            )));
617        }
618
619        let key_bytes = std::fs::read(key_path.as_ref()).map_err(|e| {
620            Error::PrivateKey(format!(
621                "failed to read private key {}: {e}",
622                key_path.as_ref().display()
623            ))
624        })?;
625        let (key_data, key_label) = parse_private_key(&key_bytes)?;
626
627        Ok(self.client_identity(ClientIdentity::Pem {
628            cert_chain: certs,
629            private_key_der: key_data,
630            key_label,
631        }))
632    }
633
634    /// Enable or disable hostname verification.
635    ///
636    /// When disabled, the client does not verify that the server's
637    /// certificate matches the requested hostname. This is insecure
638    /// and should only be used for testing.
639    #[must_use]
640    pub fn verify_hostname(mut self, enabled: bool) -> Self {
641        self.verify_hostname = enabled;
642        self
643    }
644
645    /// Enable or disable certificate verification.
646    ///
647    /// When disabled (`danger_accept_invalid_certs(true)`), the client
648    /// does not verify the server's certificate chain or hostname.
649    /// This is **insecure** and should only be used for testing against
650    /// known self-signed certificates.
651    #[must_use]
652    pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
653        self.verify_certificate = !accept;
654        self.verify_hostname = !accept;
655        self
656    }
657
658    /// Set the minimum TLS version.
659    #[must_use]
660    pub fn min_tls_version(mut self, version: TlsVersion) -> Self {
661        self.min_version = Some(version);
662        self
663    }
664
665    /// Set the maximum TLS version.
666    #[must_use]
667    pub fn max_tls_version(mut self, version: TlsVersion) -> Self {
668        self.max_version = Some(version);
669        self
670    }
671
672    /// Enable or disable SNI (Server Name Indication).
673    ///
674    /// Disabling SNI can break hostname verification and virtual-host
675    /// routing. It should rarely be necessary.
676    #[must_use]
677    pub fn sni(mut self, enabled: bool) -> Self {
678        self.sni_enabled = enabled;
679        self
680    }
681
682    /// Build the [`TlsConfig`].
683    #[must_use]
684    pub fn build(self) -> TlsConfig {
685        TlsConfig {
686            trust_store: self.trust_store,
687            custom_ca_roots: self.custom_ca_roots,
688            client_identity: self.client_identity,
689            verify_hostname: self.verify_hostname,
690            verify_certificate: self.verify_certificate,
691            min_version: self.min_version,
692            max_version: self.max_version,
693            sni_enabled: self.sni_enabled,
694            root_store: Arc::new(OnceLock::new()),
695        }
696    }
697}
698
699/// A certificate verifier that accepts all certificates (unsafe).
700#[derive(Debug)]
701struct NoVerifier {
702    supported_schemes: Vec<rustls::SignatureScheme>,
703}
704
705pub(crate) fn process_crypto_provider() -> Result<Arc<rustls::crypto::CryptoProvider>> {
706    if let Some(provider) = rustls::crypto::CryptoProvider::get_default() {
707        return Ok(provider.clone());
708    }
709
710    // Explicitly install the provider implied by the selected crate features.
711    // Relying on `ClientConfig::builder()` to install the provider as a side
712    // effect is fragile: a future rustls change or a pre-installed custom
713    // provider could leave `get_default()` as `None` or mismatched.
714    #[cfg(feature = "tls-rustls")]
715    {
716        // `CryptoProvider::get_default` was None above, so no provider is
717        // installed yet. Try to install the feature-selected provider
718        // explicitly before falling back to the builder side-effect.
719        let provider = rustls::crypto::ring::default_provider();
720        let _ = provider.install_default();
721        if let Some(provider) = rustls::crypto::CryptoProvider::get_default() {
722            return Ok(provider.clone());
723        }
724    }
725    // Fallback: ask rustls to install the provider selected by its crate
726    // features, then use that same process-level provider for all custom
727    // verifiers.
728    let _ = rustls::ClientConfig::builder();
729    rustls::crypto::CryptoProvider::get_default()
730        .cloned()
731        .ok_or_else(|| Error::TlsConfig("no default TLS crypto provider".into()))
732}
733
734/// Verify a certificate chain while intentionally skipping hostname matching.
735///
736/// This preserves certificate and signature validation for callers that need
737/// to use a trusted certificate whose name is not the request hostname.
738#[derive(Debug)]
739struct NoHostnameVerifier {
740    roots: Arc<rustls::RootCertStore>,
741    delegate: Arc<rustls::client::WebPkiServerVerifier>,
742    supported_algs: rustls::crypto::WebPkiSupportedAlgorithms,
743}
744
745fn no_hostname_verifier(
746    roots: &rustls::RootCertStore,
747    provider: Arc<rustls::crypto::CryptoProvider>,
748) -> Result<Arc<dyn rustls::client::danger::ServerCertVerifier>> {
749    let roots = Arc::new(roots.clone());
750    let supported_algs = provider.signature_verification_algorithms;
751    let delegate =
752        rustls::client::WebPkiServerVerifier::builder_with_provider(roots.clone(), provider)
753            .build()
754            .map_err(|e| Error::TlsConfig(format!("failed to build certificate verifier: {e}")))?;
755    Ok(Arc::new(NoHostnameVerifier {
756        roots,
757        delegate,
758        supported_algs,
759    }))
760}
761
762impl rustls::client::danger::ServerCertVerifier for NoHostnameVerifier {
763    fn verify_server_cert(
764        &self,
765        end_entity: &CertificateDer<'_>,
766        intermediates: &[CertificateDer<'_>],
767        _server_name: &rustls::pki_types::ServerName<'_>,
768        _ocsp_response: &[u8],
769        now: rustls::pki_types::UnixTime,
770    ) -> std::result::Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
771        let cert = rustls::server::ParsedCertificate::try_from(end_entity)?;
772        rustls::client::verify_server_cert_signed_by_trust_anchor(
773            &cert,
774            &self.roots,
775            intermediates,
776            now,
777            self.supported_algs.all,
778        )?;
779        Ok(rustls::client::danger::ServerCertVerified::assertion())
780    }
781
782    fn verify_tls12_signature(
783        &self,
784        message: &[u8],
785        cert: &CertificateDer<'_>,
786        dss: &rustls::DigitallySignedStruct,
787    ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
788        self.delegate.verify_tls12_signature(message, cert, dss)
789    }
790
791    fn verify_tls13_signature(
792        &self,
793        message: &[u8],
794        cert: &CertificateDer<'_>,
795        dss: &rustls::DigitallySignedStruct,
796    ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
797        self.delegate.verify_tls13_signature(message, cert, dss)
798    }
799
800    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
801        self.delegate.supported_verify_schemes()
802    }
803}
804
805impl rustls::client::danger::ServerCertVerifier for NoVerifier {
806    fn verify_server_cert(
807        &self,
808        _end_entity: &CertificateDer<'_>,
809        _intermediates: &[CertificateDer<'_>],
810        _server_name: &rustls::pki_types::ServerName<'_>,
811        _ocsp_response: &[u8],
812        _now: rustls::pki_types::UnixTime,
813    ) -> std::result::Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
814        Ok(rustls::client::danger::ServerCertVerified::assertion())
815    }
816
817    fn verify_tls12_signature(
818        &self,
819        _message: &[u8],
820        _cert: &CertificateDer<'_>,
821        _dss: &rustls::DigitallySignedStruct,
822    ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
823        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
824    }
825
826    fn verify_tls13_signature(
827        &self,
828        _message: &[u8],
829        _cert: &CertificateDer<'_>,
830        _dss: &rustls::DigitallySignedStruct,
831    ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
832        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
833    }
834
835    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
836        self.supported_schemes.clone()
837    }
838}
839
840/// A resolver that returns a single certificate and key for mTLS.
841struct SingleCertResolver {
842    cert_chain: Vec<CertificateDer<'static>>,
843    private_key_der: Vec<u8>,
844    key_label: String,
845}
846
847impl std::fmt::Debug for SingleCertResolver {
848    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
849        f.debug_struct("SingleCertResolver")
850            .field("cert_count", &self.cert_chain.len())
851            .field("key_label", &self.key_label)
852            .finish_non_exhaustive()
853    }
854}
855
856impl SingleCertResolver {
857    fn new(identity: ClientIdentity) -> Self {
858        match identity {
859            ClientIdentity::Pem {
860                cert_chain,
861                private_key_der,
862                key_label,
863            } => Self {
864                cert_chain,
865                private_key_der,
866                key_label,
867            },
868        }
869    }
870}
871
872impl rustls::client::ResolvesClientCert for SingleCertResolver {
873    fn resolve(
874        &self,
875        _root_hint_subjects: &[&[u8]],
876        _sigschemes: &[rustls::SignatureScheme],
877    ) -> Option<Arc<rustls::sign::CertifiedKey>> {
878        let key_der = match self.key_label.as_str() {
879            "RSA PRIVATE KEY" => PrivateKeyDer::Pkcs1(rustls::pki_types::PrivatePkcs1KeyDer::from(
880                self.private_key_der.clone(),
881            )),
882            "EC PRIVATE KEY" => PrivateKeyDer::Sec1(rustls::pki_types::PrivateSec1KeyDer::from(
883                self.private_key_der.clone(),
884            )),
885            _ => PrivateKeyDer::Pkcs8(rustls::pki_types::PrivatePkcs8KeyDer::from(
886                self.private_key_der.clone(),
887            )),
888        };
889        let signing_key = match rustls::crypto::ring::sign::any_supported_type(&key_der) {
890            Ok(k) => k,
891            Err(e) => {
892                #[cfg(feature = "tracing")]
893                tracing::warn!(
894                    "eggfetch: unsupported private key type ({key_label}): {e}",
895                    key_label = self.key_label
896                );
897                #[cfg(not(feature = "tracing"))]
898                let _ = (&self.key_label, &e);
899                return None;
900            }
901        };
902        Some(Arc::new(rustls::sign::CertifiedKey::new(
903            self.cert_chain.clone(),
904            signing_key,
905        )))
906    }
907
908    fn has_certs(&self) -> bool {
909        !self.cert_chain.is_empty()
910    }
911}
912
913// PEM parsing utilities.
914
915/// Byte sequence opening a PEM section (`-----BEGIN `).
916const PEM_BEGIN: &[u8] = b"-----BEGIN ";
917/// Byte sequence closing a PEM section (`-----END `).
918const PEM_END: &[u8] = b"-----END ";
919
920/// Load PEM-encoded certificates from a file.
921fn load_pem_certs_from_path(path: &Path) -> Result<Vec<CertificateDer<'static>>> {
922    if path.is_dir() {
923        let mut entries = std::fs::read_dir(path)
924            .map_err(|e| Error::CaBundle(format!("failed to read {}: {e}", path.display())))?
925            .filter_map(std::result::Result::ok)
926            .collect::<Vec<_>>();
927        entries.sort_by_key(std::fs::DirEntry::file_name);
928
929        let mut certs = Vec::new();
930        for entry in entries {
931            if !entry.metadata().is_ok_and(|metadata| metadata.is_file()) {
932                continue;
933            }
934            if let Ok(data) = std::fs::read(entry.path()) {
935                certs.extend(parse_pem_certificates(&data)?);
936            }
937        }
938        return Ok(certs);
939    }
940
941    let data = std::fs::read(path)
942        .map_err(|e| Error::CaBundle(format!("failed to read {}: {e}", path.display())))?;
943    parse_pem_certificates(&data)
944}
945
946/// Parse PEM-encoded certificate data into DER certificates.
947///
948/// Iterates over every `-----BEGIN`/`-----END` section in the input.
949/// Non-PEM content between sections is skipped. Malformed or unterminated
950/// PEM sections return an error instead of silently producing a partial trust
951/// store. Sections other than `CERTIFICATE` (keys, etc.) are ignored.
952fn parse_pem_certificates(pem_bytes: &[u8]) -> Result<Vec<CertificateDer<'static>>> {
953    let mut certs = Vec::new();
954    let mut rest = pem_bytes;
955
956    while let Some(pos) = find_pem_start(rest) {
957        // Feed `decode_vec` exactly one section: it rejects input with
958        // trailing content after the END marker, so handing it the whole
959        // remaining bundle would fail on multi-certificate files.
960        let section = &rest[pos..];
961        let section_len = pem_section_len(section)
962            .ok_or_else(|| Error::CaBundle("unterminated PEM block in certificate data".into()))?;
963        let (label, data) = pem_rfc7468::decode_vec(&section[..section_len])
964            .map_err(|e| Error::CaBundle(format!("invalid PEM block in certificate data: {e}")))?;
965        if label == "CERTIFICATE" {
966            certs.push(CertificateDer::from(data));
967        } else {
968            // CA bundles should contain only certificates; a key block here
969            // likely means the user passed a private-key file as a CA path,
970            // which would otherwise yield a confusing "no certificates found"
971            // error. Emit a diagnostic to aid troubleshooting.
972            #[cfg(feature = "tracing")]
973            tracing::warn!("eggfetch: ignoring non-certificate PEM block `{label}` in CA bundle");
974            #[cfg(not(feature = "tracing"))]
975            let _ = &label;
976        }
977        rest = &section[section_len..];
978    }
979
980    Ok(certs)
981}
982
983/// Find the offset of the next `-----BEGIN ` marker in the input.
984fn find_pem_start(data: &[u8]) -> Option<usize> {
985    if data.len() < PEM_BEGIN.len() {
986        return None;
987    }
988    data.windows(PEM_BEGIN.len()).position(|w| w == PEM_BEGIN)
989}
990
991/// Length of the PEM section starting at the beginning of `data` (which
992/// must start with a BEGIN marker): from that marker through the end of
993/// the first following END-marker line.
994///
995/// Returns `None` when no END marker exists (truncated block). The base64
996/// body cannot contain the `-----END ` byte sequence, so the first match
997/// after BEGIN closes the section.
998fn pem_section_len(data: &[u8]) -> Option<usize> {
999    let after_begin = &data[PEM_BEGIN.len()..];
1000    let end_marker = after_begin
1001        .windows(PEM_END.len())
1002        .position(|w| w == PEM_END)?
1003        + PEM_BEGIN.len();
1004    let line_end = data[end_marker..]
1005        .iter()
1006        .position(|&b| b == b'\n')
1007        .map_or(data.len(), |p| end_marker + p + 1);
1008    Some(line_end)
1009}
1010
1011/// Parse a PEM-encoded private key, returning raw DER bytes and the PEM label.
1012///
1013/// Like [`parse_pem_certificates`], skips non-PEM sections between valid
1014/// blocks but rejects malformed or unterminated PEM sections.
1015fn parse_private_key(key_bytes: &[u8]) -> Result<(Vec<u8>, String)> {
1016    let mut rest = key_bytes;
1017
1018    while let Some(pos) = find_pem_start(rest) {
1019        let section = &rest[pos..];
1020        let section_len = pem_section_len(section).ok_or_else(|| {
1021            Error::PrivateKey("unterminated PEM block in private key data".into())
1022        })?;
1023        let (label, data) = pem_rfc7468::decode_vec(&section[..section_len]).map_err(|e| {
1024            Error::PrivateKey(format!("invalid PEM block in private key data: {e}"))
1025        })?;
1026        if matches!(label, "PRIVATE KEY" | "RSA PRIVATE KEY" | "EC PRIVATE KEY") {
1027            return Ok((data, label.to_string()));
1028        }
1029        rest = &section[section_len..];
1030    }
1031
1032    Err(Error::PrivateKey("no private key found in PEM data".into()))
1033}
1034
1035#[cfg(test)]
1036mod tests {
1037    use super::*;
1038    use proptest::prelude::*;
1039
1040    #[test]
1041    fn default_tls_config() {
1042        let config = TlsConfig::default();
1043        assert!(config.verify_hostname());
1044        assert!(config.verify_certificate());
1045        assert!(config.sni_enabled());
1046    }
1047
1048    #[test]
1049    fn builder_defaults() {
1050        let config = TlsConfig::builder().build();
1051        assert!(config.verify_hostname());
1052        assert!(config.verify_certificate());
1053        assert!(config.sni_enabled());
1054    }
1055
1056    #[test]
1057    fn builder_disable_verification() {
1058        let config = TlsConfig::builder()
1059            .danger_accept_invalid_certs(true)
1060            .build();
1061        assert!(!config.verify_hostname());
1062        assert!(!config.verify_certificate());
1063    }
1064
1065    #[test]
1066    fn config_disable_verification_preserves_other_settings() {
1067        let config = TlsConfig::builder()
1068            .sni(false)
1069            .min_tls_version(TlsVersion::Tls13)
1070            .build()
1071            .danger_accept_invalid_certs(true);
1072        assert!(!config.verify_hostname());
1073        assert!(!config.verify_certificate());
1074        assert!(!config.sni_enabled());
1075        assert_eq!(config.min_version, Some(TlsVersion::Tls13));
1076    }
1077
1078    #[test]
1079    fn builder_custom_tls_version() {
1080        let config = TlsConfig::builder()
1081            .min_tls_version(TlsVersion::Tls13)
1082            .build();
1083        assert_eq!(config.min_version, Some(TlsVersion::Tls13));
1084    }
1085
1086    #[test]
1087    fn builder_invalid_version_range() {
1088        let config = TlsConfig::builder()
1089            .min_tls_version(TlsVersion::Tls13)
1090            .max_tls_version(TlsVersion::Tls12)
1091            .build();
1092        let err = config.build_rustls_config().unwrap_err();
1093        assert_eq!(err.kind(), "tls_config");
1094    }
1095
1096    #[test]
1097    fn builder_sni_disabled() {
1098        let config = TlsConfig::builder().sni(false).build();
1099        assert!(!config.sni_enabled());
1100    }
1101
1102    #[test]
1103    fn trust_store_default() {
1104        let config = TlsConfig::builder().build();
1105        assert!(matches!(
1106            config.trust_store,
1107            TrustStore::NativeWithWebPkiFallback
1108        ));
1109    }
1110
1111    #[test]
1112    fn trust_store_custom_empty_rejected() {
1113        let result = TlsConfig::builder()
1114            .ca_certificate_pem(b"")
1115            .map(super::TlsConfigBuilder::build);
1116        assert!(result.is_err());
1117    }
1118
1119    #[test]
1120    fn add_ca_certificate_path_combines_files_and_directories() {
1121        let make_ca_pem = || {
1122            let mut params = rcgen::CertificateParams::default();
1123            params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
1124            let key = rcgen::KeyPair::generate().unwrap();
1125            params.self_signed(&key).unwrap().pem()
1126        };
1127        let first = make_ca_pem();
1128        let second = make_ca_pem();
1129        let tempdir = tempfile::tempdir().unwrap();
1130        let first_path = tempdir.path().join("first.pem");
1131        let cert_dir = tempdir.path().join("certs");
1132        std::fs::create_dir(&cert_dir).unwrap();
1133        std::fs::write(&first_path, first).unwrap();
1134        std::fs::write(cert_dir.join("second.pem"), second).unwrap();
1135
1136        let config = TlsConfig::builder()
1137            .ca_certificate_path(first_path)
1138            .unwrap()
1139            .add_ca_certificate_path(cert_dir)
1140            .unwrap()
1141            .build();
1142        assert_eq!(config.custom_ca_roots.len(), 2);
1143
1144        let empty_dir = tempdir.path().join("empty");
1145        std::fs::create_dir(&empty_dir).unwrap();
1146        let config = TlsConfig::builder()
1147            .ca_certificate_path(tempdir.path().join("first.pem"))
1148            .unwrap()
1149            .add_ca_certificate_path(empty_dir)
1150            .unwrap()
1151            .build();
1152        assert_eq!(config.custom_ca_roots.len(), 1);
1153    }
1154
1155    #[test]
1156    fn tls_version_ordering() {
1157        assert!(TlsVersion::Tls12 < TlsVersion::Tls13);
1158    }
1159
1160    #[test]
1161    fn build_rustls_config_verification() {
1162        let config = TlsConfig::builder().build();
1163        let result = config.build_rustls_config();
1164        assert!(result.is_ok());
1165    }
1166
1167    #[test]
1168    fn build_rustls_config_no_verify() {
1169        let config = TlsConfig::builder()
1170            .danger_accept_invalid_certs(true)
1171            .sni(false)
1172            .build();
1173        let rustls_config = config.build_rustls_config().unwrap();
1174        assert!(!rustls_config.enable_sni);
1175    }
1176
1177    #[test]
1178    fn build_rustls_config_version_range() {
1179        let config = TlsConfig::builder()
1180            .min_tls_version(TlsVersion::Tls12)
1181            .max_tls_version(TlsVersion::Tls13)
1182            .build();
1183        let result = config.build_rustls_config();
1184        assert!(result.is_ok());
1185    }
1186
1187    #[test]
1188    fn parse_empty_pem_certificates() {
1189        let result = parse_pem_certificates(b"");
1190        assert!(result.unwrap().is_empty());
1191    }
1192
1193    #[test]
1194    fn parse_invalid_pem_certificates() {
1195        let result = parse_pem_certificates(b"not valid pem data");
1196        assert!(result.unwrap().is_empty());
1197    }
1198
1199    #[test]
1200    fn parse_pem_certificates_skip_garbage_between_blocks() {
1201        // A corrupted/comment section between two certificates must not
1202        // silently discard the rest of the bundle.
1203        let valid_block = |body: &[u8]| -> Vec<u8> {
1204            let mut block = b"-----BEGIN CERTIFICATE-----\n".to_vec();
1205            block.extend_from_slice(body);
1206            block.extend_from_slice(b"\n-----END CERTIFICATE-----\n");
1207            block
1208        };
1209        // Valid base64 bodies (pem_rfc7468 validates base64 content).
1210        let first = valid_block(b"AAAA");
1211        let second = valid_block(b"BBBB");
1212        let mut pem = first;
1213        pem.extend_from_slice(b"\nthis is not valid PEM \x01\x02 data\n");
1214        pem.extend_from_slice(&second);
1215
1216        let certs = parse_pem_certificates(&pem).unwrap();
1217        assert_eq!(certs.len(), 2, "both certificates must be recovered");
1218    }
1219
1220    #[test]
1221    fn parse_pem_certificates_multi_block_bundle() {
1222        // A plain concatenated bundle (the standard CA-bundle shape)
1223        // must yield every certificate.
1224        let mut pem = b"-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n".to_vec();
1225        pem.extend_from_slice(b"-----BEGIN CERTIFICATE-----\nBBBB\n-----END CERTIFICATE-----\n");
1226        pem.extend_from_slice(b"-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----\n");
1227
1228        let certs = parse_pem_certificates(&pem).unwrap();
1229        assert_eq!(certs.len(), 2, "both certificates, key section skipped");
1230    }
1231
1232    #[test]
1233    fn parse_private_key_skips_leading_garbage() {
1234        let key_block = b"-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----\n";
1235        let mut pem = b"corrupt \x03 preamble\n".to_vec();
1236        pem.extend_from_slice(key_block);
1237
1238        let (der, label) = parse_private_key(&pem).unwrap();
1239        assert_eq!(label, "PRIVATE KEY");
1240        // Base64 "AAAA" decodes to three NUL bytes.
1241        assert_eq!(der, vec![0u8, 0, 0]);
1242    }
1243
1244    #[test]
1245    fn parse_pem_certificates_rejects_corrupted_blocks() {
1246        let pem = b"-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n\
1247-----BEGIN CERTIFICATE-----\n%%%\n-----END CERTIFICATE-----\n";
1248        let err = parse_pem_certificates(pem).unwrap_err();
1249        assert_eq!(err.kind(), "ca_bundle");
1250    }
1251
1252    #[test]
1253    fn error_variants() {
1254        let err = Error::TlsConfig("test".into());
1255        assert_eq!(err.kind(), "tls_config");
1256
1257        let err = Error::CaBundle("test".into());
1258        assert_eq!(err.kind(), "ca_bundle");
1259
1260        let err = Error::ClientCert("test".into());
1261        assert_eq!(err.kind(), "client_cert");
1262
1263        let err = Error::PrivateKey("test".into());
1264        assert_eq!(err.kind(), "private_key");
1265
1266        let err = Error::CertificateVerification("test".into());
1267        assert_eq!(err.kind(), "certificate_verification");
1268
1269        let err = Error::HostnameVerification("test".into());
1270        assert_eq!(err.kind(), "hostname_verification");
1271    }
1272
1273    #[test]
1274    fn debug_impl_no_secrets() {
1275        let config = TlsConfig::builder().build();
1276        let debug = format!("{config:?}");
1277        assert!(debug.contains("verify_hostname: true"));
1278        assert!(debug.contains("verify_certificate: true"));
1279    }
1280
1281    #[test]
1282    fn client_identity_debug_no_private_key() {
1283        let identity = ClientIdentity::Pem {
1284            cert_chain: vec![],
1285            private_key_der: b"super-secret-private-key-data".to_vec(),
1286            key_label: "PRIVATE KEY".to_string(),
1287        };
1288        let debug = format!("{identity:?}");
1289        assert!(
1290            !debug.contains("super-secret"),
1291            "ClientIdentity Debug must not leak private key bytes: {debug}"
1292        );
1293        assert!(debug.contains("cert_count"));
1294        assert!(debug.contains("key_label"));
1295    }
1296
1297    proptest::proptest! {
1298        #[test]
1299        fn parse_pem_certificates_empty_input(_ in 0u64..100) {
1300            let result = parse_pem_certificates(b"");
1301            prop_assert!(result.unwrap().is_empty());
1302        }
1303
1304        #[test]
1305        fn parse_pem_certificates_garbage(input in ".{0,200}") {
1306            // Must not panic
1307            let _ = parse_pem_certificates(input.as_bytes());
1308        }
1309
1310        #[test]
1311        fn tls_config_builder_round_trip(sni in prop::bool::ANY) {
1312            let config = TlsConfig::builder()
1313                .sni(sni)
1314                .build();
1315            prop_assert_eq!(config.sni_enabled(), sni);
1316            // Defaults are always true
1317            prop_assert!(config.verify_hostname());
1318            prop_assert!(config.verify_certificate());
1319        }
1320
1321        #[test]
1322        fn build_rustls_config_valid_for_defaults(_ in 0u64..100) {
1323            let config = TlsConfig::default();
1324            let result = config.build_rustls_config();
1325            prop_assert!(result.is_ok());
1326        }
1327    }
1328}