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