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