rustls-extra-roots 0.1.0

Trust the built-in Mozilla roots plus an additional PEM bundle named by an environment variable — additive, not replacing, and fatal when the bundle cannot be used.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
//! The built-in Mozilla roots, plus a corporate CA bundle the environment
//! names.
//!
//! A program that makes outbound TLS connections from inside a corporate
//! network usually needs two things trusted at once: the public certificate
//! authorities, and whichever internal CA the network's inspecting proxy
//! presents. This crate is the twenty lines that combine them, plus the
//! three rules that turn out to matter.
//!
//! # Three rules worth knowing first
//!
//! **The bundle is additional, not a replacement.** The variable is spelled
//! `SSL_CERT_FILE` by default, and OpenSSL gives that name the opposite
//! meaning: setting it there *replaces* the default trust store. Here it
//! **adds** to it, because a corporate CA is issued alongside the public
//! ones rather than instead of them. If that is not the meaning you want,
//! name a different variable — see [`ExtraRoots::from_variable`] — but be
//! deliberate about it. A deployment that set `SSL_CERT_FILE` expecting
//! OpenSSL's meaning gets a *larger* trust set than it intended, never a
//! smaller one: the safe direction to be wrong in, but still worth knowing.
//!
//! **A configured bundle that cannot be used is fatal.** Not a warning.
//! Silently falling back to the default roots is how a certificate problem
//! becomes a TLS handshake failure three hops away, in a different service,
//! hours later. If the operator said to load a file, and the file cannot be
//! loaded, [`validate_at_startup`] says so and the process should not
//! start. Every error names the file, because "invalid certificate" with no
//! path is the least useful message a deployment can fail with.
//!
//! **Blank is absent.** `SSL_CERT_FILE=""` means the variable was not set.
//! A templated container definition whose source was empty produces exactly
//! that, and reading it as "load the file named empty string" fails a
//! service for a reason nobody can see in the definition.
//!
//! # Why not something that already exists
//!
//! [`webpki-roots`] compiles the Mozilla set in and offers no way to extend
//! it. [`rustls-native-certs`] reads the operating system's store, which is
//! a different thing: it replaces the Mozilla set with the host's, and in a
//! distroless or scratch container there is no host store to read.
//! `webpki-roots-patcher` solves the same problem with `LD_PRELOAD`. What
//! is missing is the boring middle: compiled-in roots, plus one file, from
//! inside the process.
//!
//! [`webpki-roots`]: https://crates.io/crates/webpki-roots
//! [`rustls-native-certs`]: https://crates.io/crates/rustls-native-certs
//!
//! # Examples
//!
//! The usual call. With no bundle configured this is the Mozilla root set:
//!
//! ```
//! let roots = rustls_extra_roots::root_store().expect("no bundle is configured here");
//! assert!(!roots.is_empty());
//! ```
//!
//! Checking a specific file, which is what the startup check does:
//!
//! ```
//! use std::path::Path;
//!
//! let error = rustls_extra_roots::root_store_from(Some(Path::new("/nonexistent.pem")))
//!     .expect_err("the file is not there");
//!
//! assert!(error.to_string().contains("/nonexistent.pem"));
//! ```
//!
//! Under a different variable name, for a program that already means
//! something else by `SSL_CERT_FILE`:
//!
//! ```
//! use rustls_extra_roots::ExtraRoots;
//!
//! let roots = ExtraRoots::from_variable("CORPORATE_CA_BUNDLE")
//!     .root_store()
//!     .expect("nothing is configured under that name here");
//! # let _ = roots;
//! ```
//!
//! # Crypto providers
//!
//! [`root_store`] and friends need no crypto provider: assembling a trust
//! store is not a cryptographic operation. [`client_config`] does, because
//! `rustls` reads the process-default provider to pick cipher suites — this
//! crate deliberately selects none, so either install one
//! (`CryptoProvider::install_default`, or enable `ring` / `aws-lc-rs` on
//! your own `rustls` dependency) or call
//! [`client_config_with_provider`] to be explicit.

