Skip to main content

toolkit/bootstrap/
crypto.rs

1use std::sync::OnceLock;
2
3/// Error returned when the crypto provider cannot be installed.
4// `Clone` required by `OnceLock<Result<_>>` cache in `init_crypto_provider` --
5// the cached result is cloned on every call.
6// `PartialEq`/`Eq` used by tests asserting the cached result is stable.
7#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
8#[non_exhaustive]
9pub enum CryptoProviderError {
10    /// Application primitives cannot use the configured crypto backend.
11    #[error("application crypto initialization failed: {0}")]
12    ApplicationCryptoUnavailable(toolkit_security::crypto::CryptoError),
13    /// Another crypto provider was already installed (FIPS mode).
14    #[error("failed to install FIPS crypto provider - another provider is already installed")]
15    FipsProviderConflict,
16    /// Windows is not in FIPS mode — the system-wide Group Policy
17    /// `FipsAlgorithmPolicy` is not enabled, so CNG would not enforce the
18    /// FIPS-Approved algorithm subset at runtime. Fail-closed: refuse to
19    /// start rather than silently degrade the FIPS claim.
20    #[cfg(target_os = "windows")]
21    #[error(
22        "Windows is not in FIPS mode (HKLM\\System\\CurrentControlSet\\Control\\Lsa\\FipsAlgorithmPolicy != 1). \
23         Enable system-wide FIPS via Group Policy (Computer Configuration > Windows Settings > \
24         Security Settings > Local Policies > Security Options > 'System cryptography: Use FIPS \
25         compliant algorithms') and reboot before launching this service."
26    )]
27    SystemFipsModeNotEnabled,
28}
29
30static INIT_RESULT: OnceLock<Result<(), CryptoProviderError>> = OnceLock::new();
31
32/// Install the process-wide default rustls [`CryptoProvider`](rustls::crypto::CryptoProvider).
33///
34/// Dispatch:
35///
36/// - **`fips` feature + macOS**: installs the Apple corecrypto-backed provider
37///   from `rustls-corecrypto-provider`, **restricted to TLS 1.3 cipher
38///   suites** via `fips_provider()`. corecrypto is shipped inside macOS and
39///   validated by Apple under FIPS 140-3 per OS release; see
40///   <https://csrc.nist.gov/projects/cryptographic-module-validation-program>
41///   for the cert matching the running macOS version. TLS 1.2 cipher suites
42///   are excluded under `fips` because Apple does not expose a separately
43///   CAVS-validated TLS PRF primitive (unlike aws-lc-fips on Linux); see
44///   the `cf-gears-rustls-corecrypto-provider` README "FIPS claim boundaries"
45///   section. On macOS the `rustls/fips` feature is not activated (see
46///   `rustls-fips-shim`), so the AWS-LC FIPS dylib is not linked.
47/// - **`fips` feature + Windows**: installs the Windows CNG-backed provider
48///   from `rustls-cng-crypto`'s `fips_provider()`. CNG is shipped inside
49///   Windows and validated by Microsoft under FIPS 140-3 per OS release.
50///   Requires Windows to be in system-wide FIPS mode
51///   (`HKLM\System\CurrentControlSet\Control\Lsa\FipsAlgorithmPolicy = 1`,
52///   set via Group Policy); fails closed with
53///   [`CryptoProviderError::SystemFipsModeNotEnabled`] otherwise. As with
54///   macOS, `rustls/fips` is not activated on this target, so the AWS-LC
55///   FIPS dylib is not linked.
56/// - **`fips` feature + other** (Linux, etc.): installs the FIPS-validated
57///   AWS-LC provider (`aws-lc-fips-sys`, NIST Certificate #4816). The cert's
58///   OE covers Linux but not Darwin/Windows, which is why those targets use
59///   different providers.
60/// - **Standard mode** (no `fips` feature): installs the `aws-lc-rs` provider
61///   explicitly. This keeps the choice deterministic: the workspace enables
62///   rustls's `aws-lc-rs` feature (e.g. through `sqlx-core`'s rustls
63///   features), any dependency may also enable its `ring` feature, and rustls
64///   0.23 panics when it cannot auto-detect a single provider. Conflicts here
65///   are non-fatal: if another provider was installed first, it stays active,
66///   the conflict is logged at `warn!`, and `Ok(())` is returned.
67///
68/// This **must** be called before any TLS configuration, HTTP client, database
69/// connection, or JWT operation is created.
70///
71/// Safe to call multiple times -- only the first invocation has an effect;
72/// subsequent calls return the cached first-call result.
73///
74/// # FIPS-claim caveats
75///
76/// On the resulting provider, `provider.fips() == true` is a **runtime
77/// witness** under the witness-pattern rework — it is `true` only when both
78/// (a) every primitive routes through a CMVP-validated module *and* (b)
79/// the runtime OE check agrees. It is no longer an unconditional design-
80/// intent claim.
81///
82/// **macOS**: the corecrypto crate runs an OE check at first provider
83/// construction (`cf_gears_rustls_corecrypto_provider::oe::fips_witness_ok`).
84/// On a macOS major outside the active corecrypto CMVP cert OE, **every**
85/// `fips()` impl in the provider returns `false` and a single
86/// `tracing::warn!` is emitted. The post-install witness `assert!` then
87/// **panics** — a misconfigured FIPS build must never silently proceed.
88/// Use `CF_GEARS_FIPS_OE_OVERRIDE=1` to force the witness to `true`
89/// for CI on pre-release macOS — never for production. See the
90/// `cf-gears-rustls-corecrypto-provider` README "Runtime FIPS witness" section
91/// and FIPS PRD §8.3.
92///
93/// Downstream TLS configuration code (`toolkit_http::tls::apply_fips_hardening`)
94/// performs its own `config.fips()` check and returns `Err` rather than
95/// panicking — `ClientConfig::fips()` depends on per-config settings
96/// (`require_ems`, protocol versions) beyond the provider itself, so the
97/// TLS-layer check is a defence-in-depth complement to the bootstrap
98/// assertion here.
99///
100/// **Linux / Windows**: runtime OE-validation is not yet implemented; OE
101/// coverage is verified via the release checklist (manual CMVP cert search,
102/// PRD §9.3). Tracked as a follow-up in PRD §10.
103///
104/// # Errors
105///
106/// - [`CryptoProviderError::FipsProviderConflict`] if the `fips` feature is
107///   enabled and another rustls provider was installed first.
108/// - [`CryptoProviderError::SystemFipsModeNotEnabled`] on Windows+`fips` when
109///   the OS is not in system-wide FIPS mode.
110///
111/// # Panics
112///
113/// Panics (via `assert!`) under `--features fips` if the installed crypto
114/// provider does not report `fips() == true`. This is an intentional
115/// fail-closed guard against misconfigured builds (wrong feature flags,
116/// wrong OS, or macOS OE mismatch without the override env-var).
117pub fn init_crypto_provider() -> Result<(), CryptoProviderError> {
118    INIT_RESULT
119        .get_or_init(|| {
120            #[cfg(all(feature = "fips", target_os = "macos"))]
121            {
122                // The facade owns target selection and explicitly selects fips_provider().
123                if let Err(prev) = toolkit_security::tls::configured_provider().install_default()
124                {
125                    tracing::error!(
126                        previous_provider = ?prev,
127                        "FIPS crypto provider conflict: another rustls provider was already installed"
128                    );
129                    return Err(CryptoProviderError::FipsProviderConflict);
130                }
131                tracing::info!("FIPS-140-3 crypto provider installed (Apple corecrypto, macOS, TLS 1.3-only)");
132            }
133
134            #[cfg(all(feature = "fips", target_os = "windows"))]
135            {
136                // Fail-closed: when Windows is not in system-wide FIPS mode,
137                // `rustls_cng_crypto::fips_provider()` returns a CryptoProvider
138                // with empty `cipher_suites` / `kx_groups` (rustls's per-suite
139                // `.fips()` flag is the gate; in non-FIPS-mode Windows none
140                // qualify). The upstream crate's `fips::enabled()` helper is
141                // `pub(crate)`, so we detect the same condition via the
142                // documented empty-provider shape rather than poking
143                // `BCryptGetFipsAlgorithmMode` ourselves. Refuse to install
144                // rather than degrade the FIPS claim with a non-handshakeable
145                // provider.
146                let provider = toolkit_security::tls::configured_provider();
147                if provider.cipher_suites.is_empty() {
148                    tracing::error!(
149                        "Windows FIPS mode not enabled (FipsAlgorithmPolicy != 1); \
150                         rustls-cng-crypto returned an empty FIPS provider"
151                    );
152                    return Err(CryptoProviderError::SystemFipsModeNotEnabled);
153                }
154                if let Err(prev) = provider.install_default() {
155                    tracing::error!(
156                        previous_provider = ?prev,
157                        "FIPS crypto provider conflict: another rustls provider was already installed"
158                    );
159                    return Err(CryptoProviderError::FipsProviderConflict);
160                }
161                tracing::info!("FIPS-140-3 crypto provider installed (Windows CNG)");
162            }
163
164            #[cfg(all(feature = "fips", not(any(target_os = "macos", target_os = "windows"))))]
165            {
166                if let Err(prev) = toolkit_security::tls::configured_provider().install_default() {
167                    tracing::error!(
168                        previous_provider = ?prev,
169                        "FIPS crypto provider conflict: another rustls provider was already installed"
170                    );
171                    return Err(CryptoProviderError::FipsProviderConflict);
172                }
173                tracing::info!("FIPS-140-3 crypto provider installed (AWS-LC FIPS module)");
174            }
175
176            #[cfg(feature = "fips")]
177            {
178                let Some(provider) = rustls::crypto::CryptoProvider::get_default() else {
179                    unreachable!("provider must be installed at this point");
180                };
181                assert!(
182                    provider.fips(),
183                    "FIPS post-install witness failed: installed provider does not report fips()==true"
184                );
185                tracing::info!("FIPS post-install witness: OK");
186            }
187
188            #[cfg(not(feature = "fips"))]
189            {
190                if let Err(prev) = toolkit_security::tls::configured_provider().install_default() {
191                    // Non-fatal: another provider is already active, TLS still works.
192                    tracing::warn!(
193                        previous_provider = ?prev,
194                        "aws-lc-rs crypto provider not installed: another default provider was already set"
195                    );
196                } else {
197                    tracing::info!("aws-lc-rs crypto provider installed");
198                }
199            }
200
201            toolkit_security::crypto::initialize()
202                .map_err(CryptoProviderError::ApplicationCryptoUnavailable)?;
203            Ok(())
204        })
205        .clone()
206}