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//! - When `tls-native-roots` is enabled, native system roots are preferred and
12//!   packaged `WebPKI` roots are used as a construction fallback when native
13//!   roots are unavailable. Without that feature, packaged `WebPKI` roots are
14//!   the default.
15//! - TLS 1.2 and 1.3 are supported.
16//! - SNI is enabled by default.
17//!
18//! # Custom CA bundles
19//!
20//! A custom CA bundle replaces the default root store (it does not
21//! augment). The bundle is loaded at construction time; malformed or
22//! empty bundles are rejected immediately.
23//!
24//! # Safety
25//!
26//! Disabling certificate verification (`verify = false`) weakens TLS
27//! guarantees. It should only be used for testing or against known
28//! trusted targets. The Python binding documents this in the `verify`
29//! parameter docstring.
30
31use std::path::Path;
32use std::sync::atomic::{AtomicU64, Ordering};
33use std::sync::Arc;
34use std::sync::OnceLock;
35
36use rustls::pki_types::{CertificateDer, PrivateKeyDer};
37
38use crate::error::{Error, Result};
39
40/// Monotonic source for opaque TLS connection-policy tokens.
41///
42/// Each independently built `TlsConfig` mints a fresh token; `Clone` shares
43/// the token. The value is never rendered in diagnostics and carries no key
44/// material — it is only an equality token for reusable-client caches. `0`
45/// is reserved for "no TLS config" in route keys, so issuance starts at `1`.
46static TLS_POLICY_TOKEN_NEXT: AtomicU64 = AtomicU64::new(1);
47
48/// Mint a fresh opaque policy token for a newly built or mutated `TlsConfig`.
49fn mint_tls_policy_token() -> Arc<u64> {
50    // Skip `0` (reserved for "no TLS config"). Each `fetch_add` return value
51    // is distinct, so retrying on `0` cannot collide with a concurrent minter.
52    loop {
53        let id = TLS_POLICY_TOKEN_NEXT.fetch_add(1, Ordering::Relaxed);
54        if id != 0 {
55            return Arc::new(id);
56        }
57    }
58}
59
60/// Trust store source for certificate verification.
61#[derive(Debug, Clone, Default)]
62pub enum TrustStore {
63    /// Use native system roots with packaged `WebPKI` roots as a construction
64    /// fallback when `tls-native-roots` is enabled. Without that feature, the
65    /// default builder uses packaged `WebPKI` roots directly.
66    ///
67    /// When native loading fails, construction succeeds on `WebPKI` roots.
68    /// Per-path causes are emitted only via `tracing::warn` with feature
69    /// `tracing`; without it the substitution is silent. Callers who must
70    /// detect the fallback should build with [`TrustStore::NativeOnly`],
71    /// which fails closed, or enable `tracing`.
72    #[default]
73    NativeWithWebPkiFallback,
74    /// Use only native system roots. Fails at construction if the
75    /// platform root store is unavailable.
76    NativeOnly,
77    /// Use only packaged Mozilla/WebPKI roots. Does not consult the
78    /// operating system trust store.
79    WebPkiOnly,
80    /// Use the provided CA certificates as the sole trust anchor.
81    /// These replace all other roots.
82    Custom(Vec<CertificateDer<'static>>),
83}
84
85/// A client certificate and private key for mTLS.
86#[derive(Clone)]
87pub enum ClientIdentity {
88    /// A certificate chain and private key in DER format.
89    Pem {
90        /// The certificate chain, in DER bytes.
91        cert_chain: Vec<CertificateDer<'static>>,
92        /// The private key, as raw DER bytes.
93        private_key_der: Vec<u8>,
94        /// The label from the PEM block (e.g., "PRIVATE KEY", "RSA PRIVATE KEY").
95        key_label: String,
96    },
97}
98
99impl std::fmt::Debug for ClientIdentity {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101        match self {
102            Self::Pem {
103                cert_chain,
104                key_label,
105                ..
106            } => f
107                .debug_struct("ClientIdentity::Pem")
108                .field("cert_count", &cert_chain.len())
109                .field("key_label", key_label)
110                .finish_non_exhaustive(),
111        }
112    }
113}
114
115/// Minimum or maximum TLS protocol version.
116#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
117pub enum TlsVersion {
118    /// TLS 1.2.
119    Tls12,
120    /// TLS 1.3.
121    Tls13,
122}
123
124impl TlsVersion {
125    fn to_rustls(self) -> &'static rustls::SupportedProtocolVersion {
126        match self {
127            Self::Tls12 => &rustls::version::TLS12,
128            Self::Tls13 => &rustls::version::TLS13,
129        }
130    }
131}
132
133/// Immutable shared TLS configuration for a client.
134///
135/// Construct via [`TlsConfig::builder()`] or [`TlsConfig::builder_with_defaults()`].
136#[derive(Clone)]
137pub struct TlsConfig {
138    trust_store: TrustStore,
139    custom_ca_roots: Vec<CertificateDer<'static>>,
140    additional_ca_roots: Vec<CertificateDer<'static>>,
141    crypto_provider: Option<Arc<rustls::crypto::CryptoProvider>>,
142    client_identity: Option<ClientIdentity>,
143    verify_hostname: bool,
144    verify_certificate: bool,
145    min_version: Option<TlsVersion>,
146    max_version: Option<TlsVersion>,
147    sni_enabled: bool,
148    root_store: Arc<OnceLock<Result<rustls::RootCertStore>>>,
149    /// Opaque connection-policy identity shared by unchanged clones.
150    ///
151    /// Any operation that creates a `TlsConfig` with changed
152    /// connection-affecting semantics mints a new token. The token is
153    /// crate-private, never rendered, and carries no key material. The
154    /// lazily built `root_store` cache is an implementation cache only and
155    /// never participates in identity on its own.
156    policy_token: Arc<u64>,
157}
158
159impl std::fmt::Debug for TlsConfig {
160    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161        f.debug_struct("TlsConfig")
162            .field("trust_store", &self.trust_store)
163            .field("has_custom_ca", &!self.custom_ca_roots.is_empty())
164            .field("additional_ca_count", &self.additional_ca_roots.len())
165            .field(
166                "has_explicit_crypto_provider",
167                &self.crypto_provider.is_some(),
168            )
169            .field("has_client_identity", &self.client_identity.is_some())
170            .field("verify_hostname", &self.verify_hostname)
171            .field("verify_certificate", &self.verify_certificate)
172            .field("min_version", &self.min_version)
173            .field("max_version", &self.max_version)
174            .field("sni_enabled", &self.sni_enabled)
175            .finish_non_exhaustive()
176    }
177}
178
179impl Default for TlsConfig {
180    fn default() -> Self {
181        Self::builder().build()
182    }
183}
184
185impl TlsConfig {
186    /// Return an opaque identity for internal connection-client caches.
187    ///
188    /// Cloned configurations share this identity; separately constructed
189    /// configurations do not pool together even when their visible settings
190    /// happen to match, and any consuming mutator that changes
191    /// connection-affecting policy mints a new token. The value is never
192    /// exposed in diagnostics and carries no key material.
193    ///
194    /// Field/mutator inventory (all connection-affecting): trust-store
195    /// selection and custom/additional CA roots, explicit crypto provider,
196    /// mTLS client identity, `verify_hostname` / `verify_certificate`
197    /// (including `danger_accept_invalid_certs`), min/max TLS versions, and
198    /// SNI enablement. The lazily built `root_store` cache is explicitly
199    /// excluded: clones share it, but sharing it no longer implies
200    /// compatibility.
201    #[cfg(all(feature = "proxy", feature = "tls-rustls"))]
202    pub(crate) fn connection_identity(&self) -> u64 {
203        *self.policy_token
204    }
205
206    /// Create a builder with secure defaults (verification enabled, native
207    /// roots preferred, SNI enabled).
208    #[must_use]
209    pub fn builder() -> TlsConfigBuilder {
210        TlsConfigBuilder::new()
211    }
212
213    /// Create a builder from the default configuration.
214    ///
215    /// This is identical to [`TlsConfig::builder()`] and exists for
216    /// discoverability.
217    #[must_use]
218    pub fn builder_with_defaults() -> TlsConfigBuilder {
219        Self::builder()
220    }
221
222    /// Enable or disable certificate and hostname verification while
223    /// retaining the rest of this configuration.
224    ///
225    /// This mints a fresh opaque connection identity: a clone modified this
226    /// way must never compare as cache-compatible with its parent, even
227    /// though both share the same lazily built root-store cache.
228    #[must_use]
229    pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
230        self.verify_certificate = !accept;
231        self.verify_hostname = !accept;
232        self.policy_token = mint_tls_policy_token();
233        self
234    }
235
236    /// Build a `tokio_rustls::TlsConnector` from this TLS configuration.
237    ///
238    /// This is the convenience entry point for
239    /// [`crate::network_stream::UpgradedStream::start_tls`] and other
240    /// contexts where a generic TLS upgrade must reflect the full
241    /// configured policy (custom CA, verification, SNI, version bounds,
242    /// client identity).
243    ///
244    /// # Errors
245    ///
246    /// Returns an error if the underlying rustls configuration cannot be
247    /// built (see [`Self::build_rustls_config`]).
248    pub fn tls_connector(&self) -> Result<tokio_rustls::TlsConnector> {
249        let config = self.build_rustls_config()?;
250        Ok(tokio_rustls::TlsConnector::from(Arc::new(config)))
251    }
252
253    /// Build a `rustls::ClientConfig` from this TLS configuration.
254    ///
255    /// # Errors
256    ///
257    /// Returns an error if the trust store, client certificates, or
258    /// protocol versions cannot be configured.
259    pub fn build_rustls_config(&self) -> Result<rustls::ClientConfig> {
260        let root_store = self.build_root_store()?;
261
262        let mut protocol_versions = Vec::new();
263        match (self.min_version, self.max_version) {
264            (Some(min), Some(max)) => {
265                if min > max {
266                    return Err(Error::TlsConfig(format!(
267                        "invalid TLS version range: min ({min:?}) > max ({max:?})"
268                    )));
269                }
270                for v in Self::supported_versions() {
271                    if v >= min && v <= max {
272                        protocol_versions.push(v.to_rustls());
273                    }
274                }
275            }
276            (Some(min), None) => {
277                for v in Self::supported_versions() {
278                    if v >= min {
279                        protocol_versions.push(v.to_rustls());
280                    }
281                }
282            }
283            (None, Some(max)) => {
284                for v in Self::supported_versions() {
285                    if v <= max {
286                        protocol_versions.push(v.to_rustls());
287                    }
288                }
289            }
290            (None, None) => {
291                for v in Self::supported_versions() {
292                    protocol_versions.push(v.to_rustls());
293                }
294            }
295        }
296
297        if protocol_versions.is_empty() {
298            return Err(Error::TlsConfig(
299                "no supported TLS versions in configured range".into(),
300            ));
301        }
302
303        let provider = self.resolve_crypto_provider()?;
304        let supported_schemes = provider
305            .signature_verification_algorithms
306            .supported_schemes();
307        let mut config = if self.verify_certificate && self.verify_hostname {
308            rustls::ClientConfig::builder_with_provider(provider.clone())
309                .with_protocol_versions(&protocol_versions)
310                .map_err(|e| Error::TlsConfig(format!("TLS version config: {e}")))?
311                .with_root_certificates(root_store)
312                .with_no_client_auth()
313        } else if self.verify_certificate {
314            rustls::ClientConfig::builder_with_provider(provider.clone())
315                .with_protocol_versions(&protocol_versions)
316                .map_err(|e| Error::TlsConfig(format!("TLS version config: {e}")))?
317                .dangerous()
318                .with_custom_certificate_verifier(no_hostname_verifier(
319                    &root_store,
320                    provider.clone(),
321                )?)
322                .with_no_client_auth()
323        } else {
324            rustls::ClientConfig::builder_with_provider(provider.clone())
325                .with_protocol_versions(&protocol_versions)
326                .map_err(|e| Error::TlsConfig(format!("TLS version config: {e}")))?
327                .dangerous()
328                .with_custom_certificate_verifier(Arc::new(NoVerifier { supported_schemes }))
329                .with_no_client_auth()
330        };
331
332        // Default ALPN advertises both protocols when HTTP/2 is compiled in.
333        // Callers enforcing `HttpVersionPolicy` must override via
334        // `crate::client::configure_tls_alpn` (used by all client paths).
335        // Direct use of `build_rustls_config` without override intentionally
336        // retains this default; an empty default would silently downgrade
337        // `tls_connector`/`start_tls` users to HTTP/1.1.
338        #[cfg(feature = "transport-http2")]
339        {
340            config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
341        }
342        #[cfg(not(feature = "transport-http2"))]
343        {
344            config.alpn_protocols = vec![b"http/1.1".to_vec()];
345        }
346        config.enable_sni = self.sni_enabled;
347
348        if let Some(identity) = &self.client_identity {
349            config.client_auth_cert_resolver = Arc::new(SingleCertResolver::new(
350                identity.clone(),
351                provider.as_ref(),
352            )?);
353        }
354
355        Ok(config)
356    }
357
358    /// Build the root certificate store from the configured trust policy.
359    fn build_root_store(&self) -> Result<rustls::RootCertStore> {
360        self.root_store
361            .get_or_init(|| self.build_root_store_uncached())
362            .clone()
363    }
364
365    fn build_root_store_uncached(&self) -> Result<rustls::RootCertStore> {
366        let mut roots = match &self.trust_store {
367            // Explicit opt-in fallback: `NativeWithWebPkiFallback` silently
368            // uses WebPKI roots when native loading fails or yields empty
369            // (silent without the `tracing` feature). Fail-closed callers
370            // must select `NativeOnly` instead.
371            TrustStore::NativeWithWebPkiFallback => match Self::try_native_roots() {
372                Ok(store) if !store.is_empty() => Ok(store),
373                _ => Ok(Self::webpki_roots()),
374            },
375            TrustStore::NativeOnly => Self::try_native_roots(),
376            TrustStore::WebPkiOnly => Ok(Self::webpki_roots()),
377            TrustStore::Custom(certs) => {
378                if certs.is_empty() {
379                    return Err(Error::CaBundle("custom CA bundle is empty".into()));
380                }
381                let mut store = rustls::RootCertStore::empty();
382                for cert in certs {
383                    store
384                        .add(cert.clone())
385                        .map_err(|e| Error::CaBundle(format!("invalid CA certificate: {e}")))?;
386                }
387                Ok(store)
388            }
389        }?;
390
391        for cert in &self.additional_ca_roots {
392            roots
393                .add(cert.clone())
394                .map_err(|e| Error::CaBundle(format!("invalid additional CA certificate: {e}")))?;
395        }
396        Ok(roots)
397    }
398
399    #[cfg(not(feature = "tls-native-roots"))]
400    fn try_native_roots() -> Result<rustls::RootCertStore> {
401        Err(Error::TlsConfig(
402            "native root certificates are disabled; enable tls-native-roots".into(),
403        ))
404    }
405
406    #[cfg(feature = "tls-native-roots")]
407    fn try_native_roots() -> Result<rustls::RootCertStore> {
408        let mut roots = rustls::RootCertStore::empty();
409
410        #[cfg(target_os = "linux")]
411        let pem_paths: &[&str] = &[
412            "/etc/ssl/certs/ca-certificates.crt",
413            "/etc/pki/tls/certs/ca-bundle.crt",
414            "/etc/ssl/ca-bundle.pem",
415        ];
416
417        #[cfg(target_os = "macos")]
418        let pem_paths: &[&str] = &["/etc/ssl/cert.pem", "/usr/local/etc/openssl/cert.pem"];
419
420        #[cfg(any(target_os = "linux", target_os = "macos"))]
421        for path in pem_paths {
422            match load_pem_certs_from_path(Path::new(path)) {
423                Ok(certs) => {
424                    for cert in certs {
425                        if let Err(e) = roots.add(cert) {
426                            #[cfg(feature = "tracing")]
427                            tracing::warn!(
428                                "eggfetch: skipped invalid CA certificate in {path}: {e}"
429                            );
430                            #[cfg(not(feature = "tracing"))]
431                            let _ = (path, &e);
432                        }
433                    }
434                }
435                Err(e) => {
436                    // A missing or unreadable system bundle silently falls
437                    // back toward WebPKI roots below; log it so operators
438                    // have a signal instead of a silent trust change.
439                    #[cfg(feature = "tracing")]
440                    tracing::warn!("eggfetch: failed to load native CA bundle {path}: {e}");
441                    #[cfg(not(feature = "tracing"))]
442                    let _ = (path, &e);
443                }
444            }
445        }
446
447        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
448        {
449            for cert in rustls_native_certs::load_native_certs().certs {
450                if let Err(e) = roots.add(cert) {
451                    #[cfg(feature = "tracing")]
452                    tracing::warn!("eggfetch: skipped invalid native CA certificate: {e}");
453                    #[cfg(not(feature = "tracing"))]
454                    let _ = &e;
455                }
456            }
457        }
458
459        if roots.is_empty() {
460            return Err(Error::TlsConfig(
461                "native root certificates not available".into(),
462            ));
463        }
464        Ok(roots)
465    }
466
467    fn webpki_roots() -> rustls::RootCertStore {
468        let mut roots = rustls::RootCertStore::empty();
469        roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
470        roots
471    }
472
473    fn supported_versions() -> impl Iterator<Item = TlsVersion> {
474        [TlsVersion::Tls12, TlsVersion::Tls13].into_iter()
475    }
476
477    /// Returns `true` if hostname verification is enabled.
478    #[must_use]
479    pub fn verify_hostname(&self) -> bool {
480        self.verify_hostname
481    }
482
483    /// Returns `true` if certificate verification is enabled.
484    #[must_use]
485    pub fn verify_certificate(&self) -> bool {
486        self.verify_certificate
487    }
488
489    /// Returns `true` if SNI is enabled.
490    #[must_use]
491    pub fn sni_enabled(&self) -> bool {
492        self.sni_enabled
493    }
494
495    /// Returns whether this configuration carries an explicitly selected
496    /// Rustls crypto provider.
497    #[must_use]
498    pub fn has_explicit_crypto_provider(&self) -> bool {
499        self.crypto_provider.is_some()
500    }
501
502    /// Build the provider used by this configuration without changing the
503    /// process-wide Rustls provider.
504    fn resolve_crypto_provider(&self) -> Result<Arc<rustls::crypto::CryptoProvider>> {
505        if let Some(provider) = &self.crypto_provider {
506            return Ok(provider.clone());
507        }
508        process_crypto_provider()
509    }
510
511    /// Build a `rustls::ClientConfig` for QUIC (TLS 1.3 only, ALPN `h3`).
512    ///
513    /// This differs from [`build_rustls_config`](Self::build_rustls_config)
514    /// by restricting to TLS 1.3 and using the `h3` ALPN.
515    ///
516    /// # Errors
517    ///
518    /// Returns an error if the trust store, client certificates, or
519    /// protocol versions cannot be configured.
520    #[allow(dead_code)]
521    pub(crate) fn build_quic_rustls_config(&self) -> Result<rustls::ClientConfig> {
522        let root_store = self.build_root_store()?;
523
524        let provider = self.resolve_crypto_provider()?;
525        let supported_schemes = provider
526            .signature_verification_algorithms
527            .supported_schemes();
528        let mut config = if self.verify_certificate && self.verify_hostname {
529            rustls::ClientConfig::builder_with_provider(provider.clone())
530                .with_protocol_versions(&[&rustls::version::TLS13])
531                .map_err(|e| Error::Tls(format!("TLS version config: {e}")))?
532                .with_root_certificates(root_store)
533                .with_no_client_auth()
534        } else if self.verify_certificate {
535            rustls::ClientConfig::builder_with_provider(provider.clone())
536                .with_protocol_versions(&[&rustls::version::TLS13])
537                .map_err(|e| Error::Tls(format!("TLS version config: {e}")))?
538                .dangerous()
539                .with_custom_certificate_verifier(no_hostname_verifier(
540                    &root_store,
541                    provider.clone(),
542                )?)
543                .with_no_client_auth()
544        } else {
545            rustls::ClientConfig::builder_with_provider(provider.clone())
546                .with_protocol_versions(&[&rustls::version::TLS13])
547                .map_err(|e| Error::Tls(format!("TLS version config: {e}")))?
548                .dangerous()
549                .with_custom_certificate_verifier(Arc::new(NoVerifier { supported_schemes }))
550                .with_no_client_auth()
551        };
552
553        config.alpn_protocols = vec![b"h3".to_vec()];
554        config.enable_sni = self.sni_enabled;
555
556        if let Some(identity) = &self.client_identity {
557            config.client_auth_cert_resolver = Arc::new(SingleCertResolver::new(
558                identity.clone(),
559                provider.as_ref(),
560            )?);
561        }
562
563        Ok(config)
564    }
565}
566
567/// Builder for constructing a [`TlsConfig`].
568pub struct TlsConfigBuilder {
569    trust_store: TrustStore,
570    custom_ca_roots: Vec<CertificateDer<'static>>,
571    additional_ca_roots: Vec<CertificateDer<'static>>,
572    crypto_provider: Option<Arc<rustls::crypto::CryptoProvider>>,
573    client_identity: Option<ClientIdentity>,
574    verify_hostname: bool,
575    verify_certificate: bool,
576    min_version: Option<TlsVersion>,
577    max_version: Option<TlsVersion>,
578    sni_enabled: bool,
579}
580
581impl Default for TlsConfigBuilder {
582    fn default() -> Self {
583        Self::new()
584    }
585}
586
587impl TlsConfigBuilder {
588    /// Create a new builder with secure defaults.
589    #[must_use]
590    pub fn new() -> Self {
591        Self {
592            trust_store: TrustStore::NativeWithWebPkiFallback,
593            custom_ca_roots: Vec::new(),
594            additional_ca_roots: Vec::new(),
595            crypto_provider: None,
596            client_identity: None,
597            verify_hostname: true,
598            verify_certificate: true,
599            min_version: None,
600            max_version: None,
601            sni_enabled: true,
602        }
603    }
604
605    /// Set the trust store source.
606    #[must_use]
607    pub fn trust_store(mut self, store: TrustStore) -> Self {
608        self.trust_store = store;
609        self
610    }
611
612    /// Load CA certificates from a PEM file, replacing any existing trust
613    /// store configuration.
614    ///
615    /// # Errors
616    ///
617    /// Returns an error if the file cannot be read or the PEM data is
618    /// malformed.
619    pub fn ca_certificate_path(mut self, path: impl AsRef<Path>) -> Result<Self> {
620        let certs = load_pem_certs_from_path(path.as_ref())?;
621        if certs.is_empty() {
622            // Fail closed for the replace variant: a typo'd empty directory
623            // must not silently leave the previous trust store in place.
624            return Err(Error::CaBundle(format!(
625                "no certificates found in {}",
626                path.as_ref().display()
627            )));
628        }
629        self.custom_ca_roots = certs;
630        self.trust_store = TrustStore::Custom(self.custom_ca_roots.clone());
631        Ok(self)
632    }
633
634    /// Add CA certificates from a PEM file or certificate directory to the
635    /// configured custom trust store, replacing the default trust store if
636    /// this is the first custom source.
637    ///
638    /// Duplicate certificates are ignored. This is useful when multiple
639    /// environment-provided CA sources are combined.
640    ///
641    /// # Errors
642    ///
643    /// Returns an error if the path cannot be read or contains no PEM
644    /// certificates. Empty directories are ignored.
645    pub fn add_ca_certificate_path(mut self, path: impl AsRef<Path>) -> Result<Self> {
646        let certs = load_pem_certs_from_path(path.as_ref())?;
647        if certs.is_empty() {
648            if path.as_ref().is_dir() {
649                return Ok(self);
650            }
651            return Err(Error::CaBundle(format!(
652                "no certificates found in {}",
653                path.as_ref().display()
654            )));
655        }
656        if !matches!(&self.trust_store, TrustStore::Custom(_)) {
657            self.custom_ca_roots.clear();
658        }
659        for cert in certs {
660            if !self
661                .custom_ca_roots
662                .iter()
663                .any(|existing| existing.as_ref() == cert.as_ref())
664            {
665                self.custom_ca_roots.push(cert);
666            }
667        }
668        self.trust_store = TrustStore::Custom(self.custom_ca_roots.clone());
669        Ok(self)
670    }
671
672    /// Load additional CA certificates from a PEM file or certificate
673    /// directory. Additional roots augment the selected base trust store;
674    /// unlike [`Self::ca_certificate_path`], they do not replace it.
675    ///
676    /// Existing [`Self::add_ca_certificate_path`] behavior is intentionally
677    /// unchanged: that method continues to build a replacement custom set.
678    ///
679    /// # Errors
680    ///
681    /// Returns an error if the path cannot be read or contains malformed
682    /// certificate data. Empty directories are ignored, matching the
683    /// existing path-based CA API.
684    pub fn additional_ca_certificate_path(mut self, path: impl AsRef<Path>) -> Result<Self> {
685        let certs = load_pem_certs_from_path(path.as_ref())?;
686        if certs.is_empty() {
687            if path.as_ref().is_dir() {
688                return Ok(self);
689            }
690            return Err(Error::CaBundle(format!(
691                "no certificates found in {}",
692                path.as_ref().display()
693            )));
694        }
695        append_unique_certs(&mut self.additional_ca_roots, certs);
696        Ok(self)
697    }
698
699    /// Load CA certificates from PEM bytes, replacing any existing trust
700    /// store configuration.
701    ///
702    /// # Errors
703    ///
704    /// Returns an error if the PEM data is malformed or empty.
705    pub fn ca_certificate_pem(mut self, pem_bytes: &[u8]) -> Result<Self> {
706        let certs = parse_pem_certificates(pem_bytes)?;
707        if certs.is_empty() {
708            return Err(Error::CaBundle("no certificates found in PEM data".into()));
709        }
710        self.custom_ca_roots = certs;
711        self.trust_store = TrustStore::Custom(self.custom_ca_roots.clone());
712        Ok(self)
713    }
714
715    /// Load CA certificates from DER bytes, replacing any existing trust
716    /// store configuration.
717    ///
718    /// Each certificate is expected as raw DER-encoded X.509 data
719    /// (without PEM framing).
720    ///
721    /// # Errors
722    ///
723    /// Returns an error if no certificates are provided.
724    pub fn ca_certificate_der(mut self, der_certs: Vec<Vec<u8>>) -> Result<Self> {
725        let certs: Vec<CertificateDer<'static>> =
726            der_certs.into_iter().map(CertificateDer::from).collect();
727        if certs.is_empty() {
728            return Err(Error::CaBundle("no DER certificates provided".into()));
729        }
730        self.custom_ca_roots = certs;
731        self.trust_store = TrustStore::Custom(self.custom_ca_roots.clone());
732        Ok(self)
733    }
734
735    /// Load additional CA certificates from PEM bytes. The certificates are
736    /// added to the selected base trust store rather than replacing it.
737    ///
738    /// # Errors
739    ///
740    /// Returns an error if the PEM data is malformed or contains no
741    /// certificates.
742    pub fn additional_ca_certificate_pem(mut self, pem_bytes: &[u8]) -> Result<Self> {
743        let certs = parse_pem_certificates(pem_bytes)?;
744        if certs.is_empty() {
745            return Err(Error::CaBundle(
746                "no certificates found in additional PEM data".into(),
747            ));
748        }
749        append_unique_certs(&mut self.additional_ca_roots, certs);
750        Ok(self)
751    }
752
753    /// Load additional CA certificates from raw DER values. The certificates
754    /// are added to the selected base trust store rather than replacing it.
755    ///
756    /// # Errors
757    ///
758    /// Returns an error if no certificates are supplied.
759    pub fn additional_ca_certificate_der(mut self, der_certs: Vec<Vec<u8>>) -> Result<Self> {
760        if der_certs.is_empty() {
761            return Err(Error::CaBundle(
762                "no additional DER certificates provided".into(),
763            ));
764        }
765        append_unique_certs(
766            &mut self.additional_ca_roots,
767            der_certs.into_iter().map(CertificateDer::from),
768        );
769        Ok(self)
770    }
771
772    /// Use an explicitly supplied Rustls crypto provider for this
773    /// configuration. The provider is local to the resulting [`TlsConfig`]
774    /// and is never installed as the process-wide default.
775    #[must_use]
776    pub fn crypto_provider(mut self, provider: Arc<rustls::crypto::CryptoProvider>) -> Self {
777        self.crypto_provider = Some(provider);
778        self
779    }
780
781    /// Set the client identity for mTLS.
782    #[must_use]
783    pub fn client_identity(mut self, identity: ClientIdentity) -> Self {
784        self.client_identity = Some(identity);
785        self
786    }
787
788    /// Load a client certificate and private key from PEM files.
789    ///
790    /// # Errors
791    ///
792    /// Returns an error if the files cannot be read or the PEM data is
793    /// malformed.
794    pub fn client_cert_path(
795        self,
796        cert_path: impl AsRef<Path>,
797        key_path: impl AsRef<Path>,
798    ) -> Result<Self> {
799        let certs = load_pem_certs_from_path(cert_path.as_ref())?;
800        if certs.is_empty() {
801            return Err(Error::ClientCert(format!(
802                "no certificates found in {}",
803                cert_path.as_ref().display()
804            )));
805        }
806
807        let key_bytes = std::fs::read(key_path.as_ref()).map_err(|e| {
808            Error::PrivateKey(format!(
809                "failed to read private key {}: {e}",
810                key_path.as_ref().display()
811            ))
812        })?;
813        let (key_data, key_label) = parse_private_key(&key_bytes)?;
814
815        Ok(self.client_identity(ClientIdentity::Pem {
816            cert_chain: certs,
817            private_key_der: key_data,
818            key_label,
819        }))
820    }
821
822    /// Enable or disable hostname verification.
823    ///
824    /// When disabled, the client does not verify that the server's
825    /// certificate matches the requested hostname. This is insecure
826    /// and should only be used for testing.
827    #[must_use]
828    pub fn verify_hostname(mut self, enabled: bool) -> Self {
829        self.verify_hostname = enabled;
830        self
831    }
832
833    /// Enable or disable certificate verification.
834    ///
835    /// When disabled (`danger_accept_invalid_certs(true)`), the client
836    /// does not verify the server's certificate chain or hostname.
837    /// This is **insecure** and should only be used for testing against
838    /// known self-signed certificates.
839    #[must_use]
840    pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
841        self.verify_certificate = !accept;
842        self.verify_hostname = !accept;
843        self
844    }
845
846    /// Set the minimum TLS version.
847    #[must_use]
848    pub fn min_tls_version(mut self, version: TlsVersion) -> Self {
849        self.min_version = Some(version);
850        self
851    }
852
853    /// Set the maximum TLS version.
854    #[must_use]
855    pub fn max_tls_version(mut self, version: TlsVersion) -> Self {
856        self.max_version = Some(version);
857        self
858    }
859
860    /// Enable or disable SNI (Server Name Indication).
861    ///
862    /// Disabling SNI can break hostname verification and virtual-host
863    /// routing. It should rarely be necessary.
864    #[must_use]
865    pub fn sni(mut self, enabled: bool) -> Self {
866        self.sni_enabled = enabled;
867        self
868    }
869
870    /// Build the [`TlsConfig`].
871    ///
872    /// Each call mints a fresh opaque connection identity, even for
873    /// structurally identical policy. Unchanged `Clone`s share identity;
874    /// separate builds never pool together implicitly.
875    #[must_use]
876    pub fn build(self) -> TlsConfig {
877        TlsConfig {
878            trust_store: self.trust_store,
879            custom_ca_roots: self.custom_ca_roots,
880            additional_ca_roots: self.additional_ca_roots,
881            crypto_provider: self.crypto_provider,
882            client_identity: self.client_identity,
883            verify_hostname: self.verify_hostname,
884            verify_certificate: self.verify_certificate,
885            min_version: self.min_version,
886            max_version: self.max_version,
887            sni_enabled: self.sni_enabled,
888            root_store: Arc::new(OnceLock::new()),
889            policy_token: mint_tls_policy_token(),
890        }
891    }
892}
893
894/// A certificate verifier that accepts all certificates (unsafe).
895#[derive(Debug)]
896struct NoVerifier {
897    supported_schemes: Vec<rustls::SignatureScheme>,
898}
899
900pub(crate) fn process_crypto_provider() -> Result<Arc<rustls::crypto::CryptoProvider>> {
901    if let Some(provider) = rustls::crypto::CryptoProvider::get_default() {
902        return Ok(provider.clone());
903    }
904
905    // Explicitly install the provider implied by the selected crate features.
906    // Relying on `ClientConfig::builder()` to install the provider as a side
907    // effect is fragile: a future rustls change or a pre-installed custom
908    // provider could leave `get_default()` as `None` or mismatched.
909    #[cfg(feature = "tls-rustls")]
910    {
911        // `CryptoProvider::get_default` was None above, so no provider is
912        // installed yet. Try to install the feature-selected provider
913        // explicitly before falling back to the builder side-effect.
914        let provider = rustls::crypto::ring::default_provider();
915        let _ = provider.install_default();
916        if let Some(provider) = rustls::crypto::CryptoProvider::get_default() {
917            return Ok(provider.clone());
918        }
919    }
920    // Fallback: ask rustls to install the provider selected by its crate
921    // features, then use that same process-level provider for all custom
922    // verifiers.
923    let _ = rustls::ClientConfig::builder();
924    rustls::crypto::CryptoProvider::get_default()
925        .cloned()
926        .ok_or_else(|| Error::TlsConfig("no default TLS crypto provider".into()))
927}
928
929/// Verify a certificate chain while intentionally skipping hostname matching.
930///
931/// This preserves certificate and signature validation for callers that need
932/// to use a trusted certificate whose name is not the request hostname.
933#[derive(Debug)]
934struct NoHostnameVerifier {
935    roots: Arc<rustls::RootCertStore>,
936    delegate: Arc<rustls::client::WebPkiServerVerifier>,
937    supported_algs: rustls::crypto::WebPkiSupportedAlgorithms,
938}
939
940fn no_hostname_verifier(
941    roots: &rustls::RootCertStore,
942    provider: Arc<rustls::crypto::CryptoProvider>,
943) -> Result<Arc<dyn rustls::client::danger::ServerCertVerifier>> {
944    let roots = Arc::new(roots.clone());
945    let supported_algs = provider.signature_verification_algorithms;
946    let delegate =
947        rustls::client::WebPkiServerVerifier::builder_with_provider(roots.clone(), provider)
948            .build()
949            .map_err(|e| Error::TlsConfig(format!("failed to build certificate verifier: {e}")))?;
950    Ok(Arc::new(NoHostnameVerifier {
951        roots,
952        delegate,
953        supported_algs,
954    }))
955}
956
957impl rustls::client::danger::ServerCertVerifier for NoHostnameVerifier {
958    fn verify_server_cert(
959        &self,
960        end_entity: &CertificateDer<'_>,
961        intermediates: &[CertificateDer<'_>],
962        _server_name: &rustls::pki_types::ServerName<'_>,
963        _ocsp_response: &[u8],
964        now: rustls::pki_types::UnixTime,
965    ) -> std::result::Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
966        let cert = rustls::server::ParsedCertificate::try_from(end_entity)?;
967        rustls::client::verify_server_cert_signed_by_trust_anchor(
968            &cert,
969            &self.roots,
970            intermediates,
971            now,
972            self.supported_algs.all,
973        )?;
974        Ok(rustls::client::danger::ServerCertVerified::assertion())
975    }
976
977    fn verify_tls12_signature(
978        &self,
979        message: &[u8],
980        cert: &CertificateDer<'_>,
981        dss: &rustls::DigitallySignedStruct,
982    ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
983        self.delegate.verify_tls12_signature(message, cert, dss)
984    }
985
986    fn verify_tls13_signature(
987        &self,
988        message: &[u8],
989        cert: &CertificateDer<'_>,
990        dss: &rustls::DigitallySignedStruct,
991    ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
992        self.delegate.verify_tls13_signature(message, cert, dss)
993    }
994
995    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
996        self.delegate.supported_verify_schemes()
997    }
998}
999
1000impl rustls::client::danger::ServerCertVerifier for NoVerifier {
1001    fn verify_server_cert(
1002        &self,
1003        _end_entity: &CertificateDer<'_>,
1004        _intermediates: &[CertificateDer<'_>],
1005        _server_name: &rustls::pki_types::ServerName<'_>,
1006        _ocsp_response: &[u8],
1007        _now: rustls::pki_types::UnixTime,
1008    ) -> std::result::Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
1009        Ok(rustls::client::danger::ServerCertVerified::assertion())
1010    }
1011
1012    fn verify_tls12_signature(
1013        &self,
1014        _message: &[u8],
1015        _cert: &CertificateDer<'_>,
1016        _dss: &rustls::DigitallySignedStruct,
1017    ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
1018        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
1019    }
1020
1021    fn verify_tls13_signature(
1022        &self,
1023        _message: &[u8],
1024        _cert: &CertificateDer<'_>,
1025        _dss: &rustls::DigitallySignedStruct,
1026    ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
1027        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
1028    }
1029
1030    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
1031        self.supported_schemes.clone()
1032    }
1033}
1034
1035/// A resolver that returns a single certificate and key for mTLS.
1036struct SingleCertResolver {
1037    certified_key: Arc<rustls::sign::CertifiedKey>,
1038    key_label: String,
1039}
1040
1041impl std::fmt::Debug for SingleCertResolver {
1042    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1043        f.debug_struct("SingleCertResolver")
1044            .field("cert_count", &self.certified_key.cert.len())
1045            .field("key_label", &self.key_label)
1046            .finish_non_exhaustive()
1047    }
1048}
1049
1050impl SingleCertResolver {
1051    fn new(identity: ClientIdentity, provider: &rustls::crypto::CryptoProvider) -> Result<Self> {
1052        match identity {
1053            ClientIdentity::Pem {
1054                cert_chain,
1055                private_key_der,
1056                key_label,
1057            } => {
1058                let key_der = private_key_der_from_parts(&private_key_der, &key_label);
1059                let certified_key = rustls::sign::CertifiedKey::from_der(
1060                    cert_chain, key_der, provider,
1061                )
1062                .map_err(|e| Error::PrivateKey(format!("failed to load private key: {e}")))?;
1063                Ok(Self {
1064                    certified_key: Arc::new(certified_key),
1065                    key_label,
1066                })
1067            }
1068        }
1069    }
1070}
1071
1072impl rustls::client::ResolvesClientCert for SingleCertResolver {
1073    fn resolve(
1074        &self,
1075        _root_hint_subjects: &[&[u8]],
1076        _sigschemes: &[rustls::SignatureScheme],
1077    ) -> Option<Arc<rustls::sign::CertifiedKey>> {
1078        self.has_certs().then(|| self.certified_key.clone())
1079    }
1080
1081    fn has_certs(&self) -> bool {
1082        !self.certified_key.cert.is_empty()
1083    }
1084}
1085
1086fn private_key_der_from_parts(bytes: &[u8], label: &str) -> PrivateKeyDer<'static> {
1087    match label {
1088        "RSA PRIVATE KEY" => PrivateKeyDer::Pkcs1(rustls::pki_types::PrivatePkcs1KeyDer::from(
1089            bytes.to_owned(),
1090        )),
1091        "EC PRIVATE KEY" => {
1092            PrivateKeyDer::Sec1(rustls::pki_types::PrivateSec1KeyDer::from(bytes.to_owned()))
1093        }
1094        _ => PrivateKeyDer::Pkcs8(rustls::pki_types::PrivatePkcs8KeyDer::from(
1095            bytes.to_owned(),
1096        )),
1097    }
1098}
1099
1100fn append_unique_certs(
1101    destination: &mut Vec<CertificateDer<'static>>,
1102    certificates: impl IntoIterator<Item = CertificateDer<'static>>,
1103) {
1104    for certificate in certificates {
1105        if !destination
1106            .iter()
1107            .any(|existing| existing.as_ref() == certificate.as_ref())
1108        {
1109            destination.push(certificate);
1110        }
1111    }
1112}
1113
1114// PEM parsing utilities.
1115
1116/// Byte sequence opening a PEM section (`-----BEGIN `).
1117const PEM_BEGIN: &[u8] = b"-----BEGIN ";
1118/// Byte sequence closing a PEM section (`-----END `).
1119const PEM_END: &[u8] = b"-----END ";
1120
1121/// Load PEM-encoded certificates from a file.
1122fn load_pem_certs_from_path(path: &Path) -> Result<Vec<CertificateDer<'static>>> {
1123    if path.is_dir() {
1124        let mut entries = std::fs::read_dir(path)
1125            .map_err(|e| Error::CaBundle(format!("failed to read {}: {e}", path.display())))?
1126            .filter_map(std::result::Result::ok)
1127            .collect::<Vec<_>>();
1128        entries.sort_by_key(std::fs::DirEntry::file_name);
1129
1130        let mut certs = Vec::new();
1131        for entry in entries {
1132            if !entry.metadata().is_ok_and(|metadata| metadata.is_file()) {
1133                continue;
1134            }
1135            if let Ok(data) = std::fs::read(entry.path()) {
1136                certs.extend(parse_pem_certificates(&data)?);
1137            }
1138        }
1139        return Ok(certs);
1140    }
1141
1142    let data = std::fs::read(path)
1143        .map_err(|e| Error::CaBundle(format!("failed to read {}: {e}", path.display())))?;
1144    parse_pem_certificates(&data)
1145}
1146
1147/// Parse PEM-encoded certificate data into DER certificates.
1148///
1149/// Iterates over every `-----BEGIN`/`-----END` section in the input.
1150/// Non-PEM content between sections is skipped. Malformed or unterminated
1151/// PEM sections return an error instead of silently producing a partial trust
1152/// store. Sections other than `CERTIFICATE` (keys, etc.) are ignored.
1153fn parse_pem_certificates(pem_bytes: &[u8]) -> Result<Vec<CertificateDer<'static>>> {
1154    let mut certs = Vec::new();
1155    let mut rest = pem_bytes;
1156
1157    while let Some(pos) = find_pem_start(rest) {
1158        // Feed `decode_vec` exactly one section: it rejects input with
1159        // trailing content after the END marker, so handing it the whole
1160        // remaining bundle would fail on multi-certificate files.
1161        let section = &rest[pos..];
1162        let section_len = pem_section_len(section)
1163            .ok_or_else(|| Error::CaBundle("unterminated PEM block in certificate data".into()))?;
1164        let (label, data) = pem_rfc7468::decode_vec(&section[..section_len])
1165            .map_err(|e| Error::CaBundle(format!("invalid PEM block in certificate data: {e}")))?;
1166        if label == "CERTIFICATE" {
1167            certs.push(CertificateDer::from(data));
1168        } else {
1169            // CA bundles should contain only certificates; a key block here
1170            // likely means the user passed a private-key file as a CA path,
1171            // which would otherwise yield a confusing "no certificates found"
1172            // error. Emit a diagnostic to aid troubleshooting.
1173            #[cfg(feature = "tracing")]
1174            tracing::warn!("eggfetch: ignoring non-certificate PEM block `{label}` in CA bundle");
1175            #[cfg(not(feature = "tracing"))]
1176            let _ = &label;
1177        }
1178        rest = &section[section_len..];
1179    }
1180
1181    Ok(certs)
1182}
1183
1184/// Find the offset of the next `-----BEGIN ` marker in the input.
1185fn find_pem_start(data: &[u8]) -> Option<usize> {
1186    if data.len() < PEM_BEGIN.len() {
1187        return None;
1188    }
1189    data.windows(PEM_BEGIN.len()).position(|w| w == PEM_BEGIN)
1190}
1191
1192/// Length of the PEM section starting at the beginning of `data` (which
1193/// must start with a BEGIN marker): from that marker through the end of
1194/// the first following END-marker line.
1195///
1196/// Returns `None` when no END marker exists (truncated block). The base64
1197/// body cannot contain the `-----END ` byte sequence, so the first match
1198/// after BEGIN closes the section.
1199fn pem_section_len(data: &[u8]) -> Option<usize> {
1200    let after_begin = &data[PEM_BEGIN.len()..];
1201    let end_marker = after_begin
1202        .windows(PEM_END.len())
1203        .position(|w| w == PEM_END)?
1204        + PEM_BEGIN.len();
1205    let line_end = data[end_marker..]
1206        .iter()
1207        .position(|&b| b == b'\n')
1208        .map_or(data.len(), |p| end_marker + p + 1);
1209    Some(line_end)
1210}
1211
1212/// Parse a PEM-encoded private key, returning raw DER bytes and the PEM label.
1213///
1214/// Like [`parse_pem_certificates`], skips non-PEM sections between valid
1215/// blocks but rejects malformed or unterminated PEM sections.
1216fn parse_private_key(key_bytes: &[u8]) -> Result<(Vec<u8>, String)> {
1217    let mut rest = key_bytes;
1218
1219    while let Some(pos) = find_pem_start(rest) {
1220        let section = &rest[pos..];
1221        let section_len = pem_section_len(section).ok_or_else(|| {
1222            Error::PrivateKey("unterminated PEM block in private key data".into())
1223        })?;
1224        let (label, data) = pem_rfc7468::decode_vec(&section[..section_len]).map_err(|e| {
1225            Error::PrivateKey(format!("invalid PEM block in private key data: {e}"))
1226        })?;
1227        if matches!(label, "PRIVATE KEY" | "RSA PRIVATE KEY" | "EC PRIVATE KEY") {
1228            return Ok((data, label.to_string()));
1229        }
1230        rest = &section[section_len..];
1231    }
1232
1233    Err(Error::PrivateKey("no private key found in PEM data".into()))
1234}
1235
1236#[cfg(test)]
1237mod tests {
1238    use super::*;
1239    use proptest::prelude::*;
1240
1241    #[test]
1242    fn default_tls_config() {
1243        let config = TlsConfig::default();
1244        assert!(config.verify_hostname());
1245        assert!(config.verify_certificate());
1246        assert!(config.sni_enabled());
1247    }
1248
1249    #[test]
1250    fn explicit_provider_is_local_and_retained_by_tls_config() {
1251        let provider = Arc::new(rustls::crypto::ring::default_provider());
1252        let before = rustls::crypto::CryptoProvider::get_default().cloned();
1253        let config = TlsConfig::builder()
1254            .crypto_provider(provider.clone())
1255            .trust_store(TrustStore::WebPkiOnly)
1256            .build();
1257        assert!(config.has_explicit_crypto_provider());
1258        assert!(config.build_rustls_config().is_ok());
1259        let provider_ptr =
1260            |value: Option<&Arc<rustls::crypto::CryptoProvider>>| value.map(Arc::as_ptr);
1261        assert_eq!(
1262            provider_ptr(rustls::crypto::CryptoProvider::get_default()),
1263            provider_ptr(before.as_ref()),
1264            "explicit provider configuration must not mutate the global provider"
1265        );
1266    }
1267
1268    #[test]
1269    fn additional_ca_roots_augment_without_changing_replacement_semantics() {
1270        let mut params = rcgen::CertificateParams::default();
1271        params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
1272        let key = rcgen::KeyPair::generate().unwrap();
1273        let cert = params.self_signed(&key).unwrap();
1274        let der = cert.der().to_vec();
1275        let config = TlsConfig::builder()
1276            .trust_store(TrustStore::WebPkiOnly)
1277            .additional_ca_certificate_der(vec![der.clone(), der])
1278            .unwrap()
1279            .build();
1280        let debug = format!("{config:?}");
1281        assert!(debug.contains("additional_ca_count: 1"));
1282        assert!(config.build_rustls_config().is_ok());
1283
1284        let replacement = TlsConfig::builder()
1285            .ca_certificate_der(vec![cert.der().to_vec()])
1286            .unwrap()
1287            .build();
1288        assert!(replacement.build_rustls_config().is_ok());
1289    }
1290
1291    #[test]
1292    fn malformed_additional_ca_fails_closed() {
1293        let result = TlsConfig::builder().additional_ca_certificate_pem(b"not a certificate");
1294        assert!(result.is_err());
1295        assert_eq!(
1296            result.err().expect("error checked above").kind(),
1297            "ca_bundle"
1298        );
1299    }
1300
1301    #[test]
1302    fn builder_defaults() {
1303        let config = TlsConfig::builder().build();
1304        assert!(config.verify_hostname());
1305        assert!(config.verify_certificate());
1306        assert!(config.sni_enabled());
1307    }
1308
1309    #[test]
1310    fn builder_disable_verification() {
1311        let config = TlsConfig::builder()
1312            .danger_accept_invalid_certs(true)
1313            .build();
1314        assert!(!config.verify_hostname());
1315        assert!(!config.verify_certificate());
1316    }
1317
1318    #[test]
1319    fn config_disable_verification_preserves_other_settings() {
1320        let config = TlsConfig::builder()
1321            .sni(false)
1322            .min_tls_version(TlsVersion::Tls13)
1323            .build()
1324            .danger_accept_invalid_certs(true);
1325        assert!(!config.verify_hostname());
1326        assert!(!config.verify_certificate());
1327        assert!(!config.sni_enabled());
1328        assert_eq!(config.min_version, Some(TlsVersion::Tls13));
1329    }
1330
1331    #[test]
1332    fn builder_custom_tls_version() {
1333        let config = TlsConfig::builder()
1334            .min_tls_version(TlsVersion::Tls13)
1335            .build();
1336        assert_eq!(config.min_version, Some(TlsVersion::Tls13));
1337    }
1338
1339    #[test]
1340    fn builder_invalid_version_range() {
1341        let config = TlsConfig::builder()
1342            .min_tls_version(TlsVersion::Tls13)
1343            .max_tls_version(TlsVersion::Tls12)
1344            .build();
1345        let err = config.build_rustls_config().unwrap_err();
1346        assert_eq!(err.kind(), "tls_config");
1347    }
1348
1349    #[test]
1350    fn builder_sni_disabled() {
1351        let config = TlsConfig::builder().sni(false).build();
1352        assert!(!config.sni_enabled());
1353    }
1354
1355    #[test]
1356    fn trust_store_default() {
1357        let config = TlsConfig::builder().build();
1358        assert!(matches!(
1359            config.trust_store,
1360            TrustStore::NativeWithWebPkiFallback
1361        ));
1362    }
1363
1364    #[test]
1365    fn trust_store_custom_empty_rejected() {
1366        let result = TlsConfig::builder()
1367            .ca_certificate_pem(b"")
1368            .map(super::TlsConfigBuilder::build);
1369        assert!(result.is_err());
1370    }
1371
1372    #[test]
1373    fn add_ca_certificate_path_combines_files_and_directories() {
1374        let make_ca_pem = || {
1375            let mut params = rcgen::CertificateParams::default();
1376            params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
1377            let key = rcgen::KeyPair::generate().unwrap();
1378            params.self_signed(&key).unwrap().pem()
1379        };
1380        let first = make_ca_pem();
1381        let second = make_ca_pem();
1382        let tempdir = tempfile::tempdir().unwrap();
1383        let first_path = tempdir.path().join("first.pem");
1384        let cert_dir = tempdir.path().join("certs");
1385        std::fs::create_dir(&cert_dir).unwrap();
1386        std::fs::write(&first_path, first).unwrap();
1387        std::fs::write(cert_dir.join("second.pem"), second).unwrap();
1388
1389        let config = TlsConfig::builder()
1390            .ca_certificate_path(first_path)
1391            .unwrap()
1392            .add_ca_certificate_path(cert_dir)
1393            .unwrap()
1394            .build();
1395        assert_eq!(config.custom_ca_roots.len(), 2);
1396
1397        let empty_dir = tempdir.path().join("empty");
1398        std::fs::create_dir(&empty_dir).unwrap();
1399        let config = TlsConfig::builder()
1400            .ca_certificate_path(tempdir.path().join("first.pem"))
1401            .unwrap()
1402            .add_ca_certificate_path(empty_dir)
1403            .unwrap()
1404            .build();
1405        assert_eq!(config.custom_ca_roots.len(), 1);
1406    }
1407
1408    #[test]
1409    fn tls_version_ordering() {
1410        assert!(TlsVersion::Tls12 < TlsVersion::Tls13);
1411    }
1412
1413    #[test]
1414    fn build_rustls_config_verification() {
1415        let config = TlsConfig::builder().build();
1416        let result = config.build_rustls_config();
1417        assert!(result.is_ok());
1418    }
1419
1420    #[test]
1421    fn webpki_only_builds_without_native_roots() {
1422        let config = TlsConfig::builder()
1423            .trust_store(TrustStore::WebPkiOnly)
1424            .build();
1425        assert!(config.build_rustls_config().is_ok());
1426    }
1427
1428    #[cfg(not(feature = "tls-native-roots"))]
1429    #[test]
1430    fn native_only_reports_disabled_feature() {
1431        let config = TlsConfig::builder()
1432            .trust_store(TrustStore::NativeOnly)
1433            .build();
1434        let error = config.build_rustls_config().unwrap_err();
1435        assert!(error.to_string().contains("tls-native-roots"));
1436    }
1437
1438    #[test]
1439    fn build_rustls_config_no_verify() {
1440        let config = TlsConfig::builder()
1441            .danger_accept_invalid_certs(true)
1442            .sni(false)
1443            .build();
1444        let rustls_config = config.build_rustls_config().unwrap();
1445        assert!(!rustls_config.enable_sni);
1446    }
1447
1448    #[test]
1449    fn build_rustls_config_version_range() {
1450        let config = TlsConfig::builder()
1451            .min_tls_version(TlsVersion::Tls12)
1452            .max_tls_version(TlsVersion::Tls13)
1453            .build();
1454        let result = config.build_rustls_config();
1455        assert!(result.is_ok());
1456    }
1457
1458    #[test]
1459    fn parse_empty_pem_certificates() {
1460        let result = parse_pem_certificates(b"");
1461        assert_eq!(result.unwrap(), []);
1462    }
1463
1464    #[test]
1465    fn parse_invalid_pem_certificates() {
1466        let result = parse_pem_certificates(b"not valid pem data");
1467        assert_eq!(result.unwrap(), []);
1468    }
1469
1470    #[test]
1471    fn parse_pem_certificates_skip_garbage_between_blocks() {
1472        // A corrupted/comment section between two certificates must not
1473        // silently discard the rest of the bundle.
1474        let valid_block = |body: &[u8]| -> Vec<u8> {
1475            let mut block = b"-----BEGIN CERTIFICATE-----\n".to_vec();
1476            block.extend_from_slice(body);
1477            block.extend_from_slice(b"\n-----END CERTIFICATE-----\n");
1478            block
1479        };
1480        // Valid base64 bodies (pem_rfc7468 validates base64 content).
1481        let first = valid_block(b"AAAA");
1482        let second = valid_block(b"BBBB");
1483        let mut pem = first;
1484        pem.extend_from_slice(b"\nthis is not valid PEM \x01\x02 data\n");
1485        pem.extend_from_slice(&second);
1486
1487        let certs = parse_pem_certificates(&pem).unwrap();
1488        assert_eq!(certs.len(), 2, "both certificates must be recovered");
1489    }
1490
1491    #[test]
1492    fn parse_pem_certificates_multi_block_bundle() {
1493        // A plain concatenated bundle (the standard CA-bundle shape)
1494        // must yield every certificate.
1495        let mut pem = b"-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n".to_vec();
1496        pem.extend_from_slice(b"-----BEGIN CERTIFICATE-----\nBBBB\n-----END CERTIFICATE-----\n");
1497        pem.extend_from_slice(b"-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----\n");
1498
1499        let certs = parse_pem_certificates(&pem).unwrap();
1500        assert_eq!(certs.len(), 2, "both certificates, key section skipped");
1501    }
1502
1503    #[test]
1504    fn parse_private_key_skips_leading_garbage() {
1505        let key_block = b"-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----\n";
1506        let mut pem = b"corrupt \x03 preamble\n".to_vec();
1507        pem.extend_from_slice(key_block);
1508
1509        let (der, label) = parse_private_key(&pem).unwrap();
1510        assert_eq!(label, "PRIVATE KEY");
1511        // Base64 "AAAA" decodes to three NUL bytes.
1512        assert_eq!(der, vec![0u8, 0, 0]);
1513    }
1514
1515    #[test]
1516    fn parse_pem_certificates_rejects_corrupted_blocks() {
1517        let pem = b"-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n\
1518-----BEGIN CERTIFICATE-----\n%%%\n-----END CERTIFICATE-----\n";
1519        let err = parse_pem_certificates(pem).unwrap_err();
1520        assert_eq!(err.kind(), "ca_bundle");
1521    }
1522
1523    #[test]
1524    fn error_variants() {
1525        let err = Error::TlsConfig("test".into());
1526        assert_eq!(err.kind(), "tls_config");
1527
1528        let err = Error::CaBundle("test".into());
1529        assert_eq!(err.kind(), "ca_bundle");
1530
1531        let err = Error::ClientCert("test".into());
1532        assert_eq!(err.kind(), "client_cert");
1533
1534        let err = Error::PrivateKey("test".into());
1535        assert_eq!(err.kind(), "private_key");
1536
1537        let err = Error::CertificateVerification("test".into());
1538        assert_eq!(err.kind(), "certificate_verification");
1539
1540        let err = Error::HostnameVerification("test".into());
1541        assert_eq!(err.kind(), "hostname_verification");
1542    }
1543
1544    #[test]
1545    fn debug_impl_no_secrets() {
1546        let config = TlsConfig::builder().build();
1547        let debug = format!("{config:?}");
1548        assert!(debug.contains("verify_hostname: true"));
1549        assert!(debug.contains("verify_certificate: true"));
1550    }
1551
1552    #[cfg(all(feature = "proxy", feature = "tls-rustls"))]
1553    #[test]
1554    fn unchanged_clone_shares_connection_identity() {
1555        let base = TlsConfig::builder().build();
1556        let strict = base.clone();
1557        assert_eq!(
1558            base.connection_identity(),
1559            strict.connection_identity(),
1560            "unchanged clones must remain cache-compatible"
1561        );
1562    }
1563
1564    #[cfg(all(feature = "proxy", feature = "tls-rustls"))]
1565    #[test]
1566    fn danger_mutation_mints_new_connection_identity() {
1567        // Baseline-red regression for the proxy-TLS aliasing defect: a clone
1568        // modified with `danger_accept_invalid_certs(true)` previously shared
1569        // the root-store pointer identity with its strict parent.
1570        let base = TlsConfig::builder().build();
1571        let strict = base.clone();
1572        let weak = base.clone().danger_accept_invalid_certs(true);
1573        assert_ne!(
1574            strict.connection_identity(),
1575            weak.connection_identity(),
1576            "changed verification policy must not alias through clone ancestry"
1577        );
1578    }
1579
1580    #[cfg(all(feature = "proxy", feature = "tls-rustls"))]
1581    #[test]
1582    fn independent_builds_never_share_connection_identity() {
1583        let first = TlsConfig::builder().build();
1584        let second = TlsConfig::builder().build();
1585        assert_ne!(
1586            first.connection_identity(),
1587            second.connection_identity(),
1588            "separate builds mint fresh identity even for identical policy"
1589        );
1590    }
1591
1592    #[cfg(all(feature = "proxy", feature = "tls-rustls"))]
1593    #[test]
1594    fn connection_identity_covers_policy_dimensions() {
1595        // Each dimension builds an independent config; all must differ from
1596        // the base because every build mints a fresh opaque token. The
1597        // assertions document the connection-affecting surface, not structural
1598        // equality: false misses are acceptable, false hits are not.
1599        let base = TlsConfig::builder().build();
1600        let base_id = base.connection_identity();
1601
1602        let sni_off = TlsConfig::builder().sni(false).build();
1603        assert_ne!(base_id, sni_off.connection_identity());
1604
1605        let min_tls = TlsConfig::builder()
1606            .min_tls_version(TlsVersion::Tls13)
1607            .build();
1608        assert_ne!(base_id, min_tls.connection_identity());
1609
1610        let max_tls = TlsConfig::builder()
1611            .max_tls_version(TlsVersion::Tls12)
1612            .build();
1613        assert_ne!(base_id, max_tls.connection_identity());
1614
1615        let webpki = TlsConfig::builder()
1616            .trust_store(TrustStore::WebPkiOnly)
1617            .build();
1618        assert_ne!(base_id, webpki.connection_identity());
1619
1620        let provider = Arc::new(rustls::crypto::ring::default_provider());
1621        let explicit_provider = TlsConfig::builder()
1622            .crypto_provider(provider)
1623            .trust_store(TrustStore::WebPkiOnly)
1624            .build();
1625        assert_ne!(base_id, explicit_provider.connection_identity());
1626
1627        let custom_ca = TlsConfig::builder()
1628            .ca_certificate_der(vec![vec![0u8; 32]])
1629            .unwrap()
1630            .build();
1631        assert_ne!(base_id, custom_ca.connection_identity());
1632
1633        let additional_ca = TlsConfig::builder()
1634            .trust_store(TrustStore::WebPkiOnly)
1635            .additional_ca_certificate_der(vec![vec![1u8; 32]])
1636            .unwrap()
1637            .build();
1638        assert_ne!(base_id, additional_ca.connection_identity());
1639
1640        let identity = ClientIdentity::Pem {
1641            cert_chain: vec![],
1642            private_key_der: vec![2u8; 16],
1643            key_label: "PRIVATE KEY".to_string(),
1644        };
1645        let mtls = TlsConfig::builder().client_identity(identity).build();
1646        assert_ne!(base_id, mtls.connection_identity());
1647    }
1648
1649    #[cfg(all(feature = "proxy", feature = "tls-rustls"))]
1650    #[test]
1651    fn connection_identity_is_opaque_and_non_renderable() {
1652        let config = TlsConfig::builder().build();
1653        let id = config.connection_identity();
1654        assert_ne!(id, 0, "0 is reserved for no-TLS-config keys");
1655        let debug = format!("{config:?}");
1656        assert!(
1657            !debug.contains(&id.to_string()),
1658            "opaque token must never appear in diagnostics: {debug}"
1659        );
1660    }
1661
1662    #[test]
1663    fn client_identity_debug_no_private_key() {
1664        let identity = ClientIdentity::Pem {
1665            cert_chain: vec![],
1666            private_key_der: b"super-secret-private-key-data".to_vec(),
1667            key_label: "PRIVATE KEY".to_string(),
1668        };
1669        let debug = format!("{identity:?}");
1670        assert!(
1671            !debug.contains("super-secret"),
1672            "ClientIdentity Debug must not leak private key bytes: {debug}"
1673        );
1674        assert!(debug.contains("cert_count"));
1675        assert!(debug.contains("key_label"));
1676    }
1677
1678    proptest::proptest! {
1679        #[test]
1680        fn parse_pem_certificates_empty_input(_ in 0u64..100) {
1681            let result = parse_pem_certificates(b"");
1682            prop_assert!(result.unwrap().is_empty());
1683        }
1684
1685        #[test]
1686        fn parse_pem_certificates_garbage(input in ".{0,200}") {
1687            // Must not panic
1688            let _ = parse_pem_certificates(input.as_bytes());
1689        }
1690
1691        #[test]
1692        fn tls_config_builder_round_trip(sni in prop::bool::ANY) {
1693            let config = TlsConfig::builder()
1694                .sni(sni)
1695                .build();
1696            prop_assert_eq!(config.sni_enabled(), sni);
1697            // Defaults are always true
1698            prop_assert!(config.verify_hostname());
1699            prop_assert!(config.verify_certificate());
1700        }
1701
1702        #[test]
1703        fn build_rustls_config_valid_for_defaults(_ in 0u64..100) {
1704            let config = TlsConfig::default();
1705            let result = config.build_rustls_config();
1706            prop_assert!(result.is_ok());
1707        }
1708    }
1709}