#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]

use std::borrow::Cow;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use rustls::crypto::CryptoProvider;
use rustls::{ClientConfig, RootCertStore};
use rustls_pki_types::CertificateDer;
use rustls_pki_types::pem::PemObject;

/// The environment variable consulted when no other name is given.
///
/// See the crate documentation for why this name does not carry its
/// OpenSSL meaning here.
pub const DEFAULT_VARIABLE: &str = "SSL_CERT_FILE";

/// Why the trust roots could not be assembled.
///
/// Each variant names the file. A deployment failing with "invalid
/// certificate" and no path is a deployment somebody has to guess about.
#[derive(Debug, thiserror::Error)]
pub enum TrustError {
    /// The file could not be opened, read, or parsed as PEM.
    #[error("could not read the CA bundle {path}: {source}")]
    Unreadable {
        /// Which file.
        path: String,
        /// Why.
        #[source]
        source: io::Error,
    },

    /// The file was read but held no certificate.
    ///
    /// A PEM file of only a private key lands here, as does an empty file
    /// and a file of PEM-looking text that parsed to nothing. All three
    /// mean the same thing to a caller: the bundle contributed no roots, so
    /// continuing would silently use the defaults.
    #[error("the CA bundle {path} contains no certificate")]
    Empty {
        /// Which file.
        path: String,
    },

    /// Certificates parsed, but `rustls` rejected every one of them.
    #[error("the CA bundle {path} contains {count} certificate(s), none usable as a root")]
    NoneUsable {
        /// Which file.
        path: String,
        /// How many were read before being rejected.
        count: usize,
    },
}

/// Which environment variable names the bundle.
///
/// Construct one of these when [`DEFAULT_VARIABLE`] is not the name you
/// want; the free functions in this crate are the same operations against
/// the default.
///
/// # Examples
///
/// ```
/// use rustls_extra_roots::{DEFAULT_VARIABLE, ExtraRoots};
///
/// assert_eq!(ExtraRoots::new().variable(), DEFAULT_VARIABLE);
/// assert_eq!(ExtraRoots::from_variable("MY_CA_BUNDLE").variable(), "MY_CA_BUNDLE");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExtraRoots {
    /// The variable to read.
    variable: Cow<'static, str>,
}

impl Default for ExtraRoots {
    fn default() -> Self {
        Self::new()
    }
}

impl ExtraRoots {
    /// Read [`DEFAULT_VARIABLE`].
    #[must_use]
    pub const fn new() -> Self {
        Self {
            variable: Cow::Borrowed(DEFAULT_VARIABLE),
        }
    }

    /// Read the named variable instead.
    #[must_use]
    pub fn from_variable(variable: impl Into<Cow<'static, str>>) -> Self {
        Self {
            variable: variable.into(),
        }
    }

    /// Which variable this reads.
    #[must_use]
    pub fn variable(&self) -> &str {
        &self.variable
    }

    /// The bundle this names, if it names one.
    ///
    /// [`None`] when unset, empty, or whitespace — blank is absent.
    #[must_use]
    pub fn configured_bundle(&self) -> Option<PathBuf> {
        bundle_from_value(std::env::var(self.variable.as_ref()).ok().as_deref())
    }

    /// Trust roots: the built-in set, plus whatever this variable names.
    ///
    /// # Errors
    ///
    /// [`TrustError`] if a bundle is configured and cannot be used. No
    /// error is possible when none is configured.
    pub fn root_store(&self) -> Result<RootCertStore, TrustError> {
        root_store_from(self.configured_bundle().as_deref())
    }

