footing 0.4.1

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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
//! Outbound TLS trust configuration.
//!
//! The default policy uses bundled WebPKI roots. Applications can explicitly
//! append PEM roots from a mounted directory; configured directories must exist
//! and be readable. [`TlsTrustMode::CustomOnly`] instead trusts only the supplied
//! roots and requires a nonempty CA directory. No filesystem location is inspected
//! implicitly, and failed custom-root loading never falls back to public roots.
//!
//! ```rust
//! use footing::tls::{TlsTrustMode, TlsTrustSettings};
//!
//! let config = TlsTrustSettings::default().build().unwrap();
//! assert!(config.root_ca_dir().is_none());
//! let internal = TlsTrustSettings::with_root_ca_dir("/run/certs/ca")
//!     .with_mode(TlsTrustMode::CustomOnly)
//!     .build().unwrap();
//! assert!(internal.root_ca_dir().is_some());
//! assert_eq!(internal.mode(), TlsTrustMode::CustomOnly);
//! ```

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

/// Certificate authorities trusted for outbound TLS connections.
#[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 {
    /// Bundled WebPKI roots plus any explicitly configured custom roots.
    #[default]
    #[serde(rename = "webpki")]
    WebPki,
    /// Only explicitly configured custom roots, excluding public and system roots.
    CustomOnly,
}

/// Unvalidated serializable outbound TLS trust settings.
#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct TlsTrustSettings {
    /// Trust policy; defaults to WebPKI plus optional custom roots.
    pub mode: TlsTrustMode,
    /// Optional directory containing `.pem`, `.crt`, or `.cer` root CA files.
    ///
    /// Required by [`TlsTrustMode::CustomOnly`]. A configured directory must
    /// exist and be readable when [`TlsTrustConfig::load`] is called.
    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 {
    /// Creates WebPKI-only trust settings.
    #[must_use]
    pub const fn webpki_only() -> Self {
        Self {
            mode: TlsTrustMode::WebPki,
            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 {
            mode: TlsTrustMode::WebPki,
            root_ca_dir: Some(path.into()),
        }
    }

    /// Selects the trusted roots. Custom-only mode requires a CA directory.
    #[must_use]
    pub const fn with_mode(mut self, mode: TlsTrustMode) -> Self {
        self.mode = mode;
        self
    }

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

    /// Validates the trust policy and 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();
        issues.require(
            self.mode != TlsTrustMode::CustomOnly || self.root_ca_dir.is_some(),
            format!("{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, format!("{path}.root_ca_dir"), root_ca_dir);
        }
        issues.into_result()
    }
}

/// Validated immutable outbound TLS trust configuration.
#[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 {
    /// Creates validated WebPKI-only trust configuration.
    #[must_use]
    pub const fn webpki_only() -> Self {
        Self {
            mode: TlsTrustMode::WebPki,
            root_ca_dir: None,
        }
    }

    /// Returns the configured trust policy.
    #[must_use]
    pub const fn mode(&self) -> TlsTrustMode {
        self.mode
    }

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

    /// Loads PEM roots from the configured directory.
    ///
    /// Missing or unreadable directories fail in both modes. CA paths must
    /// resolve to regular files; symlinks to regular files are supported.
    /// Custom-only mode also fails if no CA files are found. Certificate parsing
    /// and validation remain the responsibility of the TLS backend.
    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),
        })
    }
}

/// Loaded outbound TLS trust material.
#[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 {
    /// Returns the trust policy to apply with the loaded material.
    #[must_use]
    pub const fn mode(&self) -> TlsTrustMode {
        self.mode
    }

    /// 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("custom-only TLS trust requires at least one root CA file")]
    /// No custom root material was loaded for custom-only trust.
    MissingCustomRoots,
    #[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::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 {
    /// Applies the configured trust policy and loaded roots to a Reqx builder.
    ///
    /// Custom-only mode excludes bundled WebPKI and system roots. Explicit roots
    /// already present on the supplied builder are retained as custom roots.
    ///
    /// The transport type `T` is inferred from the supplied builder. For standalone
    /// method references, specify it explicitly, for example
    /// `LoadedTlsTrust::apply_to_reqx_builder::<reqx::advanced::AsyncTransportOptions>`.
    #[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
        }
    }

    /// 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>) -> 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> {
    // Follow mounted CA symlinks, but reject pipes and devices before opening:
    // their reads (or even open calls) can wait indefinitely for a producer.
    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)
}

fn normalize_path(path: &str) -> String {
    let path = path.trim();
    if path.is_empty() {
        "tls".to_owned()
    } else {
        path.to_owned()
    }
}

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

    // Self-signed P-256 CA used only to exercise local TLS client construction.
    // No private key is retained or needed by these tests.
    #[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));
        // Unblock the pre-fix loader before asserting so failure leaves no thread.
        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();

            // Removing explicit roots leaves WebPKI usable, but an actual
            // Specific root store must be rejected by Reqx as empty. This
            // distinguishes the applied modes without network requests.
            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()))
    }
}