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