    /// A client configuration trusting [`ExtraRoots::root_store`], with no
    /// client certificate.
    ///
    /// # Panics
    ///
    /// Through `rustls`, if no process-default [`CryptoProvider`] has been
    /// installed. See the crate documentation, or use
    /// [`client_config_with_provider`].
    ///
    /// # Errors
    ///
    /// [`TrustError`], as [`ExtraRoots::root_store`].
    pub fn client_config(&self) -> Result<ClientConfig, TrustError> {
        Ok(ClientConfig::builder()
            .with_root_certificates(self.root_store()?)
            .with_no_client_auth())
    }

    /// Fail now if a configured bundle is unusable.
    ///
    /// Call this during startup, before binding a port or accepting work:
    /// the point is that the process refuses to reach a state where it
    /// looks healthy while being unable to make the TLS connections its
    /// work depends on.
    ///
    /// Returns the bundle that was validated, so the caller can log it.
    ///
    /// # Errors
    ///
    /// [`TrustError`] if a bundle is configured and cannot be used.
    pub fn validate(&self) -> Result<Option<PathBuf>, TrustError> {
        let bundle = self.configured_bundle();
        root_store_from(bundle.as_deref())?;
        Ok(bundle)
    }

    /// The startup check, logged, as a single call a `main` can branch on.
    ///
    /// Returns `false` when the process must not start.
    ///
    /// Worth calling even from a program that does not obviously speak TLS,
    /// if the variable is set across a whole deployment: a service that
    /// ignored a broken value would be the one that quietly kept running
    /// while its neighbours refused to, which is the least useful possible
    /// arrangement.
    ///
    /// Call it after logging is configured, so the failure is recorded
    /// rather than lost.
    #[must_use]
    pub fn startup_check(&self) -> bool {
        match self.validate() {
            Ok(Some(bundle)) => {
                log_trusted(&bundle);
                true
            }
            Ok(None) => true,
            Err(error) => {
                log_unusable(&self.variable, &error);
                false
            }
        }
    }
}

/// The blank-is-absent rule, separated from the environment that carries it.
///
/// Reading the variable is not the interesting part; deciding what counts
/// as "set" is. Keeping the decision pure means a test can state the rule
/// directly instead of mutating process-global state — which
/// [`std::env::set_var`] is `unsafe` for good reason, and which this crate
/// forbids outright.
///
/// # Examples
///
/// ```
/// use std::path::PathBuf;
/// use rustls_extra_roots::bundle_from_value;
///
/// assert_eq!(bundle_from_value(None), None);
/// assert_eq!(bundle_from_value(Some("   ")), None);
/// assert_eq!(bundle_from_value(Some("/ca.pem")), Some(PathBuf::from("/ca.pem")));
/// ```
#[must_use]
pub fn bundle_from_value(value: Option<&str>) -> Option<PathBuf> {
    value
        .filter(|value| !value.trim().is_empty())
        .map(PathBuf::from)
}

/// The bundle [`DEFAULT_VARIABLE`] names, if it names one.
#[must_use]
pub fn configured_bundle() -> Option<PathBuf> {
    ExtraRoots::new().configured_bundle()
}

/// Trust roots: the built-in set, plus whatever [`DEFAULT_VARIABLE`] names.
///
/// # Errors
///
/// [`TrustError`] if a bundle is configured and cannot be used.
pub fn root_store() -> Result<RootCertStore, TrustError> {
    ExtraRoots::new().root_store()
}

