footing 0.1.13

Feature-gated foundations for Rust backend services
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
687
688
//! Outbound TLS trust configuration.
//!
//! The default policy is intentionally small: use bundled WebPKI roots and,
//! when present, append PEM roots from one mounted directory. This keeps
//! scratch-container deployments deterministic without relying on distribution
//! certificate stores.
//!
//! ```rust
//! use footing::tls::TlsTrustSettings;
//!
//! let config = TlsTrustSettings::default().build().unwrap();
//! assert_eq!(
//!     config.root_ca_dir().unwrap().to_string_lossy(),
//!     "/etc/pki/ca-trust/source/anchors"
//! );
//! ```

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},
};

const DEFAULT_ROOT_CA_DIR: &str = "/etc/pki/ca-trust/source/anchors";
const CA_FILE_EXTENSIONS: &[&str] = &["cer", "crt", "pem"];
/// Maximum number of directory entries inspected while loading custom roots.
pub const MAX_ROOT_CA_DIRECTORY_ENTRIES: usize = 1_024;
/// Maximum number of custom root CA files loaded from one directory.
pub const MAX_ROOT_CA_FILES: usize = 128;
/// Maximum size accepted for one custom root CA file.
pub const MAX_ROOT_CA_FILE_BYTES: usize = 1024 * 1024;
/// Maximum size accepted for the concatenated custom root CA bundle.
pub const MAX_ROOT_CA_BUNDLE_BYTES: usize = 8 * 1024 * 1024;

/// Unvalidated serializable outbound TLS trust settings.
#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct TlsTrustSettings {
    /// Optional directory containing `.pem`, `.crt`, or `.cer` root CA files.
    ///
    /// Missing directories are ignored so images can use the same default
    /// configuration with or without an internal CA mount.
    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("custom_root_ca_dir", &self.root_ca_dir.is_some())
            .finish()
    }
}

impl Default for TlsTrustSettings {
    fn default() -> Self {
        Self {
            root_ca_dir: default_root_ca_dir(),
        }
    }
}

impl TlsTrustSettings {
    /// Creates WebPKI-only trust settings.
    #[must_use]
    pub const fn webpki_only() -> Self {
        Self { root_ca_dir: None }
    }

    /// Creates WebPKI trust settings with a mounted CA directory.
    #[must_use]
    pub fn with_root_ca_dir(path: impl Into<PathBuf>) -> Self {
        Self {
            root_ca_dir: Some(path.into()),
        }
    }

    /// Builds immutable TLS trust configuration.
    pub fn build(self) -> Result<TlsTrustConfig, SettingsValidationError> {
        self.validate()?;
        Ok(TlsTrustConfig {
            root_ca_dir: self.root_ca_dir,
        })
    }

    /// Validates path shape without touching the filesystem.
    pub fn validate(&self) -> Result<(), SettingsValidationError> {
        self.validate_at("tls")
    }

    pub(crate) fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
        let path = normalize_path(path);
        let mut issues = SettingsIssues::new();
        if let Some(root_ca_dir) = self.root_ca_dir.as_deref() {
            validate_path_shape(&mut issues, format!("{path}.root_ca_dir"), root_ca_dir);
        }
        issues.into_result()
    }
}

/// Validated immutable outbound TLS trust configuration.
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct TlsTrustConfig {
    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 {
    /// Creates validated WebPKI-only trust configuration.
    #[must_use]
    pub const fn webpki_only() -> Self {
        Self { root_ca_dir: None }
    }

    /// Returns the configured CA directory.
    #[must_use]
    pub fn root_ca_dir(&self) -> Option<&Path> {
        self.root_ca_dir.as_deref()
    }

    /// Loads additional PEM roots from the configured directory.
    pub fn load(&self) -> Result<LoadedTlsTrust, TlsTrustError> {
        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()),
        })
    }
}

/// Loaded outbound TLS trust material.
#[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 {
    /// Concatenated PEM root CA bundle, if custom roots were loaded.
    #[must_use]
    pub fn root_ca_pem(&self) -> Option<&[u8]> {
        self.root_ca_pem.as_deref()
    }

    /// Number of files that contributed custom root CA material.
    #[must_use]
    pub fn root_ca_source_count(&self) -> usize {
        self.root_ca_sources.len()
    }

    /// Files that contributed custom root CA material.
    #[must_use]
    pub fn root_ca_sources(&self) -> &[PathBuf] {
        &self.root_ca_sources
    }
}

/// TLS trust loading error.
#[derive(Error)]
#[non_exhaustive]
pub enum TlsTrustError {
    #[error("TLS root CA directory path must point to a directory")]
    /// Indicates root CA dir not directory.
    RootCaDirNotDirectory {
        #[doc = "The affected path."]
        path: PathBuf,
    },
    #[error("TLS root CA file is empty")]
    /// The root CA file is empty.
    EmptyRootCaFile {
        #[doc = "The affected path."]
        path: PathBuf,
    },
    #[error("TLS root CA directory contains too many entries")]
    /// The directory exceeds the bounded scan limit.
    TooManyRootCaDirectoryEntries {
        #[doc = "The configured upper bound."]
        max: usize,
    },
    #[error("TLS root CA directory contains too many CA files")]
    /// The directory exceeds the custom CA file limit.
    TooManyRootCaFiles {
        #[doc = "The configured upper bound."]
        max: usize,
    },
    #[error("TLS root CA file is too large")]
    /// One custom CA file exceeds the byte limit.
    RootCaFileTooLarge {
        #[doc = "The affected path."]
        path: PathBuf,
        #[doc = "The configured upper bound."]
        max_bytes: usize,
    },
    #[error("TLS root CA bundle is too large")]
    /// The combined custom CA bundle exceeds the byte limit.
    RootCaBundleTooLarge {
        #[doc = "The configured upper bound."]
        max_bytes: usize,
    },
    #[error("failed to read TLS root CA file")]
    /// Indicates read root CA file.
    ReadRootCaFile {
        /// The affected path.
        path: PathBuf,
        #[source]
        /// The source value.
        source: io::Error,
    },
    #[error("failed to read TLS root CA directory")]
    /// Indicates read root CA dir.
    ReadRootCaDir {
        /// The affected path.
        path: PathBuf,
        #[source]
        /// The source value.
        source: io::Error,
    },
    #[error("failed to read TLS root CA directory entry")]
    /// Indicates read root CA dir entry.
    ReadRootCaDirEntry {
        /// The affected path.
        path: PathBuf,
        #[source]
        /// The source value.
        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::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 {
    /// Applies WebPKI plus optional custom roots to a Reqx async builder.
    #[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
        }
    }

    /// Builds a throwaway Reqx client to validate TLS root material eagerly.
    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> {
    let metadata = match fs::metadata(path) {
        Ok(metadata) => metadata,
        Err(source) if source.kind() == io::ErrorKind::NotFound => return Ok(()),
        Err(source) => {
            return Err(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_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)
}

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, TlsTrustSettings,
    };

    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]
    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 = config_with_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 = 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 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");
    }

    #[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");
        let loaded = config_with_ca_dir(&ca_dir)
            .load()
            .expect("bounded root bundle should load before TLS parsing");

        loaded
            .validate_reqx()
            .expect_err("Reqx must reject invalid root certificate material");
        fs::remove_dir_all(&ca_dir).expect("test dir should be removed");
    }

    fn test_dir(name: &str) -> PathBuf {
        std::env::temp_dir().join(format!("{name}-{}", std::process::id()))
    }
}