use std::{
fmt, fs, io,
io::Read,
path::{Path, PathBuf},
sync::Arc,
};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::{
config::{ConfigIssueCollector, ConfigValidationError},
result::{ClassifyError, ErrorKind},
};
const DEFAULT_ROOT_CA_DIR: &str = "/etc/pki/ca-trust/source/anchors";
const CA_FILE_EXTENSIONS: &[&str] = &["cer", "crt", "pem"];
pub const MAX_ROOT_CA_DIRECTORY_ENTRIES: usize = 1_024;
pub const MAX_ROOT_CA_FILES: usize = 128;
pub const MAX_ROOT_CA_FILE_BYTES: usize = 1024 * 1024;
pub const MAX_ROOT_CA_BUNDLE_BYTES: usize = 8 * 1024 * 1024;
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct TlsTrustConfig {
#[serde(default = "default_root_ca_dir")]
pub root_ca_dir: Option<PathBuf>,
}
impl fmt::Debug for TlsTrustConfig {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("TlsTrustConfig")
.field("custom_root_ca_dir", &self.root_ca_dir.is_some())
.finish()
}
}
impl Default for TlsTrustConfig {
fn default() -> Self {
Self {
root_ca_dir: default_root_ca_dir(),
}
}
}
impl TlsTrustConfig {
#[must_use]
pub const fn webpki_only() -> Self {
Self { root_ca_dir: None }
}
#[must_use]
pub fn with_root_ca_dir(path: impl Into<PathBuf>) -> Self {
Self {
root_ca_dir: Some(path.into()),
}
}
#[must_use]
pub fn root_ca_dir(&self) -> Option<&Path> {
self.root_ca_dir.as_deref()
}
pub fn load(&self) -> Result<LoadedTlsTrust, TlsTrustError> {
self.validate_paths()?;
let mut bundle = Vec::new();
let mut sources = Vec::new();
if let Some(path) = self.root_ca_dir() {
append_root_ca_dir(path, &mut bundle, &mut sources)?;
}
let root_ca_pem = if bundle.is_empty() {
None
} else {
Some(Arc::<[u8]>::from(bundle.into_boxed_slice()))
};
Ok(LoadedTlsTrust {
root_ca_pem,
root_ca_sources: Arc::from(sources.into_boxed_slice()),
})
}
pub fn validate_at(&self, path: &str) -> Result<(), ConfigValidationError> {
let path = normalize_path(path);
let mut issues = ConfigIssueCollector::new();
if let Some(root_ca_dir) = self.root_ca_dir() {
validate_path_shape(&mut issues, format!("{path}.root_ca_dir"), root_ca_dir);
}
issues.into_result()
}
fn validate_paths(&self) -> Result<(), TlsTrustError> {
if let Some(path) = self.root_ca_dir() {
validate_absolute_path(path)?;
}
Ok(())
}
}
#[derive(Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct LoadedTlsTrust {
root_ca_pem: Option<Arc<[u8]>>,
root_ca_sources: Arc<[PathBuf]>,
}
impl fmt::Debug for LoadedTlsTrust {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("LoadedTlsTrust")
.field(
"root_ca_pem_bytes",
&self.root_ca_pem.as_deref().map_or(0, <[u8]>::len),
)
.field("root_ca_source_count", &self.root_ca_sources.len())
.finish_non_exhaustive()
}
}
impl LoadedTlsTrust {
#[must_use]
pub fn root_ca_pem(&self) -> Option<&[u8]> {
self.root_ca_pem.as_deref()
}
#[must_use]
pub fn root_ca_source_count(&self) -> usize {
self.root_ca_sources.len()
}
#[must_use]
pub fn root_ca_sources(&self) -> &[PathBuf] {
&self.root_ca_sources
}
}
#[derive(Error)]
#[non_exhaustive]
pub enum TlsTrustError {
#[error("TLS root CA directory path must be absolute")]
RelativePath {
#[doc = "The affected path."]
path: PathBuf,
},
#[error("TLS root CA directory path must not contain NUL bytes")]
InvalidPath {
#[doc = "The affected path."]
path: PathBuf,
},
#[error("TLS root CA directory path must point to a directory")]
RootCaDirNotDirectory {
#[doc = "The affected path."]
path: PathBuf,
},
#[error("TLS root CA file is empty")]
EmptyRootCaFile {
#[doc = "The affected path."]
path: PathBuf,
},
#[error("TLS root CA directory contains too many entries")]
TooManyRootCaDirectoryEntries {
#[doc = "The configured upper bound."]
max: usize,
},
#[error("TLS root CA directory contains too many CA files")]
TooManyRootCaFiles {
#[doc = "The configured upper bound."]
max: usize,
},
#[error("TLS root CA file is too large")]
RootCaFileTooLarge {
#[doc = "The affected path."]
path: PathBuf,
#[doc = "The configured upper bound."]
max_bytes: usize,
},
#[error("TLS root CA bundle is too large")]
RootCaBundleTooLarge {
#[doc = "The configured upper bound."]
max_bytes: usize,
},
#[error("failed to read TLS root CA file")]
ReadRootCaFile {
path: PathBuf,
#[source]
source: io::Error,
},
#[error("failed to read TLS root CA directory")]
ReadRootCaDir {
path: PathBuf,
#[source]
source: io::Error,
},
#[error("failed to read TLS root CA directory entry")]
ReadRootCaDirEntry {
path: PathBuf,
#[source]
source: io::Error,
},
}
impl fmt::Debug for TlsTrustError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("TlsTrustError")
.field("code", &self.error_code())
.finish_non_exhaustive()
}
}
impl ClassifyError for TlsTrustError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed(match self {
Self::RelativePath { .. } => "tls_root_ca_dir_relative_path",
Self::InvalidPath { .. } => "tls_root_ca_dir_invalid_path",
Self::RootCaDirNotDirectory { .. } => "tls_root_ca_dir_not_directory",
Self::EmptyRootCaFile { .. } => "tls_root_ca_file_empty",
Self::TooManyRootCaDirectoryEntries { .. } => "tls_root_ca_dir_too_many_entries",
Self::TooManyRootCaFiles { .. } => "tls_root_ca_dir_too_many_ca_files",
Self::RootCaFileTooLarge { .. } => "tls_root_ca_file_too_large",
Self::RootCaBundleTooLarge { .. } => "tls_root_ca_bundle_too_large",
Self::ReadRootCaFile { .. } => "tls_root_ca_file_read_failed",
Self::ReadRootCaDir { .. } => "tls_root_ca_dir_read_failed",
Self::ReadRootCaDirEntry { .. } => "tls_root_ca_dir_entry_read_failed",
})
}
}
#[cfg(feature = "tls-reqx")]
impl LoadedTlsTrust {
#[must_use]
pub fn apply_to_reqx_builder(&self, builder: reqx::ClientBuilder) -> reqx::ClientBuilder {
let builder = builder.tls_root_store(reqx::TlsRootStore::WebPki);
if let Some(root_ca_pem) = self.root_ca_pem() {
builder.tls_root_ca_pem(root_ca_pem.to_vec())
} else {
builder
}
}
pub fn validate_reqx(&self) -> Result<(), reqx::Error> {
self.apply_to_reqx_builder(reqx::Client::builder("https://example.invalid"))
.build()
.map(|_| ())
}
}
fn append_root_ca_dir(
path: &Path,
bundle: &mut Vec<u8>,
sources: &mut Vec<PathBuf>,
) -> Result<(), TlsTrustError> {
if !path.exists() {
return Ok(());
}
let metadata = fs::metadata(path).map_err(|source| TlsTrustError::ReadRootCaDir {
path: path.to_path_buf(),
source,
})?;
if !metadata.is_dir() {
return Err(TlsTrustError::RootCaDirNotDirectory {
path: path.to_path_buf(),
});
}
let mut entries = Vec::new();
let mut entry_count = 0usize;
for entry in fs::read_dir(path).map_err(|source| TlsTrustError::ReadRootCaDir {
path: path.to_path_buf(),
source,
})? {
entry_count = entry_count.saturating_add(1);
if entry_count > MAX_ROOT_CA_DIRECTORY_ENTRIES {
return Err(TlsTrustError::TooManyRootCaDirectoryEntries {
max: MAX_ROOT_CA_DIRECTORY_ENTRIES,
});
}
let entry = entry.map_err(|source| TlsTrustError::ReadRootCaDirEntry {
path: path.to_path_buf(),
source,
})?;
let entry = entry.path();
if !is_ca_file(&entry) {
continue;
}
if entries.len() >= MAX_ROOT_CA_FILES {
return Err(TlsTrustError::TooManyRootCaFiles {
max: MAX_ROOT_CA_FILES,
});
}
entries.push(entry);
}
entries.sort();
for entry in &entries {
append_root_ca_file(entry, bundle, sources)?;
}
Ok(())
}
fn append_root_ca_file(
path: &Path,
bundle: &mut Vec<u8>,
sources: &mut Vec<PathBuf>,
) -> Result<(), TlsTrustError> {
if sources.iter().any(|source| source == path) {
return Ok(());
}
let file = fs::File::open(path).map_err(|source| TlsTrustError::ReadRootCaFile {
path: path.to_path_buf(),
source,
})?;
let mut bytes = Vec::with_capacity(MAX_ROOT_CA_FILE_BYTES + 1);
file.take((MAX_ROOT_CA_FILE_BYTES + 1) as u64)
.read_to_end(&mut bytes)
.map_err(|source| TlsTrustError::ReadRootCaFile {
path: path.to_path_buf(),
source,
})?;
if bytes.len() > MAX_ROOT_CA_FILE_BYTES {
return Err(TlsTrustError::RootCaFileTooLarge {
path: path.to_path_buf(),
max_bytes: MAX_ROOT_CA_FILE_BYTES,
});
}
if bytes.is_empty() {
return Err(TlsTrustError::EmptyRootCaFile {
path: path.to_path_buf(),
});
}
let separator_bytes = usize::from(!bundle.is_empty() && !bundle.ends_with(b"\n"));
let trailing_newline_bytes = usize::from(!bytes.ends_with(b"\n"));
let next_bundle_bytes = bundle
.len()
.checked_add(separator_bytes)
.and_then(|size| size.checked_add(bytes.len()))
.and_then(|size| size.checked_add(trailing_newline_bytes))
.ok_or(TlsTrustError::RootCaBundleTooLarge {
max_bytes: MAX_ROOT_CA_BUNDLE_BYTES,
})?;
if next_bundle_bytes > MAX_ROOT_CA_BUNDLE_BYTES {
return Err(TlsTrustError::RootCaBundleTooLarge {
max_bytes: MAX_ROOT_CA_BUNDLE_BYTES,
});
}
if separator_bytes != 0 {
bundle.push(b'\n');
}
bundle.extend_from_slice(&bytes);
if !bundle.ends_with(b"\n") {
bundle.push(b'\n');
}
sources.push(path.to_path_buf());
Ok(())
}
fn validate_absolute_path(path: &Path) -> Result<(), TlsTrustError> {
if has_nul(path) {
return Err(TlsTrustError::InvalidPath {
path: path.to_path_buf(),
});
}
if !path.is_absolute() {
return Err(TlsTrustError::RelativePath {
path: path.to_path_buf(),
});
}
Ok(())
}
fn validate_path_shape(issues: &mut ConfigIssueCollector, path: String, value: &Path) {
issues.require(!has_nul(value), path.clone(), "must not contain NUL bytes");
issues.require(value.is_absolute(), path, "must be an absolute path");
}
fn is_ca_file(path: &Path) -> bool {
path.extension()
.and_then(|extension| extension.to_str())
.map(|extension| {
CA_FILE_EXTENSIONS
.iter()
.any(|candidate| extension.eq_ignore_ascii_case(candidate))
})
.unwrap_or(false)
}
fn has_nul(path: &Path) -> bool {
path.as_os_str()
.to_str()
.is_some_and(|value| value.contains('\0'))
}
fn normalize_path(path: &str) -> String {
let path = path.trim();
if path.is_empty() {
"tls".to_owned()
} else {
path.to_owned()
}
}
fn default_root_ca_dir() -> Option<PathBuf> {
Some(PathBuf::from(DEFAULT_ROOT_CA_DIR))
}
#[cfg(test)]
mod tests {
use std::{fs, path::PathBuf};
use super::{
MAX_ROOT_CA_BUNDLE_BYTES, MAX_ROOT_CA_FILE_BYTES, MAX_ROOT_CA_FILES, TlsTrustConfig,
TlsTrustError,
};
#[test]
fn default_trust_uses_webpki_plus_fixed_ca_dir() {
let config = TlsTrustConfig::default();
assert_eq!(
config.root_ca_dir().expect("default CA dir should exist"),
PathBuf::from("/etc/pki/ca-trust/source/anchors")
);
}
#[test]
fn missing_ca_dir_loads_webpki_only() {
let loaded = TlsTrustConfig::with_root_ca_dir(test_dir("footing-tls-missing"))
.load()
.expect("missing CA dir should be ignored");
assert_eq!(loaded.root_ca_source_count(), 0);
assert!(loaded.root_ca_pem().is_none());
}
#[test]
fn trust_config_validation_rejects_relative_dir() {
let error = TlsTrustConfig::with_root_ca_dir("config/ca.d")
.validate_at("tls")
.expect_err("relative path should fail validation");
assert_eq!(error.issues()[0].path(), "tls.root_ca_dir");
}
#[test]
fn trust_debug_and_errors_do_not_expose_paths_or_io_details() {
let private_path = "private-ca-directory";
let config = TlsTrustConfig::with_root_ca_dir(private_path);
let error = config.load().expect_err("relative path should fail");
let output = format!("{config:?} {error:?} {error}");
assert!(output.contains("tls_root_ca_dir_relative_path"));
assert!(!output.contains(private_path));
}
#[test]
fn trust_config_loads_ca_dir_deterministically() {
let ca_dir = test_dir("footing-tls-dir");
fs::create_dir_all(&ca_dir).expect("test dir should be created");
let first = ca_dir.join("a.pem");
let second = ca_dir.join("b.crt");
fs::write(
&first,
"-----BEGIN CERTIFICATE-----\nA\n-----END CERTIFICATE-----\n",
)
.expect("first root should be written");
fs::write(
&second,
"-----BEGIN CERTIFICATE-----\nB\n-----END CERTIFICATE-----\n",
)
.expect("second root should be written");
fs::write(ca_dir.join("ignored.txt"), "not a CA").expect("ignored file should be written");
let loaded = TlsTrustConfig::with_root_ca_dir(&ca_dir)
.load()
.expect("trust config should load");
assert_eq!(loaded.root_ca_source_count(), 2);
assert_eq!(loaded.root_ca_sources()[0], first);
assert_eq!(loaded.root_ca_sources()[1], second);
assert!(
std::str::from_utf8(loaded.root_ca_pem().expect("bundle should exist"))
.expect("bundle should be utf8")
.contains("BEGIN CERTIFICATE")
);
let debug = format!("{loaded:?}");
assert!(debug.contains("root_ca_pem_bytes"));
assert!(!debug.contains("BEGIN CERTIFICATE"));
assert!(!debug.contains(first.to_string_lossy().as_ref()));
fs::remove_dir_all(&ca_dir).expect("test dir should be removed");
}
#[test]
fn ca_dir_must_be_directory_when_present() {
let file = test_dir("footing-tls-file");
fs::write(&file, "not a dir").expect("file should be written");
let error = TlsTrustConfig::with_root_ca_dir(&file)
.load()
.expect_err("file path should fail");
assert!(matches!(error, TlsTrustError::RootCaDirNotDirectory { .. }));
fs::remove_file(&file).expect("file should be removed");
}
#[test]
fn trust_config_rejects_oversized_ca_files_before_unbounded_allocation() {
let ca_dir = test_dir("footing-tls-oversized");
fs::create_dir_all(&ca_dir).expect("test dir should be created");
fs::write(
ca_dir.join("oversized.pem"),
vec![b'A'; MAX_ROOT_CA_FILE_BYTES + 1],
)
.expect("oversized root should be written");
let error = TlsTrustConfig::with_root_ca_dir(&ca_dir)
.load()
.expect_err("oversized root should fail");
assert!(matches!(error, TlsTrustError::RootCaFileTooLarge { .. }));
fs::remove_dir_all(&ca_dir).expect("test dir should be removed");
}
#[test]
fn trust_config_rejects_excessive_ca_file_counts() {
let ca_dir = test_dir("footing-tls-too-many");
fs::create_dir_all(&ca_dir).expect("test dir should be created");
for index in 0..=MAX_ROOT_CA_FILES {
fs::write(ca_dir.join(format!("{index:03}.pem")), "certificate")
.expect("root should be written");
}
let error = TlsTrustConfig::with_root_ca_dir(&ca_dir)
.load()
.expect_err("excessive root count should fail");
assert!(matches!(error, TlsTrustError::TooManyRootCaFiles { .. }));
fs::remove_dir_all(&ca_dir).expect("test dir should be removed");
}
#[test]
fn trust_config_bounds_combined_ca_bundle_size() {
let ca_file = test_dir("footing-tls-bundle-limit.pem");
fs::write(&ca_file, "certificate").expect("root should be written");
let mut bundle = vec![b'A'; MAX_ROOT_CA_BUNDLE_BYTES];
let mut sources = Vec::new();
let error = super::append_root_ca_file(&ca_file, &mut bundle, &mut sources)
.expect_err("oversized bundle should fail");
assert!(matches!(error, TlsTrustError::RootCaBundleTooLarge { .. }));
assert_eq!(bundle.len(), MAX_ROOT_CA_BUNDLE_BYTES);
assert!(sources.is_empty());
fs::remove_file(&ca_file).expect("root should be removed");
}
fn test_dir(name: &str) -> PathBuf {
std::env::temp_dir().join(format!("{name}-{}", std::process::id()))
}
}