use std::{
fmt, fs, io,
io::Read,
path::{Path, PathBuf},
sync::Arc,
};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::{
result::{ClassifyError, ErrorKind},
settings::{SettingsIssues, SettingsValidationError, field_path},
};
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;
#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum TlsTrustMode {
#[default]
#[serde(rename = "webpki")]
WebPki,
CustomOnly,
}
#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct TlsTrustSettings {
pub mode: TlsTrustMode,
pub root_ca_dir: Option<PathBuf>,
}
impl fmt::Debug for TlsTrustSettings {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("TlsTrustSettings")
.field("mode", &self.mode)
.field("custom_root_ca_dir", &self.root_ca_dir.is_some())
.finish()
}
}
impl TlsTrustSettings {
#[must_use]
pub const fn webpki_only() -> Self {
Self {
mode: TlsTrustMode::WebPki,
root_ca_dir: None,
}
}
#[must_use]
pub fn with_root_ca_dir(path: impl Into<PathBuf>) -> Self {
Self {
mode: TlsTrustMode::WebPki,
root_ca_dir: Some(path.into()),
}
}
#[must_use]
pub const fn with_mode(mut self, mode: TlsTrustMode) -> Self {
self.mode = mode;
self
}
pub fn build(self) -> Result<TlsTrustConfig, SettingsValidationError> {
self.validate()?;
Ok(TlsTrustConfig {
mode: self.mode,
root_ca_dir: self.root_ca_dir,
})
}
pub fn validate(&self) -> Result<(), SettingsValidationError> {
self.validate_at("tls")
}
pub fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
let mut issues = SettingsIssues::new();
issues.require(
self.mode != TlsTrustMode::CustomOnly || self.root_ca_dir.is_some(),
field_path(path, "root_ca_dir"),
"is required when mode is custom_only",
);
if let Some(root_ca_dir) = self.root_ca_dir.as_deref() {
validate_path_shape(&mut issues, field_path(path, "root_ca_dir"), root_ca_dir);
}
issues.into_result()
}
}
#[derive(Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct TlsTrustConfig {
mode: TlsTrustMode,
root_ca_dir: Option<PathBuf>,
}
impl fmt::Debug for TlsTrustConfig {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("TlsTrustConfig")
.field("mode", &self.mode)
.field("custom_root_ca_dir", &self.root_ca_dir.is_some())
.finish()
}
}
impl TlsTrustConfig {
#[must_use]
pub const fn webpki_only() -> Self {
Self {
mode: TlsTrustMode::WebPki,
root_ca_dir: None,
}
}
#[must_use]
pub const fn mode(&self) -> TlsTrustMode {
self.mode
}
#[must_use]
pub fn root_ca_dir(&self) -> Option<&Path> {
self.root_ca_dir.as_deref()
}
pub fn load(&self) -> Result<LoadedTlsTrust, TlsTrustError> {
let mut bundle = Vec::new();
let sources = match self.root_ca_dir() {
Some(path) => append_root_ca_dir(path, &mut bundle)?,
None => Vec::new(),
};
if self.mode == TlsTrustMode::CustomOnly && bundle.is_empty() {
return Err(TlsTrustError::MissingCustomRoots);
}
let root_ca_pem = if bundle.is_empty() {
None
} else {
Some(Arc::<[u8]>::from(bundle))
};
Ok(LoadedTlsTrust {
mode: self.mode,
root_ca_pem,
root_ca_sources: Arc::from(sources),
})
}
}
#[derive(Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct LoadedTlsTrust {
mode: TlsTrustMode,
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("mode", &self.mode)
.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 const fn mode(&self) -> TlsTrustMode {
self.mode
}
#[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("custom-only TLS trust requires at least one root CA file")]
MissingCustomRoots,
#[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) -> crate::result::ErrorCode {
crate::result::ErrorCode::internal(match self {
Self::MissingCustomRoots => "tls_custom_roots_missing",
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<T>(
&self,
builder: reqx::ClientBuilder<T>,
) -> reqx::ClientBuilder<T> {
let builder = builder.tls_root_store(match self.mode {
TlsTrustMode::WebPki => reqx::TlsRootStore::WebPki,
TlsTrustMode::CustomOnly => reqx::TlsRootStore::Specific,
});
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>) -> Result<Vec<PathBuf>, TlsTrustError> {
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();
entries.dedup();
for entry in &entries {
append_root_ca_file(entry, bundle)?;
}
Ok(entries)
}
fn append_root_ca_file(path: &Path, bundle: &mut Vec<u8>) -> Result<(), TlsTrustError> {
let metadata = fs::metadata(path).map_err(|source| TlsTrustError::ReadRootCaFile {
path: path.to_path_buf(),
source,
})?;
if !metadata.is_file() {
return Err(TlsTrustError::ReadRootCaFile {
path: path.to_path_buf(),
source: io::Error::new(
io::ErrorKind::InvalidInput,
"root CA must be a regular file",
),
});
}
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');
}
Ok(())
}
fn validate_path_shape(issues: &mut SettingsIssues, 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().as_encoded_bytes().contains(&0)
}
#[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, TlsTrustMode, TlsTrustSettings,
};
#[cfg(feature = "tls-reqx")]
const TEST_CA_PEM: &str = "-----BEGIN CERTIFICATE-----
MIIBozCCAUmgAwIBAgIUQDWrcBX0j4Re2Njp8L+whfK8zCwwCgYIKoZIzj0EAwIw
HjEcMBoGA1UEAwwTRm9vdGluZyBUTFMgdGVzdCBDQTAgFw0yNjA5MzAxODEyMjBa
GA8yMTI2MDkwNjE4MTIyMFowHjEcMBoGA1UEAwwTRm9vdGluZyBUTFMgdGVzdCBD
QTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABK/t0RwUd/KMe5U433x9OK+k+And
Jsh9KktG1CxZ/AHSHR1X1TD9ZT/+xfFDdeEkD7ksx0fxVH5K502i7HHPofqjYzBh
MB0GA1UdDgQWBBTnk3EmhF731WIC0hllzO+jIW0WazAfBgNVHSMEGDAWgBTnk3Em
hF731WIC0hllzO+jIW0WazAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB
BjAKBggqhkjOPQQDAgNIADBFAiAwShB0Vq0imuCGUps9A/wsavSrJ0S4+IJS0cra
XYX5UAIhAI/Xp2L4udsHqsCWTz6HBcqGiurKC7vWftTXJRq+f+eS
-----END CERTIFICATE-----
";
fn config_with_ca_dir(path: impl Into<PathBuf>) -> TlsTrustConfig {
TlsTrustSettings::with_root_ca_dir(path).build().unwrap()
}
#[test]
#[cfg(unix)]
fn trust_validation_rejects_nul_in_non_utf8_paths() {
use std::{ffi::OsString, os::unix::ffi::OsStringExt};
let path = PathBuf::from(OsString::from_vec(b"/tmp/ca-\xff\0.pem".to_vec()));
let error = TlsTrustSettings::with_root_ca_dir(path)
.build()
.expect_err("NUL must be rejected even in non-UTF-8 paths");
assert_eq!(error.issues()[0].path(), "tls.root_ca_dir");
}
#[test]
#[cfg(unix)]
fn ca_directory_metadata_errors_are_not_treated_as_missing_directories() {
let path = test_dir("footing-tls-symlink-loop");
std::os::unix::fs::symlink(&path, &path).unwrap();
let result = config_with_ca_dir(&path).load();
fs::remove_file(&path).unwrap();
assert!(matches!(result, Err(TlsTrustError::ReadRootCaDir { .. })));
}
#[test]
#[cfg(target_os = "linux")]
fn ca_loading_rejects_pipes_without_waiting_for_the_writer() {
use std::{os::fd::AsRawFd, sync::mpsc, time::Duration};
let ca_dir = test_dir("footing-tls-pipe");
fs::create_dir_all(&ca_dir).unwrap();
let (reader, writer) = std::io::pipe().unwrap();
std::os::unix::fs::symlink(
format!("/proc/self/fd/{}", reader.as_raw_fd()),
ca_dir.join("root.pem"),
)
.unwrap();
let config = config_with_ca_dir(&ca_dir);
let (sender, receiver) = mpsc::channel();
let loading = std::thread::spawn(move || {
sender.send(config.load()).unwrap();
});
let result = receiver.recv_timeout(Duration::from_secs(1));
drop(writer);
loading.join().unwrap();
drop(reader);
fs::remove_dir_all(&ca_dir).unwrap();
assert!(result.is_ok(), "CA loading waited for a pipe writer");
assert!(matches!(
result.unwrap(),
Err(TlsTrustError::ReadRootCaFile { source, .. })
if source.kind() == std::io::ErrorKind::InvalidInput
));
}
#[test]
#[cfg(unix)]
fn ca_loading_accepts_symlinks_to_regular_files() {
let ca_dir = test_dir("footing-tls-mounted-ca");
fs::create_dir_all(ca_dir.join("mounted")).unwrap();
fs::write(ca_dir.join("mounted/root"), "certificate").unwrap();
std::os::unix::fs::symlink("mounted/root", ca_dir.join("root.pem")).unwrap();
let result = config_with_ca_dir(&ca_dir).load();
fs::remove_dir_all(&ca_dir).unwrap();
let loaded = result.unwrap();
assert_eq!(loaded.root_ca_pem(), Some(&b"certificate\n"[..]));
assert_eq!(loaded.root_ca_sources(), &[ca_dir.join("root.pem")]);
}
#[test]
fn default_trust_uses_webpki_without_inspecting_the_filesystem() {
for config in [
TlsTrustConfig::default(),
TlsTrustSettings::default().build().unwrap(),
serde_json::from_str::<TlsTrustSettings>("{}")
.unwrap()
.build()
.unwrap(),
] {
assert_eq!(config.mode(), TlsTrustMode::WebPki);
assert!(config.root_ca_dir().is_none());
let loaded = config.load().unwrap();
assert_eq!(loaded.mode(), TlsTrustMode::WebPki);
assert_eq!(loaded.root_ca_source_count(), 0);
assert!(loaded.root_ca_pem().is_none());
}
}
#[test]
fn custom_only_settings_require_a_directory_and_round_trip_the_mode() {
let error = TlsTrustSettings::default()
.with_mode(TlsTrustMode::CustomOnly)
.build()
.unwrap_err();
assert_eq!(error.issues()[0].path(), "tls.root_ca_dir");
let path = test_dir("footing-tls-custom-settings");
for (mode, spelling) in [
(TlsTrustMode::WebPki, "webpki"),
(TlsTrustMode::CustomOnly, "custom_only"),
] {
let settings = TlsTrustSettings::with_root_ca_dir(&path).with_mode(mode);
let wire = serde_json::to_value(&settings).unwrap();
assert_eq!(wire["mode"], spelling);
let decoded: TlsTrustSettings = serde_json::from_value(wire).unwrap();
assert_eq!(decoded, settings);
assert_eq!(decoded.build().unwrap().mode(), mode);
}
assert!(serde_json::from_str::<TlsTrustSettings>(r#"{"mode":"system"}"#).is_err());
}
#[test]
fn custom_only_loading_rejects_empty_directories_without_a_public_root_fallback() {
use crate::result::ClassifyError;
let path = test_dir("footing-tls-empty-custom");
fs::create_dir_all(&path).unwrap();
fs::write(path.join("ignored.txt"), "not a CA file").unwrap();
let settings = TlsTrustSettings::with_root_ca_dir(&path);
assert!(settings.clone().build().unwrap().load().is_ok());
let error = settings
.with_mode(TlsTrustMode::CustomOnly)
.build()
.unwrap()
.load()
.unwrap_err();
assert!(matches!(error, TlsTrustError::MissingCustomRoots));
assert_eq!(error.error_code(), "tls_custom_roots_missing");
fs::remove_dir_all(path).unwrap();
}
#[test]
fn explicitly_configured_missing_ca_dir_fails_to_load() {
for mode in [TlsTrustMode::WebPki, TlsTrustMode::CustomOnly] {
let error = TlsTrustSettings::with_root_ca_dir(test_dir("footing-tls-missing"))
.with_mode(mode)
.build()
.unwrap()
.load()
.unwrap_err();
assert!(matches!(error, TlsTrustError::ReadRootCaDir { source, .. }
if source.kind() == std::io::ErrorKind::NotFound));
}
}
#[test]
fn trust_config_validation_rejects_relative_dir() {
let error = TlsTrustSettings::with_root_ca_dir("config/ca.d")
.validate()
.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 = TlsTrustSettings::with_root_ca_dir(private_path);
let error = config
.clone()
.build()
.expect_err("relative path should fail");
let output = format!("{config:?} {error:?} {error}");
assert!(output.contains("tls.root_ca_dir"));
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 = config_with_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 = config_with_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 = config_with_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 = config_with_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 error = super::append_root_ca_file(&ca_file, &mut bundle)
.expect_err("oversized bundle should fail");
assert!(matches!(error, TlsTrustError::RootCaBundleTooLarge { .. }));
assert_eq!(bundle.len(), MAX_ROOT_CA_BUNDLE_BYTES);
fs::remove_file(&ca_file).expect("root should be removed");
}
#[cfg(feature = "tls-reqx")]
#[test]
fn reqx_adapter_builds_webpki_client_and_rejects_invalid_custom_roots() {
TlsTrustConfig::webpki_only()
.load()
.expect("WebPKI trust must load")
.validate_reqx()
.expect("WebPKI-only Reqx client must build");
let ca_dir = test_dir("footing-tls-reqx-invalid");
fs::create_dir_all(&ca_dir).expect("test dir should be created");
fs::write(ca_dir.join("invalid.pem"), "not a certificate")
.expect("invalid root fixture should be written");
for mode in [TlsTrustMode::WebPki, TlsTrustMode::CustomOnly] {
let loaded = TlsTrustSettings::with_root_ca_dir(&ca_dir)
.with_mode(mode)
.build()
.unwrap()
.load()
.expect("bounded root bundle should load before TLS parsing");
loaded
.validate_reqx()
.expect_err("Reqx must reject invalid root certificate material in both modes");
}
fs::remove_dir_all(&ca_dir).expect("test dir should be removed");
}
#[cfg(feature = "tls-reqx")]
#[test]
fn reqx_adapter_applies_the_trust_mode_to_the_actual_backend() {
let ca_dir = test_dir("footing-tls-reqx-modes");
fs::create_dir_all(&ca_dir).unwrap();
fs::write(ca_dir.join("root.pem"), TEST_CA_PEM).unwrap();
for mode in [TlsTrustMode::WebPki, TlsTrustMode::CustomOnly] {
let loaded = TlsTrustSettings::with_root_ca_dir(&ca_dir)
.with_mode(mode)
.build()
.unwrap()
.load()
.unwrap();
assert_eq!(loaded.mode(), mode);
assert_eq!(loaded.root_ca_source_count(), 1);
loaded.validate_reqx().unwrap();
let without_custom_roots = loaded
.apply_to_reqx_builder(reqx::Client::builder("https://example.invalid"))
.clear_tls_root_cas()
.build();
assert_eq!(without_custom_roots.is_ok(), mode == TlsTrustMode::WebPki);
}
fs::remove_dir_all(ca_dir).unwrap();
}
fn test_dir(name: &str) -> PathBuf {
std::env::temp_dir().join(format!("{name}-{}", std::process::id()))
}
}