Skip to main content

toolkit_http/
tls.rs

1//! TLS utilities for the HTTP client.
2//!
3//! This gear provides cached loading of native root certificates to avoid
4//! repeated OS certificate store lookups (which can be slow on some platforms).
5
6use crate::config::{ClientAuthConfig, TlsConfig, TlsRootConfig, TlsVersion};
7use rustls_pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject};
8use std::sync::{Arc, OnceLock};
9
10/// Cached native root certificates.
11/// Always stores Ok; empty vec means no certs found (warned, not errored).
12static NATIVE_ROOTS_CACHE: OnceLock<Vec<CertificateDer<'static>>> = OnceLock::new();
13
14/// Counter for test verification that the loader only runs once.
15#[cfg(test)]
16static LOAD_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
17
18/// Load native root certificates from the OS certificate store.
19///
20/// This function is called once and the result is cached for subsequent calls.
21/// Returns Ok with potentially empty vec; missing certs are warned, not errored.
22fn load_native_certs_inner() -> Vec<CertificateDer<'static>> {
23    #[cfg(test)]
24    LOAD_COUNT.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25
26    let result = rustls_native_certs::load_native_certs();
27
28    // Log any errors encountered during loading
29    if !result.errors.is_empty() {
30        for err in &result.errors {
31            tracing::warn!(error = %err, "error loading native root certificate");
32        }
33    }
34
35    let certs: Vec<CertificateDer<'static>> = result.certs;
36
37    if certs.is_empty() {
38        tracing::warn!("no native root CA certificates found");
39    } else {
40        tracing::debug!(count = certs.len(), "loaded native root certificates");
41    }
42
43    certs
44}
45
46/// Get cached native root certificates.
47///
48/// Returns a reference to the cached certificates (may be empty).
49/// The certificates are loaded lazily on first call and cached for all subsequent calls.
50pub fn native_root_certs() -> &'static [CertificateDer<'static>] {
51    NATIVE_ROOTS_CACHE
52        .get_or_init(load_native_certs_inner)
53        .as_slice()
54}
55
56/// Get the crypto provider for TLS connections.
57///
58/// This function follows the reqwest pattern:
59/// 1. Check if a default provider is already installed globally
60/// 2. If yes, use that (respects user configuration)
61/// 3. If no, create a new aws-lc-rs / corecrypto / AWS-LC FIPS provider
62///    **without** installing it globally
63///
64/// This avoids global state mutation and is safe to call from multiple
65/// threads.
66///
67/// ## Two-providers caveat (non-FIPS only)
68///
69/// The fallback at step (3) does **not** call `install_default()`. If
70/// `toolkit::bootstrap::init_crypto_provider` (the canonical install
71/// site) has not yet run, every call into `get_crypto_provider()` will
72/// rebuild a provider — and `CryptoProvider::get_default()` continues
73/// to observe the absence. In practice this is benign because each
74/// build returns an `Arc` over the same gear-level statics inside
75/// the underlying provider crate (corecrypto's `default_provider()`
76/// itself caches a process-wide `Arc<CryptoProvider>`, so the
77/// "concurrent providers" are byte-identical handles), but it is **not
78/// the same** as having a global default installed: code paths that
79/// later call `get_default()` (e.g. rustls internals that re-detect)
80/// will still see `None`.
81///
82/// **The canonical entry point is `toolkit::bootstrap::init_crypto_provider`**.
83/// Callers outside the bootstrap path (probe binaries, ad-hoc tests)
84/// should invoke it first. The fallback here is a safety net for code
85/// that genuinely cannot run bootstrap, not a substitute for it.
86///
87/// Under `--features fips`, `build_client_config` bypasses this fallback
88/// entirely and instead returns [`TlsConfigError::NoCryptoProvider`] when
89/// no global provider is installed — silently constructing an uninstalled
90/// FIPS provider would mask a misconfigured bootstrap.
91// Under `--features fips`, `build_client_config` no longer routes through this
92// function — it goes straight to `CryptoProvider::get_default()` and fails
93// closed when none is installed. The function still exists for the non-FIPS
94// path; suppress the unused-function lint for the FIPS build.
95#[cfg_attr(feature = "fips", allow(dead_code))]
96pub fn get_crypto_provider() -> Arc<rustls::crypto::CryptoProvider> {
97    rustls::crypto::CryptoProvider::get_default()
98        .cloned()
99        .unwrap_or_else(|| {
100            let provider = toolkit_security::tls::configured_provider();
101            #[cfg(all(feature = "fips", target_os = "windows"))]
102            assert!(
103                !provider.cipher_suites.is_empty(),
104                "Windows is not in FIPS mode (FipsAlgorithmPolicy != 1). \
105                 Enable system-wide FIPS via Group Policy and reboot."
106            );
107            Arc::new(provider)
108        })
109}
110
111/// Error type returned by the fallible TLS-config builders in this gear.
112///
113/// The `Other` variant carries a boxed `dyn Error` so the source-error chain
114/// from rustls (and any future foreign error) is preserved end-to-end —
115/// downstream `HttpError::Tls(_)` wraps this and reports a proper `.source()`.
116#[derive(Debug, thiserror::Error)]
117#[non_exhaustive]
118pub enum TlsConfigError {
119    /// `rustls::crypto::CryptoProvider::get_default()` returned `None` when a
120    /// FIPS-mode TLS config was requested. Under `--features fips` the
121    /// crypto provider must be installed up-front via
122    /// `toolkit::bootstrap::init_crypto_provider`; falling back to an
123    /// uninstalled provider here would silently bypass the canonical
124    /// install path and yield a config whose FIPS-validation status is
125    /// indeterminate.
126    #[error(
127        "rustls CryptoProvider has not been installed; call \
128         toolkit::bootstrap::init_crypto_provider() before building any TLS \
129         config under --features fips"
130    )]
131    NoCryptoProvider,
132
133    /// `apply_fips_hardening` rejected the freshly-built `ClientConfig`
134    /// because `ClientConfig::fips()` reported `false`. Carries the
135    /// human-readable diagnostic. Under normal bootstrap flow the
136    /// provider-level witness is already asserted by
137    /// `init_crypto_provider`; this error surfaces per-config issues
138    /// (e.g. missing `require_ems`) or a missed `init_crypto_provider()`
139    /// call.
140    #[error("{0}")]
141    FipsHardeningFailed(String),
142
143    /// Catch-all for foreign errors (`rustls::Error`, etc.) propagated
144    /// via `?`. Marked `#[error(transparent)]` so the `Display` and
145    /// `source()` impls forward to the inner error unchanged.
146    #[error(transparent)]
147    Other(#[from] Box<dyn std::error::Error + Send + Sync + 'static>),
148}
149
150/// Test-only auto-install of the platform-appropriate FIPS crypto provider.
151///
152/// Gated on `cfg(all(test, feature = "fips"))` — `cfg(test)` is only set when
153/// compiling the crate's own unit-test target, NOT when compiling the lib for
154/// use by integration tests under `tests/`. The regression test in
155/// `tests/no_crypto_provider_fips.rs` therefore sees a clean process state and
156/// can still assert `TlsConfigError::NoCryptoProvider`.
157///
158/// Forced from inside `build_client_config` so every TLS-config-building
159/// entry point (`webpki_roots_client_config`, `native_roots_client_config`,
160/// and `HttpClientBuilder::build`) auto-installs uniformly. nextest's default
161/// "process-per-test" execution means a builder-level `LazyLock` would not
162/// cover tests that bypass the builder.
163#[cfg(all(test, feature = "fips"))]
164mod fips_test_provider {
165    use std::sync::LazyLock;
166
167    pub(super) static INSTALL: LazyLock<()> = LazyLock::new(|| {
168        // `install_default()` returns `Err` if a provider is already installed
169        // (benign here); drop the result. `drop` rather than `let _ =`
170        // satisfies clippy::let_underscore_must_use.
171        drop(toolkit_security::tls::configured_provider().install_default());
172    });
173}
174
175/// Build a rustls `ClientConfig` from the given root store and [`TlsConfig`].
176///
177/// `tls.min_version` selects the advertised protocol versions (see
178/// [`protocol_versions`]) and `tls.client_auth`, when set, installs a
179/// mutual-TLS client certificate (see [`load_client_auth`]).
180///
181/// Under the `fips` feature, applies [`apply_fips_hardening`] which:
182///   1. forces `require_ems = true` (NIST SP 800-52 Rev. 2 §3.5), and
183///   2. verifies `config.fips() == true` and returns `Err` otherwise.
184///
185/// The bootstrap `assert!` in `init_crypto_provider` is the primary
186/// guard against a non-FIPS provider; this TLS-layer check is
187/// defence-in-depth for per-config settings (`require_ems`, protocol
188/// versions) that also affect `ClientConfig::fips()`.
189fn build_client_config(
190    root_store: rustls::RootCertStore,
191    tls: &TlsConfig,
192) -> Result<rustls::ClientConfig, TlsConfigError> {
193    // Test-only: ensure the platform-appropriate FIPS crypto provider is
194    // installed before this funnel runs. The fail-closed path below requires
195    // `toolkit::bootstrap::init_crypto_provider` to have run in production;
196    // in-crate tests that don't go through bootstrap (most of them) would
197    // otherwise hit `NoCryptoProvider`. Placed here rather than in the
198    // builder so it covers every TLS-config-building entry point uniformly
199    // (`webpki_roots_client_config`, `native_roots_client_config`, and any
200    // future addition). `cfg(test)` is set only for in-crate unit tests, NOT
201    // for integration tests under `tests/` — so
202    // `tests/no_crypto_provider_fips.rs` still sees a clean process state.
203    #[cfg(all(test, feature = "fips"))]
204    std::sync::LazyLock::force(&fips_test_provider::INSTALL);
205
206    // Under `--features fips` the crypto provider MUST have been installed
207    // up-front via `toolkit::bootstrap::init_crypto_provider` — otherwise
208    // `get_crypto_provider()`'s fallback would mint an *uninstalled* provider
209    // whose FIPS-validation status is indeterminate from the rustls global's
210    // point of view. Fail closed instead.
211    //
212    // The non-FIPS branch preserves the historical infallible fallback
213    // (see `get_crypto_provider` docstring).
214    #[cfg(feature = "fips")]
215    let provider = rustls::crypto::CryptoProvider::get_default()
216        .cloned()
217        .ok_or(TlsConfigError::NoCryptoProvider)?;
218    #[cfg(not(feature = "fips"))]
219    let provider = get_crypto_provider();
220
221    let roots_builder = rustls::ClientConfig::builder_with_provider(provider)
222        .with_protocol_versions(protocol_versions(tls.min_version))
223        .map_err(|e| TlsConfigError::Other(Box::new(e)))?
224        .with_root_certificates(root_store);
225
226    // Plumb optional mutual-TLS client identity. PEM material is read and
227    // parsed here (not at config-construction time) so IO/parse failures
228    // surface as a recoverable `TlsConfigError` at client-build time.
229    #[allow(unused_mut)]
230    let mut config = match &tls.client_auth {
231        Some(auth) => {
232            let (cert_chain, key) = load_client_auth(auth)?;
233            roots_builder
234                .with_client_auth_cert(cert_chain, key)
235                .map_err(|e| TlsConfigError::Other(Box::new(e)))?
236        }
237        None => roots_builder.with_no_client_auth(),
238    };
239
240    #[cfg(feature = "fips")]
241    {
242        apply_fips_hardening(&mut config)?;
243    }
244
245    Ok(config)
246}
247
248/// Map a [`TlsVersion`] floor onto the rustls protocol-version slice.
249///
250/// `Tls12` advertises both TLS 1.2 and TLS 1.3 (equivalent to the previous
251/// `with_safe_default_protocol_versions()`); `Tls13` advertises TLS 1.3 only.
252/// The returned slices are `const` items and therefore inherently `'static` —
253/// every element is a reference to a `rustls::version::*` static.
254fn protocol_versions(min: TlsVersion) -> &'static [&'static rustls::SupportedProtocolVersion] {
255    const TLS12_AND_13: &[&rustls::SupportedProtocolVersion] =
256        &[&rustls::version::TLS13, &rustls::version::TLS12];
257    const TLS13_ONLY: &[&rustls::SupportedProtocolVersion] = &[&rustls::version::TLS13];
258    match min {
259        TlsVersion::Tls12 => TLS12_AND_13,
260        TlsVersion::Tls13 => TLS13_ONLY,
261    }
262}
263
264/// Load a PEM-encoded client certificate chain and private key for mutual TLS.
265///
266/// Reads both files referenced by [`ClientAuthConfig`], returning a
267/// [`TlsConfigError::Other`] (boxed, with path context) on any IO or parse
268/// failure or when the certificate chain is empty.
269fn load_client_auth(
270    auth: &ClientAuthConfig,
271) -> Result<(Vec<CertificateDer<'static>>, PrivateKeyDer<'static>), TlsConfigError> {
272    // `pem_file_iter` reports file-open errors eagerly and per-section parse
273    // errors lazily from the iterator; map both to the same path-context error.
274    let cert_err = |e: rustls_pki_types::pem::Error| {
275        TlsConfigError::Other(
276            format!(
277                "failed to load client certificate chain from {}: {e}",
278                auth.cert_chain.display()
279            )
280            .into(),
281        )
282    };
283    let cert_chain: Vec<CertificateDer<'static>> = CertificateDer::pem_file_iter(&auth.cert_chain)
284        .map_err(cert_err)?
285        .collect::<Result<Vec<_>, _>>()
286        .map_err(cert_err)?;
287
288    if cert_chain.is_empty() {
289        return Err(TlsConfigError::Other(
290            format!(
291                "client certificate chain at {} contained no certificates",
292                auth.cert_chain.display()
293            )
294            .into(),
295        ));
296    }
297
298    // Deliberately do NOT interpolate the underlying parse error here: it is
299    // produced from private-key bytes and must never reach logs. The path is
300    // safe to include and is sufficient to diagnose IO/format problems.
301    let key = PrivateKeyDer::from_pem_file(&auth.key).map_err(|_| {
302        TlsConfigError::Other(
303            format!(
304                "failed to load client private key from {} (IO or PEM parse error)",
305                auth.key.display()
306            )
307            .into(),
308        )
309    })?;
310
311    Ok((cert_chain, key))
312}
313
314/// Apply FIPS-mode hardening to a freshly-built `ClientConfig`:
315///   * set `require_ems = true` (NIST SP 800-52 Rev. 2 §3.5 — required for
316///     `ClientConfig::fips()` to consider TLS 1.2 sessions FIPS-compliant
317///     when the EMS extension is honoured by the peer).
318///   * verify the full FIPS chain reports `fips() == true`. If not, return
319///     `Err` — the bootstrap `assert!` in `init_crypto_provider` already
320///     guarantees the provider reports `fips() == true`, so a failure here
321///     indicates a per-config issue (e.g. missing `require_ems` or
322///     restricted protocol versions) rather than a provider-level problem.
323#[cfg(feature = "fips")]
324fn apply_fips_hardening(cfg: &mut rustls::ClientConfig) -> Result<(), TlsConfigError> {
325    cfg.require_ems = true;
326    if !cfg.fips() {
327        return Err(TlsConfigError::FipsHardeningFailed(
328            "TLS ClientConfig does not advertise FIPS after enabling require_ems. \
329             The bootstrap assert in init_crypto_provider should have caught a \
330             non-FIPS provider at startup; if you see this error the provider is \
331             FIPS-OK but a per-config setting (protocol versions, require_ems) is \
332             preventing ClientConfig::fips() from reporting true. \
333             If init_crypto_provider was not called, call it before building any \
334             TLS config."
335                .to_owned(),
336        ));
337    }
338    Ok(())
339}
340
341/// Build a rustls `ClientConfig` using the cached native root certificates.
342///
343/// # Errors
344///
345/// Returns an error if no valid root certificates are available:
346/// - OS certificate store is empty
347/// - All certificates failed to parse
348///
349/// This fail-fast behavior ensures TLS configuration errors are caught at client
350/// construction time rather than failing later during TLS handshakes.
351pub fn native_roots_client_config(tls: &TlsConfig) -> Result<rustls::ClientConfig, TlsConfigError> {
352    build_client_config(native_root_store()?, tls)
353}
354
355fn native_root_store() -> Result<rustls::RootCertStore, TlsConfigError> {
356    root_store_from_native(native_root_certs())
357}
358
359fn root_store_from_native(
360    certs: &[CertificateDer<'static>],
361) -> Result<rustls::RootCertStore, TlsConfigError> {
362    let mut root_store = rustls::RootCertStore::empty();
363
364    if certs.is_empty() {
365        return Err(TlsConfigError::Other(
366            "no native root CA certificates found in OS certificate store".into(),
367        ));
368    }
369
370    let (added, ignored) = root_store.add_parsable_certificates(certs.iter().cloned());
371
372    if ignored > 0 {
373        tracing::warn!(
374            added = added,
375            ignored = ignored,
376            "some native root certificates could not be parsed"
377        );
378    }
379
380    if added == 0 {
381        return Err(TlsConfigError::Other(
382            format!(
383                "no valid native root CA certificates parsed (found {}, all {} failed to parse)",
384                certs.len(),
385                ignored
386            )
387            .into(),
388        ));
389    }
390
391    Ok(root_store)
392}
393
394fn webpki_root_store() -> rustls::RootCertStore {
395    let mut root_store = rustls::RootCertStore::empty();
396    root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
397    root_store
398}
399
400/// Build a rustls `ClientConfig` using Mozilla's webpki-roots trust anchors.
401///
402/// Under the `fips` feature, `require_ems` is forced on (see
403/// [`build_client_config`]). This is the FIPS-conformant counterpart to the
404/// `hyper_rustls::HttpsConnectorBuilder::with_provider_and_webpki_roots`
405/// one-liner — we must build the config ourselves so we can flip the EMS bit.
406///
407/// # Errors
408///
409/// See [`custom_roots_client_config`].
410pub fn webpki_roots_client_config(tls: &TlsConfig) -> Result<rustls::ClientConfig, TlsConfigError> {
411    build_client_config(webpki_root_store(), tls)
412}
413
414/// Build a rustls `ClientConfig` trusting exactly `root_store` (e.g. a
415/// private CA for internal upstreams).
416///
417/// Same provider selection and FIPS hardening as the other builders.
418///
419/// # Errors
420///
421/// [`TlsConfigError::NoCryptoProvider`] under `fips` when no provider was
422/// installed, [`TlsConfigError::FipsHardeningFailed`] when the config does
423/// not report FIPS mode, or [`TlsConfigError::Other`] for an invalid
424/// protocol-version or client-certificate setup.
425pub fn custom_roots_client_config(
426    root_store: rustls::RootCertStore,
427    tls: &TlsConfig,
428) -> Result<rustls::ClientConfig, TlsConfigError> {
429    build_client_config(root_store, tls)
430}
431
432/// Parse every `CERTIFICATE` block of a PEM bundle; other PEM sections are
433/// skipped.
434///
435/// # Errors
436///
437/// [`TlsConfigError::Other`] when the PEM is malformed or holds no
438/// certificate.
439pub fn load_pem_bundle(pem: &[u8]) -> Result<Vec<CertificateDer<'static>>, TlsConfigError> {
440    let certs = CertificateDer::pem_slice_iter(pem)
441        .collect::<Result<Vec<_>, _>>()
442        .map_err(|e| with_context("invalid PEM certificate bundle", e))?;
443    if certs.is_empty() {
444        return Err(TlsConfigError::Other(
445            "PEM certificate bundle contains no certificates".into(),
446        ));
447    }
448    Ok(certs)
449}
450
451/// The root store for `roots` plus `extra` trust anchors.
452///
453/// # Errors
454///
455/// [`TlsConfigError::Other`] for an invalid extra root, or for an OS store
456/// with no usable certificate when there are no extra roots.
457pub fn root_store_with_extra(
458    roots: TlsRootConfig,
459    extra: &[CertificateDer<'static>],
460) -> Result<rustls::RootCertStore, TlsConfigError> {
461    root_store_from_parts(roots, native_root_certs, extra)
462}
463
464/// Unlike the OS store, where unparsable entries are skipped, a bad extra
465/// certificate is an error: it was configured explicitly.
466///
467/// An OS store with no usable certificate is an error only without extra
468/// roots; with them, the extra roots alone are trusted.
469fn root_store_from_parts(
470    roots: TlsRootConfig,
471    native: fn() -> &'static [CertificateDer<'static>],
472    extra: &[CertificateDer<'static>],
473) -> Result<rustls::RootCertStore, TlsConfigError> {
474    let mut root_store = match roots {
475        TlsRootConfig::WebPki => webpki_root_store(),
476        TlsRootConfig::Native if extra.is_empty() => root_store_from_native(native())?,
477        TlsRootConfig::Native => root_store_from_native(native()).unwrap_or_else(|e| {
478            tracing::warn!(error = %e, "OS root store unusable; trusting only the extra roots");
479            rustls::RootCertStore::empty()
480        }),
481    };
482    for (index, cert) in extra.iter().enumerate() {
483        root_store
484            .add(cert.clone())
485            .map_err(|e| with_context(format!("invalid extra root certificate #{index}"), e))?;
486    }
487    Ok(root_store)
488}
489
490/// An error message with the underlying error kept as `source()`.
491#[derive(Debug, thiserror::Error)]
492#[error("{context}: {source}")]
493struct Context {
494    context: String,
495    source: Box<dyn std::error::Error + Send + Sync>,
496}
497
498fn with_context(
499    context: impl Into<String>,
500    source: impl std::error::Error + Send + Sync + 'static,
501) -> TlsConfigError {
502    TlsConfigError::Other(Box::new(Context {
503        context: context.into(),
504        source: Box::new(source),
505    }))
506}
507
508#[cfg(test)]
509#[cfg_attr(coverage_nightly, coverage(off))]
510mod tests {
511    use super::*;
512    use std::sync::atomic::Ordering;
513
514    fn test_ca() -> rcgen::Certificate {
515        let key = rcgen::KeyPair::generate().expect("key pair");
516        let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).expect("params");
517        params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
518        params.self_signed(&key).expect("self-signed CA")
519    }
520
521    #[test]
522    fn extra_roots_are_added_to_webpki_store() {
523        let store =
524            root_store_with_extra(TlsRootConfig::WebPki, &[test_ca().der().clone()]).unwrap();
525        assert_eq!(store.len(), webpki_roots::TLS_SERVER_ROOTS.len() + 1);
526    }
527
528    #[test]
529    fn extra_roots_stand_in_for_an_empty_os_store() {
530        let store =
531            root_store_from_parts(TlsRootConfig::Native, || &[], &[test_ca().der().clone()])
532                .unwrap();
533        assert_eq!(store.len(), 1);
534    }
535
536    #[test]
537    fn empty_os_store_without_extra_roots_is_rejected() {
538        assert!(root_store_from_parts(TlsRootConfig::Native, || &[], &[]).is_err());
539    }
540
541    #[test]
542    fn invalid_extra_root_is_rejected_with_an_empty_os_store() {
543        let garbage = CertificateDer::from(vec![0u8; 8]);
544        assert!(root_store_from_parts(TlsRootConfig::Native, || &[], &[garbage]).is_err());
545    }
546
547    #[test]
548    fn invalid_extra_root_is_rejected() {
549        let garbage = CertificateDer::from(vec![0x30, 0x03, 0x02, 0x01, 0x00]);
550        assert!(root_store_with_extra(TlsRootConfig::WebPki, &[garbage]).is_err());
551    }
552
553    #[test]
554    fn pem_bundle_keeps_every_certificate_and_skips_other_sections() {
555        let key = rcgen::KeyPair::generate().expect("key pair");
556        let pem = format!(
557            "{}{}{}",
558            test_ca().pem(),
559            key.serialize_pem(),
560            test_ca().pem()
561        );
562        assert_eq!(load_pem_bundle(pem.as_bytes()).unwrap().len(), 2);
563    }
564
565    #[test]
566    fn pem_bundle_without_certificates_is_rejected() {
567        let key = rcgen::KeyPair::generate().expect("key pair");
568        assert!(load_pem_bundle(key.serialize_pem().as_bytes()).is_err());
569        assert!(load_pem_bundle(b"").is_err());
570    }
571
572    /// Test that native root certs are cached after the first load.
573    ///
574    /// NOTE: This test verifies "at most one load" rather than "exactly one load"
575    /// because `LOAD_COUNT` is a global atomic shared across all tests. If another
576    /// test (or parallel test) calls `native_root_certs()` before this test runs,
577    /// the cache will already be initialized and `final_count - initial_count`
578    /// will be 0. The assertion handles this correctly.
579    #[test]
580    fn test_native_roots_cached() {
581        // Capture count before our calls (may be non-zero if cache already initialized)
582        let initial_count = LOAD_COUNT.load(Ordering::SeqCst);
583
584        // First call - loads if not cached, otherwise uses existing cache
585        let result1 = native_root_certs();
586
587        // Second call should use cache
588        let result2 = native_root_certs();
589
590        // Third call should also use cache
591        let result3 = native_root_certs();
592
593        // Verify loader was called at most once more than initial (0 if already cached, 1 if we triggered the load)
594        let final_count = LOAD_COUNT.load(Ordering::SeqCst);
595        assert!(
596            final_count <= initial_count + 1,
597            "loader should run at most once, but ran {} times since test start",
598            final_count - initial_count
599        );
600
601        // Results should be consistent (same slice pointer)
602        assert_eq!(result1.len(), result2.len());
603        assert_eq!(result2.len(), result3.len());
604        assert!(std::ptr::eq(result1, result2), "should return same slice");
605        assert!(std::ptr::eq(result2, result3), "should return same slice");
606    }
607
608    #[test]
609    fn test_native_roots_client_config() {
610        // Building client config succeeds if native roots are available
611        // (which they should be on most CI/dev systems)
612        // On systems without native certs, this returns Err (expected behavior)
613        let result = native_roots_client_config(&TlsConfig::default());
614
615        // Log the result for debugging in CI
616        match &result {
617            Ok(_) => tracing::debug!("native_roots_client_config succeeded"),
618            Err(e) => {
619                tracing::debug!(error = %e, "native_roots_client_config failed (expected on minimal containers)");
620            }
621        }
622
623        // We don't assert success because CI containers may not have OS certs.
624        // The important thing is it doesn't panic.
625    }
626
627    /// `webpki_roots_client_config()` must always build successfully — the
628    /// trust store comes from a static `webpki-roots::TLS_SERVER_ROOTS` slice
629    /// that is non-empty on every supported platform. Catches a silent
630    /// regression if the `webpki-roots` crate ever renames its constant or
631    /// changes its `extend`-able item type.
632    ///
633    /// Asserts behavioural properties this crate actually controls:
634    ///   1. The config carries the crypto provider returned by
635    ///      `get_crypto_provider()` (non-empty cipher-suite list).
636    ///   2. The provider's cipher-suite set is non-empty — proves we did
637    ///      not accidentally build a config whose negotiation would fail
638    ///      with `NoCipherSuitesInCommon` against every peer.
639    ///   3. The provider's kx-group list is non-empty — same reasoning.
640    ///
641    /// (Asserting `alpn_protocols.len() == 0` was a rustls default we do
642    /// not control; replaced.)
643    #[test]
644    fn test_webpki_roots_client_config_builds() {
645        let cfg = webpki_roots_client_config(&TlsConfig::default())
646            .expect("webpki roots must always build");
647        let provider = cfg.crypto_provider();
648        assert!(
649            !provider.cipher_suites.is_empty(),
650            "TLS client config must carry a non-empty cipher-suite list"
651        );
652        assert!(
653            !provider.kx_groups.is_empty(),
654            "TLS client config must carry a non-empty kx-group list"
655        );
656    }
657
658    /// When built with `--features fips`, `build_client_config` MUST:
659    ///   1. Set `require_ems = true` (NIST SP 800-52 Rev. 2 §3.5)
660    ///   2. Make `config.fips()` return true (full FIPS chain)
661    ///
662    /// Without this, an Apple-corecrypto-backed FIPS build silently advertises
663    /// `config.fips() == false` because rustls's stock `require_ems` default
664    /// is gated on rustls's *own* `fips` feature — which we deliberately keep
665    /// off on macOS to avoid pulling the AWS-LC FIPS gear.
666    ///
667    /// Exercised via the public `webpki_roots_client_config()` (which routes
668    /// through `build_client_config`); calling it avoids a hard dependency on
669    /// the OS keychain that `native_roots_client_config` carries.
670    ///
671    /// Run via `cargo test -p cf-gears-toolkit-http --features fips`.
672    /// `build_client_config` auto-installs the platform FIPS provider in
673    /// test mode (see `fips_test_provider` gear) so this test does not
674    /// need its own explicit install.
675    #[test]
676    #[cfg(feature = "fips")]
677    fn fips_client_config_requires_ems_and_advertises_fips() {
678        let cfg = webpki_roots_client_config(&TlsConfig::default()).expect("build under fips");
679        assert!(cfg.require_ems, "fips build must set require_ems = true");
680        assert!(
681            cfg.fips(),
682            "fips build must yield ClientConfig::fips() == true (full provider chain)"
683        );
684    }
685
686    /// `protocol_versions` maps the `min_version` knob onto the rustls
687    /// protocol-version slice: `Tls12` advertises both 1.2 and 1.3 (the
688    /// previous `with_safe_default_protocol_versions()` behaviour) and `Tls13`
689    /// advertises 1.3 only.
690    #[test]
691    fn protocol_versions_maps_min_version() {
692        let v12 = protocol_versions(TlsVersion::Tls12);
693        assert_eq!(v12.len(), 2, "Tls12 floor must advertise TLS 1.2 and 1.3");
694        assert!(
695            v12.iter()
696                .any(|v| v.version == rustls::ProtocolVersion::TLSv1_2)
697        );
698        assert!(
699            v12.iter()
700                .any(|v| v.version == rustls::ProtocolVersion::TLSv1_3)
701        );
702
703        let v13 = protocol_versions(TlsVersion::Tls13);
704        assert_eq!(v13.len(), 1, "Tls13 floor must advertise TLS 1.3 only");
705        assert_eq!(v13[0].version, rustls::ProtocolVersion::TLSv1_3);
706    }
707
708    /// A `min_version: Tls13` config still builds a valid `ClientConfig`
709    /// through the public webpki entry point.
710    #[test]
711    fn webpki_client_config_builds_with_tls13_floor() {
712        let tls = TlsConfig {
713            min_version: TlsVersion::Tls13,
714            ..TlsConfig::default()
715        };
716        let cfg = webpki_roots_client_config(&tls).expect("tls 1.3 floor must build");
717        assert!(!cfg.crypto_provider().cipher_suites.is_empty());
718    }
719
720    /// A `client_auth` pointing at non-existent PEM files must fail closed at
721    /// build time with a `TlsConfigError` whose message names the missing path
722    /// — not panic, and not silently fall back to no-client-auth.
723    #[test]
724    fn client_auth_missing_files_errors() {
725        let tls = TlsConfig {
726            client_auth: Some(ClientAuthConfig::new(
727                "/nonexistent/toolkit-http/cert.pem",
728                "/nonexistent/toolkit-http/key.pem",
729            )),
730            ..TlsConfig::default()
731        };
732        let err =
733            webpki_roots_client_config(&tls).expect_err("missing client-auth files must error");
734        let msg = err.to_string();
735        assert!(
736            msg.contains("client certificate chain") && msg.contains("cert.pem"),
737            "error should name the missing cert path, got: {msg}"
738        );
739    }
740
741    /// Generate a self-signed ECDSA P-256 / SHA-256 identity and write it to a
742    /// fresh temp directory as PEM. Returns the [`tempfile::TempDir`] (which the
743    /// caller must keep alive — dropping it removes the files, even on panic)
744    /// and a [`ClientAuthConfig`] pointing at the written cert-chain and key.
745    ///
746    /// ECDSA P-256 / SHA-256 is an explicitly FIPS-approved signature class, so
747    /// the same identity drives both the non-FIPS and FIPS code paths.
748    fn write_self_signed_identity() -> (tempfile::TempDir, ClientAuthConfig) {
749        use std::io::Write;
750
751        let key_pair = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)
752            .expect("generate ECDSA P-256 key pair");
753        let cert = rcgen::CertificateParams::new(vec!["client.test".to_owned()])
754            .expect("certificate params")
755            .self_signed(&key_pair)
756            .expect("self-sign certificate");
757
758        let dir = tempfile::tempdir().expect("create temp dir");
759        let cert_path = dir.path().join("client_cert.pem");
760        let key_path = dir.path().join("client_key.pem");
761
762        std::fs::File::create(&cert_path)
763            .and_then(|mut f| f.write_all(cert.pem().as_bytes()))
764            .expect("write cert pem");
765        std::fs::File::create(&key_path)
766            .and_then(|mut f| f.write_all(key_pair.serialize_pem().as_bytes()))
767            .expect("write key pem");
768
769        (dir, ClientAuthConfig::new(cert_path, key_path))
770    }
771
772    /// Happy-path mutual TLS: a freshly generated self-signed cert + key load
773    /// from PEM files and produce a `ClientConfig` carrying a client-auth
774    /// resolver. Gated off under `fips`; the FIPS path is pinned separately by
775    /// `client_auth_under_fips_fails_closed`.
776    #[test]
777    #[cfg(not(feature = "fips"))]
778    fn client_auth_pem_round_trips() {
779        // `_dir` keeps the temp directory (and its PEM files) alive for the
780        // duration of the test; it is removed on drop, even if an assert panics.
781        let (_dir, client_auth) = write_self_signed_identity();
782        let tls = TlsConfig {
783            client_auth: Some(client_auth),
784            ..TlsConfig::default()
785        };
786
787        let result = webpki_roots_client_config(&tls);
788        assert!(
789            result.is_ok(),
790            "client-auth config from valid PEM must build: {:?}",
791            result.err()
792        );
793    }
794
795    /// Mutual TLS under `--features fips` must fail *closed*, never panic. Both
796    /// outcomes below are FIPS-correct and which one occurs is provider-
797    /// dependent (macOS corecrypto / Windows CNG / Linux AWS-LC):
798    ///   * `Ok(cfg)` with `cfg.fips() == true` — the active provider witnessed
799    ///     the ECDSA P-256 client-auth signer as FIPS-approved; or
800    ///   * `Err(TlsConfigError::FipsHardeningFailed(_))` — `apply_fips_hardening`
801    ///     rejected a config it could not prove `ClientConfig::fips()` for.
802    ///
803    /// Any other result (panic, a different error variant, or `Ok` with
804    /// `fips() == false`) is a regression in the FIPS mTLS path.
805    #[test]
806    #[cfg(feature = "fips")]
807    fn client_auth_under_fips_fails_closed() {
808        let (_dir, client_auth) = write_self_signed_identity();
809        let tls = TlsConfig {
810            client_auth: Some(client_auth),
811            ..TlsConfig::default()
812        };
813
814        match webpki_roots_client_config(&tls) {
815            Ok(cfg) => assert!(
816                cfg.fips(),
817                "fips build returned Ok but ClientConfig::fips() == false: \
818                 an mTLS config slipped past the FIPS witness"
819            ),
820            // Acceptable: failed closed because fips() could not be proven.
821            Err(TlsConfigError::FipsHardeningFailed(_)) => {}
822            Err(other) => {
823                panic!("unexpected non-fail-closed error on fips mTLS path: {other}")
824            }
825        }
826    }
827}