/// Trust roots: the built-in set, plus `bundle` if given.
///
/// The explicit-path form, so a caller — and a test — can be specific
/// rather than reaching through the environment.
///
/// # Errors
///
/// [`TrustError`] if `bundle` is [`Some`] and cannot be used.
pub fn root_store_from(bundle: Option<&Path>) -> Result<RootCertStore, TrustError> {
    let mut roots = RootCertStore {
        roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
    };

    let Some(path) = bundle else {
        return Ok(roots);
    };
    let named = path.display().to_string();

    // `rustls-pki-types` rather than the archived `rustls-pemfile`
    // (RUSTSEC-2025-0134); its own advisory says this is the same code.
    let certificates: Vec<CertificateDer<'static>> = CertificateDer::pem_file_iter(path)
        .map_err(|error| TrustError::Unreadable {
            path: named.clone(),
            source: io::Error::other(error.to_string()),
        })?
        .collect::<Result<_, _>>()
        .map_err(|error| TrustError::Unreadable {
            path: named.clone(),
            source: io::Error::other(error.to_string()),
        })?;

    if certificates.is_empty() {
        return Err(TrustError::Empty { path: named });
    }

    // `add_parsable_certificates` counts rather than failing, because a
    // corporate bundle legitimately carries certificates rustls will not
    // take as roots. Some being ignored is normal; ALL being ignored means
    // the file did nothing, which is the fatal case.
    let count = certificates.len();
    let (added, _ignored) = roots.add_parsable_certificates(certificates);
    if added == 0 {
        return Err(TrustError::NoneUsable { path: named, count });
    }

    log_loaded(&named, added, count - added);
    Ok(roots)
}

/// A client configuration trusting [`root_store`], with no client
/// certificate.
///
/// # Panics
///
/// Through `rustls`, if no process-default [`CryptoProvider`] has been
/// installed. See the crate documentation, or use
/// [`client_config_with_provider`].
///
/// # Errors
///
/// [`TrustError`], as [`root_store`].
pub fn client_config() -> Result<ClientConfig, TrustError> {
    ExtraRoots::new().client_config()
}

/// A client configuration trusting `bundle` in addition to the built-in
/// roots, using an explicitly supplied crypto provider.
///
/// The no-panic path: nothing here consults the process-default provider,
/// so this works in a library, in a test, and in a process that has not
/// installed one.
///
/// # Errors
///
/// [`TrustError`] if `bundle` is [`Some`] and cannot be used, or
/// [`rustls::Error`] if the provider supports none of the safe default
/// protocol versions.
pub fn client_config_with_provider(
    provider: Arc<CryptoProvider>,
    bundle: Option<&Path>,
) -> Result<ClientConfig, ConfigError> {
    let roots = root_store_from(bundle)?;
    Ok(ClientConfig::builder_with_provider(provider)
        .with_safe_default_protocol_versions()?
        .with_root_certificates(roots)
        .with_no_client_auth())
}

