#![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;
pub const DEFAULT_VARIABLE: &str = "SSL_CERT_FILE";
#[derive(Debug, thiserror::Error)]
pub enum TrustError {
#[error("could not read the CA bundle {path}: {source}")]
Unreadable {
path: String,
#[source]
source: io::Error,
},
#[error("the CA bundle {path} contains no certificate")]
Empty {
path: String,
},
#[error("the CA bundle {path} contains {count} certificate(s), none usable as a root")]
NoneUsable {
path: String,
count: usize,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExtraRoots {
variable: Cow<'static, str>,
}
impl Default for ExtraRoots {
fn default() -> Self {
Self::new()
}
}
impl ExtraRoots {
#[must_use]
pub const fn new() -> Self {
Self {
variable: Cow::Borrowed(DEFAULT_VARIABLE),
}
}
#[must_use]
pub fn from_variable(variable: impl Into<Cow<'static, str>>) -> Self {
Self {
variable: variable.into(),
}
}
#[must_use]
pub fn variable(&self) -> &str {
&self.variable
}
#[must_use]
pub fn configured_bundle(&self) -> Option<PathBuf> {
bundle_from_value(std::env::var(self.variable.as_ref()).ok().as_deref())
}
pub fn root_store(&self) -> Result<RootCertStore, TrustError> {
root_store_from(self.configured_bundle().as_deref())
}
pub fn client_config(&self) -> Result<ClientConfig, TrustError> {
Ok(ClientConfig::builder()
.with_root_certificates(self.root_store()?)
.with_no_client_auth())
}
pub fn validate(&self) -> Result<Option<PathBuf>, TrustError> {
let bundle = self.configured_bundle();
root_store_from(bundle.as_deref())?;
Ok(bundle)
}
#[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
}
}
}
}
#[must_use]
pub fn bundle_from_value(value: Option<&str>) -> Option<PathBuf> {
value
.filter(|value| !value.trim().is_empty())
.map(PathBuf::from)
}
#[must_use]
pub fn configured_bundle() -> Option<PathBuf> {
ExtraRoots::new().configured_bundle()
}
pub fn root_store() -> Result<RootCertStore, TrustError> {
ExtraRoots::new().root_store()
}
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();
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 });
}
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)
}
pub fn client_config() -> Result<ClientConfig, TrustError> {
ExtraRoots::new().client_config()
}
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())
}
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
#[error(transparent)]
Trust(#[from] TrustError),
#[error(transparent)]
Rustls(#[from] rustls::Error),
}
pub fn validate_at_startup() -> Result<Option<PathBuf>, TrustError> {
ExtraRoots::new().validate()
}
#[must_use]
pub fn startup_check() -> bool {
ExtraRoots::new().startup_check()
}
#[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::*;
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);
}
}
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");
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() {
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");
assert!(
matches!(
error,
TrustError::Empty { .. } | TrustError::Unreadable { .. }
),
"{error}"
);
}
#[test]
fn blank_is_absent() {
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"))
);
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");
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() {
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() {
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");
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 { .. })));
}
}