/// Why a client configuration could not be built.
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    /// The trust roots could not be assembled.
    #[error(transparent)]
    Trust(#[from] TrustError),

    /// `rustls` would not build a configuration from the given provider.
    #[error(transparent)]
    Rustls(#[from] rustls::Error),
}

/// Fail now if a bundle configured under [`DEFAULT_VARIABLE`] is unusable.
///
/// Returns the bundle that was validated, so the caller can log it.
///
/// # Errors
///
/// [`TrustError`] if a bundle is configured and cannot be used.
pub fn validate_at_startup() -> Result<Option<PathBuf>, TrustError> {
    ExtraRoots::new().validate()
}

/// The startup check against [`DEFAULT_VARIABLE`], logged, as a single call
/// a `main` can branch on.
///
/// Returns `false` when the process must not start.
///
/// # Examples
///
/// ```no_run
/// use std::process::ExitCode;
///
/// fn main() -> ExitCode {
///     if !rustls_extra_roots::startup_check() {
///         return ExitCode::FAILURE;
///     }
///     ExitCode::SUCCESS
/// }
/// ```
#[must_use]
pub fn startup_check() -> bool {
    ExtraRoots::new().startup_check()
}

// The three log sites, in one place so that `--no-default-features` costs
// three empty functions rather than `cfg` noise through the logic above.

#[cfg(feature = "tracing")]
fn log_loaded(path: &str, added: usize, ignored: usize) {
    tracing::info!(path, added, ignored, "loaded the additional CA bundle");
}

#[cfg(not(feature = "tracing"))]
#[allow(clippy::needless_pass_by_value)]
fn log_loaded(_path: &str, _added: usize, _ignored: usize) {}

#[cfg(feature = "tracing")]
fn log_trusted(bundle: &Path) {
    tracing::info!(
        bundle = %bundle.display(),
        "trusting an additional CA bundle alongside the built-in roots"
    );
}

#[cfg(not(feature = "tracing"))]
fn log_trusted(_bundle: &Path) {}

#[cfg(feature = "tracing")]
fn log_unusable(variable: &str, error: &TrustError) {
    tracing::error!(
        %error,
        variable,
        "the configured CA bundle is not usable, so this process will not start"
    );
}

#[cfg(not(feature = "tracing"))]
fn log_unusable(_variable: &str, _error: &TrustError) {}

#[cfg(test)]
mod tests {
    use super::*;

    /// A file in the temporary directory, removed when the test ends.
    ///
    /// Twenty lines rather than a `tempfile` dependency: this crate exists
    /// partly to argue against adding dependencies for one use. The name
    /// carries the process id and a counter because `cargo test` runs these
    /// in parallel.
    struct TempPem(PathBuf);

    impl TempPem {
        fn new(contents: &[u8]) -> Self {
            use std::sync::atomic::{AtomicU32, Ordering};
            static NEXT: AtomicU32 = AtomicU32::new(0);

            let path = std::env::temp_dir().join(format!(
                "rustls-extra-roots-{}-{}.pem",
                std::process::id(),
                NEXT.fetch_add(1, Ordering::Relaxed)
            ));
            std::fs::write(&path, contents).expect("the temporary directory is writable");
            Self(path)
        }

        fn path(&self) -> &Path {
            &self.0
        }
    }

    impl Drop for TempPem {
        fn drop(&mut self) {
            let _ = std::fs::remove_file(&self.0);
        }
    }

    /// A real, self-signed CA certificate, so the happy path is tested
    /// against something rustls actually accepts as a root rather than
    /// against a string that merely looks like PEM.
    const A_REAL_CA: &str = include_str!("../tests/a-real-ca.pem");

    #[test]
    fn no_bundle_configured_gives_the_built_in_roots() {
        let roots = root_store_from(None).expect("no bundle cannot fail");
        assert_eq!(
            roots.len(),
            webpki_roots::TLS_SERVER_ROOTS.len(),
            "with nothing configured the store is exactly the compiled-in set"
        );
    }

    #[test]
    fn a_bundle_adds_to_the_built_in_roots_rather_than_replacing_them() {
        let pem = TempPem::new(A_REAL_CA.as_bytes());
        let roots = root_store_from(Some(pem.path())).expect("a real CA is usable");

        // The rule this crate exists to state: the variable means
        // *additional* here, unlike OpenSSL's meaning of the same name.
        assert_eq!(
            roots.len(),
            webpki_roots::TLS_SERVER_ROOTS.len() + 1,
            "the bundle's certificate is added to the compiled-in set, not \
             substituted for it"
        );
    }

    #[test]
    fn a_missing_file_is_a_startup_failure_naming_the_file() {
        let error = root_store_from(Some(Path::new("/no/such/bundle.pem")))
            .expect_err("a configured bundle that cannot be read is fatal");

        assert!(matches!(error, TrustError::Unreadable { .. }));
        assert!(
            error.to_string().contains("/no/such/bundle.pem"),
            "the message must name the file: {error}"
        );
    }

    #[test]
    fn an_empty_file_is_a_startup_failure() {
        let pem = TempPem::new(b"");
        let error = root_store_from(Some(pem.path())).expect_err("no certificates means fatal");

        assert!(matches!(error, TrustError::Empty { .. }), "{error}");
    }

    #[test]
    fn a_file_of_only_a_private_key_is_a_startup_failure() {
        // The plausible operator mistake: mounting the key beside the
        // certificate and naming the wrong one. It is readable, it is valid
        // PEM, and it contributes no roots — which is exactly the case this
        // rule exists for, because the default roots would otherwise carry
        // on working until the one connection that needed the corporate CA
        // failed somewhere else.
        let pem = TempPem::new(
            b"-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIA==\n-----END PRIVATE KEY-----\n",
        );
        let error = root_store_from(Some(pem.path())).expect_err("a key is not a certificate");

        assert!(matches!(error, TrustError::Empty { .. }), "{error}");
    }

    #[test]
    fn text_that_is_not_pem_at_all_is_a_startup_failure() {
        let pem = TempPem::new(b"this is not a certificate\n");
        let error = root_store_from(Some(pem.path())).expect_err("not a bundle");

        // Whether the reader calls this unreadable or empty is its own
        // business; what matters is that it does not succeed.
        assert!(
            matches!(
                error,
                TrustError::Empty { .. } | TrustError::Unreadable { .. }
            ),
            "{error}"
        );
    }

    #[test]
    fn blank_is_absent() {
        // A templated container definition whose source was empty produces
        // `SSL_CERT_FILE=`, and reading that as "load the file named empty
        // string" fails a service for a reason nobody can see in the
        // definition.
        for blank in [None, Some(""), Some(" "), Some("\t"), Some("   \n ")] {
            assert!(
                bundle_from_value(blank).is_none(),
                "{blank:?} must read as absent"
            );
        }
    }

    #[test]
    fn a_named_bundle_is_taken_as_given() {
        assert_eq!(
            bundle_from_value(Some("/some/bundle.pem")),
            Some(PathBuf::from("/some/bundle.pem"))
        );

        // Surrounding whitespace decides absence but is not stripped from a
        // real value: a path is whatever the operator wrote, and silently
        // trimming one would be a second, invisible rule.
        assert_eq!(
            bundle_from_value(Some(" /padded.pem ")),
            Some(PathBuf::from(" /padded.pem "))
        );
    }

    #[test]
    fn the_variable_name_is_a_parameter() {
        assert_eq!(ExtraRoots::new().variable(), DEFAULT_VARIABLE);
        assert_eq!(ExtraRoots::default().variable(), "SSL_CERT_FILE");

        // Both an owned and a borrowed name, because the `Into<Cow>` bound
        // is the whole point of accepting either.
        assert_eq!(
            ExtraRoots::from_variable("CORPORATE_CA_BUNDLE").variable(),
            "CORPORATE_CA_BUNDLE"
        );
        assert_eq!(
            ExtraRoots::from_variable(String::from("OWNED_NAME")).variable(),
            "OWNED_NAME"
        );
    }

    #[test]
    fn an_unset_variable_reads_as_no_bundle() {
        // A name nothing sets, so this asserts the absent path without
        // touching process-global state.
        let roots = ExtraRoots::from_variable("RUSTLS_EXTRA_ROOTS_DEFINITELY_UNSET");
        assert_eq!(roots.configured_bundle(), None);
        assert!(roots.startup_check(), "nothing configured is not a failure");
    }

    #[test]
    fn an_explicit_provider_builds_a_configuration_without_a_process_default() {
        // `client_config` reads the process-default provider and panics
        // without one; this path takes the provider as an argument, which
        // is what makes the crate usable from a library.
        let pem = TempPem::new(A_REAL_CA.as_bytes());
        let provider = Arc::new(rustls::crypto::ring::default_provider());

        let config = client_config_with_provider(provider, Some(pem.path()))
            .expect("a real CA and a real provider");

        // `ClientConfig` does not expose its root store, so the store
        // itself is asserted where it is built; what this test adds is
        // that the explicit-provider path reaches a configuration at all,
        // with no process default installed.
        assert!(config.alpn_protocols.is_empty());
    }

    #[test]
    fn an_unusable_bundle_fails_the_configuration_too() {
        let provider = Arc::new(rustls::crypto::ring::default_provider());
        let error = client_config_with_provider(provider, Some(Path::new("/no/such.pem")))
            .expect_err("the file is not there");

        assert!(matches!(error, ConfigError::Trust(TrustError::Unreadable { .. })));
    }
}