footing 0.6.2

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
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
//! Secret and redaction primitives.
//!
//! These types make accidental logging safer by redacting `Debug` and `Display`
//! output while still allowing explicit access at integration boundaries.
//!
//! ```rust
//! use footing::secret::{ExposeSecret, SecretString};
//!
//! let secret = SecretString::new("database-password");
//! assert_eq!(secret.expose_secret(), "database-password");
//! assert_eq!(format!("{secret:?}"), "[REDACTED]");
//! ```
//!
use std::{
    env,
    error::Error,
    fmt, fs,
    io::Read,
    path::{Path, PathBuf},
};

use serde::{Deserialize, Deserializer};
use zeroize::{Zeroize, Zeroizing};

use crate::result::{ClassifyError, ErrorKind};

/// Placeholder used by redacted debug/display output.
pub const REDACTED: &str = "[REDACTED]";
/// Maximum size accepted by [`SecretSource::file`].
pub const MAX_SECRET_FILE_BYTES: u64 = 64 * 1024;

/// Explicit access to wrapped secret material.
pub trait ExposeSecret<T: ?Sized> {
    /// Returns the underlying secret.
    fn expose_secret(&self) -> &T;
}

/// A UTF-8 secret string that redacts debug and display output.
///
/// Deserialization failures use a fixed message to avoid exposing rejected values.
///
/// This type intentionally implements [`Deserialize`] but not
/// [`serde::Serialize`]. Serializing secret material requires explicitly
/// exposing it at the call site:
///
/// ```rust
/// use footing::secret::{ExposeSecret, SecretString};
///
/// let secret = SecretString::new("database-password");
/// let json = serde_json::to_string(secret.expose_secret()).unwrap();
/// assert_eq!(json, r#""database-password""#);
/// ```
///
/// ```compile_fail
/// use footing::secret::SecretString;
///
/// let secret = SecretString::new("database-password");
/// let _ = serde_json::to_string(&secret);
/// ```
#[derive(Clone, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[non_exhaustive]
pub struct SecretString {
    value: String,
}

impl SecretString {
    /// Creates a new secret string.
    #[must_use]
    pub fn new(value: impl Into<String>) -> Self {
        Self {
            value: value.into(),
        }
    }

    /// Consumes the wrapper and returns the secret value.
    #[must_use]
    pub fn into_secret(mut self) -> String {
        std::mem::take(&mut self.value)
    }

    /// Returns true when the secret is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.value.is_empty()
    }
}

impl Drop for SecretString {
    fn drop(&mut self) {
        self.value.zeroize();
    }
}

impl ExposeSecret<str> for SecretString {
    fn expose_secret(&self) -> &str {
        &self.value
    }
}

impl From<String> for SecretString {
    fn from(value: String) -> Self {
        Self::new(value)
    }
}

impl From<&str> for SecretString {
    fn from(value: &str) -> Self {
        Self::new(value)
    }
}

impl fmt::Debug for SecretString {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(REDACTED)
    }
}

impl fmt::Display for SecretString {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(REDACTED)
    }
}

impl<'de> Deserialize<'de> for SecretString {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        String::deserialize(deserializer)
            .map(Self::new)
            // A type error can include the rejected value, such as an unquoted
            // numeric password. Do not propagate that value into diagnostics.
            .map_err(|_| serde::de::Error::custom("secret must be a UTF-8 string"))
    }
}

/// Binary secret material that zeroizes memory on drop.
#[derive(Clone, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct SecretBytes {
    value: Vec<u8>,
}

impl SecretBytes {
    /// Creates a new binary secret.
    #[must_use]
    pub fn new(value: impl Into<Vec<u8>>) -> Self {
        Self {
            value: value.into(),
        }
    }

    /// Consumes the wrapper and returns the secret bytes.
    #[must_use]
    pub fn into_secret(mut self) -> Vec<u8> {
        std::mem::take(&mut self.value)
    }

    /// Returns true when the secret has no bytes.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.value.is_empty()
    }
}

impl Drop for SecretBytes {
    fn drop(&mut self) {
        self.value.zeroize();
    }
}

impl ExposeSecret<[u8]> for SecretBytes {
    fn expose_secret(&self) -> &[u8] {
        &self.value
    }
}

impl fmt::Debug for SecretBytes {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(REDACTED)
    }
}

impl fmt::Display for SecretBytes {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(REDACTED)
    }
}

/// Declarative source for a secret value.
///
/// This keeps configuration ergonomic while making application code consume a
/// single [`SecretString`] type. Exactly one of `inline`, `env`, or `file` must
/// be set. It intentionally does not implement [`serde::Serialize`] because an
/// inline source can contain secret material.
///
/// Structural deserialization failures use a fixed message; source validation
/// retains specific messages without input values. Surrounding configuration
/// parsers may attach their own input context.
#[derive(Clone, Eq, PartialEq)]
pub struct SecretSource(SecretSourceKind);

impl<'de> Deserialize<'de> for SecretSource {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let wire = SecretSourceWire::deserialize(deserializer).map_err(|_| {
            <D::Error as serde::de::Error>::custom(
                "invalid secret source structure; expected inline, env, or file string fields",
            )
        })?;
        Self::try_from(wire).map_err(serde::de::Error::custom)
    }
}

#[derive(Clone, Eq, PartialEq)]
enum SecretSourceKind {
    Inline(SecretString),
    Env(String),
    File(PathBuf),
}

impl SecretSource {
    /// Creates a source containing an inline secret value.
    pub fn inline(value: impl Into<String>) -> Result<Self, SecretSourceError> {
        Self::from_inline(SecretString::new(value))
    }

    /// Creates a source that resolves a secret from an environment variable.
    pub fn env(name: impl Into<String>) -> Result<Self, SecretSourceError> {
        let name = name.into().trim().to_owned();
        validate_secret_env_name(&name)?;
        Ok(Self(SecretSourceKind::Env(name)))
    }

    /// Creates a source that resolves a secret from a file.
    pub fn file(path: impl Into<PathBuf>) -> Result<Self, SecretSourceError> {
        let path = path.into();
        validate_secret_file_path(&path)?;
        Ok(Self(SecretSourceKind::File(path)))
    }

    #[must_use]
    /// Returns the inline value.
    pub fn inline_value(&self) -> Option<&SecretString> {
        match &self.0 {
            SecretSourceKind::Inline(value) => Some(value),
            _ => None,
        }
    }

    #[must_use]
    /// Returns the env name.
    pub fn env_name(&self) -> Option<&str> {
        match &self.0 {
            SecretSourceKind::Env(name) => Some(name),
            _ => None,
        }
    }

    #[must_use]
    /// Returns the file path.
    pub fn file_path(&self) -> Option<&Path> {
        match &self.0 {
            SecretSourceKind::File(path) => Some(path),
            _ => None,
        }
    }

    /// Resolves a nonempty secret that is not the redaction placeholder.
    /// File sources remove a single trailing newline before validation;
    /// otherwise all sources preserve the exact secret contents.
    /// File paths must resolve to regular files; symlinks to regular files are supported.
    pub fn resolve(&self) -> Result<SecretString, SecretSourceError> {
        let value = match &self.0 {
            SecretSourceKind::Inline(value) => value.clone(),
            SecretSourceKind::Env(name) => {
                env::var(name)
                    .map(SecretString::new)
                    .map_err(|source| match source {
                        env::VarError::NotPresent => SecretSourceError::EnvNotPresent {
                            name: name.to_owned(),
                        },
                        env::VarError::NotUnicode(value) => {
                            value.into_encoded_bytes().zeroize();
                            SecretSourceError::EnvInvalidUnicode {
                                name: name.to_owned(),
                            }
                        }
                    })?
            }
            SecretSourceKind::File(path) => {
                let value = read_secret_file(path)?;
                SecretString::new(strip_single_trailing_newline(value))
            }
        };
        validate_secret_value(&value)?;
        Ok(value)
    }

    fn from_inline(value: SecretString) -> Result<Self, SecretSourceError> {
        validate_secret_value(&value)?;
        Ok(Self(SecretSourceKind::Inline(value)))
    }
}

fn validate_secret_value(value: &SecretString) -> Result<(), SecretSourceError> {
    if value.is_empty() {
        Err(SecretSourceError::EmptySecret)
    } else if value.expose_secret() == REDACTED {
        Err(SecretSourceError::RedactedSecret)
    } else {
        Ok(())
    }
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SecretSourceWire {
    #[serde(default)]
    inline: Option<SecretString>,
    #[serde(default)]
    env: Option<String>,
    #[serde(default)]
    file: Option<PathBuf>,
}

impl TryFrom<SecretSourceWire> for SecretSource {
    type Error = SecretSourceError;

    fn try_from(value: SecretSourceWire) -> Result<Self, Self::Error> {
        match (value.inline, value.env, value.file) {
            (Some(value), None, None) => Self::from_inline(value),
            (None, Some(name), None) => Self::env(name),
            (None, None, Some(path)) => Self::file(path),
            (None, None, None) => Err(SecretSourceError::MissingSource),
            _ => Err(SecretSourceError::AmbiguousSource),
        }
    }
}

impl fmt::Debug for SecretSource {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SecretSource")
            .field("kind", &self.kind())
            .finish_non_exhaustive()
    }
}

impl SecretSource {
    fn kind(&self) -> &'static str {
        match &self.0 {
            SecretSourceKind::Inline(_) => "inline",
            SecretSourceKind::Env(_) => "env",
            SecretSourceKind::File(_) => "file",
        }
    }
}

#[non_exhaustive]
/// Errors that can occur while handling secret source.
pub enum SecretSourceError {
    /// The required source is missing.
    MissingSource,
    /// Indicates ambiguous source.
    AmbiguousSource,
    /// The resolved secret is empty.
    EmptySecret,
    /// The resolved secret is the redaction placeholder.
    RedactedSecret,
    /// The env name is empty.
    EmptyEnvName,
    /// The env name is invalid.
    InvalidEnvName,
    /// The file path is empty.
    EmptyFilePath,
    /// The configured environment variable is absent.
    EnvNotPresent {
        /// The configured variable name.
        name: String,
    },
    /// The environment value is not valid Unicode. Its contents are not retained.
    EnvInvalidUnicode {
        /// The configured variable name.
        name: String,
    },
    /// Indicates file.
    File {
        /// The affected path.
        path: PathBuf,
        /// The source value.
        source: std::io::Error,
    },
    /// The file exceeds the supported size.
    FileTooLarge {
        /// The affected path.
        path: PathBuf,
        /// The maximum number of bytes.
        max_bytes: u64,
    },
    /// Indicates file invalid UTF-8.
    FileInvalidUtf8 {
        /// The affected path.
        path: PathBuf,
        /// Encoding error metadata without the secret contents.
        source: std::str::Utf8Error,
    },
}

impl fmt::Debug for SecretSourceError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SecretSourceError")
            .field("code", &self.error_code())
            .finish_non_exhaustive()
    }
}

impl fmt::Display for SecretSourceError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingSource => formatter.write_str("secret source must be configured"),
            Self::AmbiguousSource => {
                formatter.write_str("secret source must set exactly one of inline, env, or file")
            }
            Self::EmptySecret => formatter.write_str("secret must not be empty"),
            Self::RedactedSecret => {
                formatter.write_str("secret must not be the redaction placeholder")
            }
            Self::EmptyEnvName => formatter.write_str("secret env var name must not be empty"),
            Self::InvalidEnvName => formatter.write_str(
                "secret env var name must start with ASCII letter or '_' and contain only ASCII letters, digits, or '_'",
            ),
            Self::EmptyFilePath => formatter.write_str("secret file path must not be empty"),
            Self::EnvNotPresent { .. } => {
                formatter.write_str("configured secret env var is not set")
            }
            Self::EnvInvalidUnicode { .. } => {
                formatter.write_str("configured secret env var is not valid Unicode")
            }
            Self::File { .. } => formatter.write_str("failed to read configured secret file"),
            Self::FileTooLarge { max_bytes, .. } => write!(
                formatter,
                "configured secret file exceeds the maximum size of {max_bytes} bytes"
            ),
            Self::FileInvalidUtf8 { .. } => {
                formatter.write_str("configured secret file is not valid UTF-8")
            }
        }
    }
}

impl Error for SecretSourceError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::File { source, .. } => Some(source),
            Self::FileInvalidUtf8 { source, .. } => Some(source),
            Self::MissingSource
            | Self::AmbiguousSource
            | Self::EmptySecret
            | Self::RedactedSecret
            | Self::EmptyEnvName
            | Self::InvalidEnvName
            | Self::EmptyFilePath
            | Self::EnvNotPresent { .. }
            | Self::EnvInvalidUnicode { .. }
            | Self::FileTooLarge { .. } => None,
        }
    }
}

impl ClassifyError for SecretSourceError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::MissingSource
            | Self::AmbiguousSource
            | Self::EmptySecret
            | Self::RedactedSecret
            | Self::EmptyEnvName
            | Self::InvalidEnvName
            | Self::EmptyFilePath
            | Self::EnvInvalidUnicode { .. }
            | Self::FileTooLarge { .. }
            | Self::FileInvalidUtf8 { .. } => ErrorKind::Validation,
            Self::EnvNotPresent { .. } | Self::File { .. } => ErrorKind::Dependency,
        }
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::MissingSource => "secret_source_missing",
            Self::AmbiguousSource => "secret_source_ambiguous",
            Self::EmptySecret => "secret_empty",
            Self::RedactedSecret => "secret_redacted",
            Self::EmptyEnvName => "secret_env_name_empty",
            Self::InvalidEnvName => "secret_env_name_invalid",
            Self::EmptyFilePath => "secret_file_path_empty",
            Self::EnvNotPresent { .. } => "secret_env_unavailable",
            Self::EnvInvalidUnicode { .. } => "secret_env_invalid_unicode",
            Self::File { .. } => "secret_file_unavailable",
            Self::FileTooLarge { .. } => "secret_file_too_large",
            Self::FileInvalidUtf8 { .. } => "secret_file_invalid_utf8",
        })
    }
}

fn read_secret_file(path: &Path) -> Result<String, SecretSourceError> {
    // Follow mounted secret symlinks, rejecting pipes and devices before opening
    // because their reads or open calls can wait indefinitely for a producer.
    let metadata = fs::metadata(path).map_err(|source| SecretSourceError::File {
        path: path.to_owned(),
        source,
    })?;
    if !metadata.is_file() {
        return Err(SecretSourceError::File {
            path: path.to_owned(),
            source: std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "secret source must be a regular file",
            ),
        });
    }
    let file = fs::File::open(path).map_err(|source| SecretSourceError::File {
        path: path.to_owned(),
        source,
    })?;
    let mut bytes = Zeroizing::new(Vec::with_capacity(MAX_SECRET_FILE_BYTES as usize + 1));
    file.take(MAX_SECRET_FILE_BYTES + 1)
        .read_to_end(&mut bytes)
        .map_err(|source| SecretSourceError::File {
            path: path.to_owned(),
            source,
        })?;
    if bytes.len() as u64 > MAX_SECRET_FILE_BYTES {
        return Err(SecretSourceError::FileTooLarge {
            path: path.to_owned(),
            max_bytes: MAX_SECRET_FILE_BYTES,
        });
    }

    std::str::from_utf8(&bytes)
        .map(str::to_owned)
        .map_err(|source| SecretSourceError::FileInvalidUtf8 {
            path: path.to_owned(),
            source,
        })
}

fn validate_secret_env_name(name: &str) -> Result<(), SecretSourceError> {
    let name = name.trim();
    if name.is_empty() {
        return Err(SecretSourceError::EmptyEnvName);
    }

    let mut bytes = name.bytes();
    let Some(first) = bytes.next() else {
        return Err(SecretSourceError::EmptyEnvName);
    };
    if !(first.is_ascii_alphabetic() || first == b'_') {
        return Err(SecretSourceError::InvalidEnvName);
    }
    if !bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') {
        return Err(SecretSourceError::InvalidEnvName);
    }

    Ok(())
}

fn validate_secret_file_path(path: &Path) -> Result<(), SecretSourceError> {
    if path.as_os_str().is_empty() {
        Err(SecretSourceError::EmptyFilePath)
    } else {
        Ok(())
    }
}

fn strip_single_trailing_newline(mut value: String) -> String {
    if value.ends_with('\n') {
        value.pop();
        if value.ends_with('\r') {
            value.pop();
        }
    }
    value
}

/// A generic value wrapper that redacts debug and display output.
#[derive(Clone, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[non_exhaustive]
pub struct Redacted<T> {
    value: T,
}

impl<T> Redacted<T> {
    /// Wraps a value.
    #[must_use]
    pub fn new(value: T) -> Self {
        Self { value }
    }

    /// Returns a reference to the wrapped value.
    #[must_use]
    pub const fn expose(&self) -> &T {
        &self.value
    }

    /// Consumes the wrapper and returns the wrapped value.
    #[must_use]
    pub fn into_inner(self) -> T {
        self.value
    }
}

impl<T> fmt::Debug for Redacted<T> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(REDACTED)
    }
}

impl<T> fmt::Display for Redacted<T> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(REDACTED)
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::{
        ExposeSecret, MAX_SECRET_FILE_BYTES, Redacted, SecretSource, SecretSourceError,
        SecretString,
    };
    use crate::result::{ClassifyError, ErrorKind};

    #[test]
    fn secret_string_redacts_formatting_and_requires_explicit_exposure() {
        let secret = SecretString::new("secret-value");

        assert_eq!(secret.expose_secret(), "secret-value");
        assert_eq!(format!("{secret:?}"), "[REDACTED]");
        assert_eq!(format!("{secret}"), "[REDACTED]");
        assert_eq!(
            serde_json::to_value(secret.expose_secret()).unwrap(),
            json!("secret-value")
        );

        let deserialized: SecretString = serde_json::from_value(json!("loaded-secret")).unwrap();
        assert_eq!(deserialized.expose_secret(), "loaded-secret");
    }

    #[test]
    fn redacted_wrapper_keeps_explicit_access() {
        let value = Redacted::new("postgres://user:password@localhost/db");

        assert_eq!(*value.expose(), "postgres://user:password@localhost/db");
        assert_eq!(format!("{value:?}"), "[REDACTED]");
    }

    #[test]
    fn secret_source_resolves_inline_without_exposing_debug_value() {
        let source = SecretSource::inline("secret-value").unwrap();

        assert_eq!(source.resolve().unwrap().expose_secret(), "secret-value");
        assert!(!format!("{source:?}").contains("secret-value"));
    }

    #[test]
    fn secret_source_reads_file_and_strips_one_trailing_newline() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("secret.txt");
        std::fs::write(&path, "secret-value\n").unwrap();
        let source = SecretSource::file(&path).unwrap();

        assert_eq!(source.resolve().unwrap().expose_secret(), "secret-value");
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn secret_file_resolution_rejects_pipes_without_waiting_for_the_writer() {
        use std::{os::fd::AsRawFd, sync::mpsc, time::Duration};

        let (reader, writer) = std::io::pipe().unwrap();
        let path = format!("/proc/self/fd/{}", reader.as_raw_fd());
        let source = SecretSource::file(path).unwrap();
        let (sender, receiver) = mpsc::channel();
        let resolving = std::thread::spawn(move || {
            sender.send(source.resolve()).unwrap();
        });
        let result = receiver.recv_timeout(Duration::from_secs(1));
        // Release the pre-fix reader before asserting, including on timeout.
        drop(writer);
        resolving.join().unwrap();
        drop(reader);

        assert!(result.is_ok(), "secret resolution waited for a pipe writer");
        assert!(matches!(
            result.unwrap(),
            Err(SecretSourceError::File { source, .. })
                if source.kind() == std::io::ErrorKind::InvalidInput
        ));
    }

    #[test]
    #[cfg(unix)]
    fn secret_file_resolution_accepts_symlinks_to_regular_files() {
        let directory = tempfile::tempdir().unwrap();
        std::fs::write(directory.path().join("mounted"), "secret-value\n").unwrap();
        std::os::unix::fs::symlink("mounted", directory.path().join("secret")).unwrap();
        let result = SecretSource::file(directory.path().join("secret"))
            .unwrap()
            .resolve();

        assert_eq!(result.unwrap().expose_secret(), "secret-value");
    }

    #[test]
    fn secret_source_file_resolution_rejects_oversized_and_invalid_utf8_files() {
        let directory = tempfile::tempdir().unwrap();
        let oversized_path = directory.path().join("oversized.txt");
        std::fs::write(
            &oversized_path,
            vec![b'a'; MAX_SECRET_FILE_BYTES as usize + 1],
        )
        .unwrap();
        let error = SecretSource::file(&oversized_path)
            .unwrap()
            .resolve()
            .expect_err("oversized file should fail");
        assert!(matches!(error, SecretSourceError::FileTooLarge { .. }));
        assert_eq!(error.error_kind(), ErrorKind::Validation);
        assert_eq!(error.error_code(), "secret_file_too_large");
        let utf8_path = directory.path().join("invalid-utf8.txt");
        std::fs::write(&utf8_path, [0xff, 0xfe]).unwrap();
        let error = SecretSource::file(&utf8_path)
            .unwrap()
            .resolve()
            .expect_err("invalid UTF-8 file should fail");
        assert!(matches!(error, SecretSourceError::FileInvalidUtf8 { .. }));
        assert_eq!(error.error_kind(), ErrorKind::Validation);
        assert_eq!(error.error_code(), "secret_file_invalid_utf8");
    }

    #[test]
    fn secret_source_requires_exactly_one_source() {
        let missing = serde_json::from_value::<SecretSource>(json!({}))
            .expect_err("missing source should fail during deserialization");
        assert!(missing.to_string().contains("must be configured"));

        let error = serde_json::from_value::<SecretSource>(json!({
            "inline": "secret",
            "env": "SECRET"
        }))
        .expect_err("ambiguous source should fail during deserialization");
        assert!(error.to_string().contains("exactly one"));
    }

    #[test]
    fn secret_source_validates_selected_source_shape() {
        assert_eq!(
            SecretSource::env(" SECRET ").unwrap().env_name(),
            Some("SECRET")
        );
        assert!(matches!(
            SecretSource::inline(""),
            Err(SecretSourceError::EmptySecret)
        ));
        assert!(matches!(
            SecretSource::inline("[REDACTED]"),
            Err(SecretSourceError::RedactedSecret)
        ));
        assert!(matches!(
            SecretSource::env(" "),
            Err(SecretSourceError::EmptyEnvName)
        ));
        assert!(matches!(
            SecretSource::env("1SECRET"),
            Err(SecretSourceError::InvalidEnvName)
        ));
        assert!(matches!(
            SecretSource::file(""),
            Err(SecretSourceError::EmptyFilePath)
        ));
        assert!(serde_json::from_value::<SecretSource>(json!({ "env": "bad-name" })).is_err());
        assert!(serde_json::from_value::<SecretSource>(json!({ "inline": "[REDACTED]" })).is_err());
    }

    #[test]
    fn file_sources_reject_empty_and_redacted_contents() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("secret.txt");
        for value in ["", "\n", "\r\n", "[REDACTED]", "[REDACTED]\n"] {
            std::fs::write(&path, value).unwrap();
            let error = SecretSource::file(&path).unwrap().resolve().unwrap_err();
            assert_eq!(error.error_kind(), ErrorKind::Validation);
            assert!(matches!(
                error,
                SecretSourceError::EmptySecret | SecretSourceError::RedactedSecret
            ));
        }
        std::fs::write(&path, " secret \r\n").unwrap();
        assert_eq!(
            SecretSource::file(&path)
                .unwrap()
                .resolve()
                .unwrap()
                .expose_secret(),
            " secret "
        );
    }

    #[test]
    fn env_sources_validate_resolved_contents() {
        const NAME: &str = "FOOTING_TEST_SECRET_VALIDATION";
        if let Ok(value) = std::env::var(NAME) {
            let result = SecretSource::env(NAME).unwrap().resolve();
            match value.as_str() {
                "" => assert!(matches!(result, Err(SecretSourceError::EmptySecret))),
                "[REDACTED]" => assert!(matches!(result, Err(SecretSourceError::RedactedSecret))),
                _ => assert_eq!(result.unwrap().expose_secret(), value),
            }
            return;
        }
        // Set only the child environment: mutating a multithreaded test process's
        // environment is unsafe on Unix.
        for value in ["", "[REDACTED]", " secret "] {
            let output = std::process::Command::new(std::env::current_exe().unwrap())
                .args([
                    "--exact",
                    "secret::tests::env_sources_validate_resolved_contents",
                ])
                .env(NAME, value)
                .output()
                .unwrap();
            assert!(
                output.status.success(),
                "{}",
                String::from_utf8_lossy(&output.stdout)
            );
        }
    }

    #[test]
    #[cfg(unix)]
    fn non_unicode_env_errors_do_not_expose_secret_contents_through_sources() {
        use std::{error::Error as _, ffi::OsString, os::unix::ffi::OsStringExt};

        const NAME: &str = "FOOTING_TEST_NON_UNICODE_SECRET";
        if std::env::var_os(NAME).is_some() {
            let error = SecretSource::env(NAME).unwrap().resolve().unwrap_err();
            assert!(matches!(error, SecretSourceError::EnvInvalidUnicode { .. }));
            assert_eq!(error.error_code(), "secret_env_invalid_unicode");
            assert!(error.source().is_none());
            let output = format!("{error} {error:?}");
            assert!(!output.contains("private-secret-bytes"));
            return;
        }
        let output = std::process::Command::new(std::env::current_exe().unwrap())
            .args([
                "--exact",
                "secret::tests::non_unicode_env_errors_do_not_expose_secret_contents_through_sources",
            ])
            .env(NAME, OsString::from_vec(b"private-secret-bytes\xff".to_vec()))
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stdout)
        );
    }

    #[test]
    fn secret_deserialization_errors_do_not_include_rejected_values() {
        let secret = "1234567890123456";
        let error = serde_json::from_str::<SecretString>(secret).unwrap_err();
        assert!(!format!("{error} {error:?}").contains(secret));

        let error = serde_json::from_value::<SecretSource>(json!({
            "inline": 1_234_567_890_123_456_u64,
        }))
        .unwrap_err();
        assert!(!format!("{error} {error:?}").contains(secret));
    }

    #[test]
    fn secret_source_deserialization_redacts_structural_errors() {
        for (input, secret) in [
            (r#""private-secret-value""#, "private-secret-value"),
            ("1234567890123456", "1234567890123456"),
            (
                r#"{"private-secret-value":"unused"}"#,
                "private-secret-value",
            ),
            (r#"{"env":1234567890123456}"#, "1234567890123456"),
            (r#"{"file":1234567890123456}"#, "1234567890123456"),
            (
                r#"["inline-secret",1234567890123456,null]"#,
                "1234567890123456",
            ),
        ] {
            let value = serde_json::from_str(input).unwrap();
            for error in [
                serde_json::from_str::<SecretSource>(input).unwrap_err(),
                serde_json::from_value::<SecretSource>(value).unwrap_err(),
            ] {
                for output in [
                    error.to_string(),
                    format!("{error:?}"),
                    format!("{error:#?}"),
                ] {
                    assert!(!output.contains(secret));
                }
            }
        }
    }

    #[test]
    fn secret_source_deserialization_preserves_specific_validation_errors() {
        for (value, expected) in [
            (json!({}), "secret source must be configured"),
            (
                json!({"inline": "secret", "env": "SECRET"}),
                "secret source must set exactly one of inline, env, or file",
            ),
            (json!({"inline": ""}), "secret must not be empty"),
            (
                json!({"inline": "[REDACTED]"}),
                "secret must not be the redaction placeholder",
            ),
            (
                json!({"env": "bad-name"}),
                "secret env var name must start with ASCII letter or '_' and contain only ASCII letters, digits, or '_'",
            ),
        ] {
            let error = serde_json::from_value::<SecretSource>(value).unwrap_err();
            assert_eq!(error.to_string(), expected);
        }
    }

    #[test]
    fn secret_source_deserialization_preserves_struct_sequences() {
        let expected = SecretSource::inline("inline-secret").unwrap();
        let json: SecretSource = serde_json::from_str(r#"["inline-secret"]"#).unwrap();
        assert_eq!(json, expected);

        let bytes =
            postcard::to_allocvec(&(Some("inline-secret"), None::<&str>, None::<&str>)).unwrap();
        let binary: SecretSource = postcard::from_bytes(&bytes).unwrap();
        assert_eq!(binary, expected);
    }

    #[test]
    fn secret_source_errors_are_classified() {
        let missing = SecretSourceError::MissingSource;

        assert_eq!(missing.error_kind(), ErrorKind::Validation);
        assert_eq!(missing.error_code(), "secret_source_missing");

        let file = SecretSource::file("/path/that/does/not/exist")
            .unwrap()
            .resolve()
            .expect_err("missing file should fail");

        assert_eq!(file.error_kind(), ErrorKind::Dependency);
        assert_eq!(file.error_code(), "secret_file_unavailable");
    }

    #[test]
    fn secret_source_errors_redact_locations_and_source_bytes() {
        let env_name = "PRIVATE_DATABASE_PASSWORD";
        let env_error = SecretSourceError::EnvNotPresent {
            name: env_name.to_owned(),
        };
        let path = std::path::PathBuf::from("/private/secrets/database-password");
        let invalid_bytes = b"private-secret-bytes\xff".to_vec();
        let utf8_error = SecretSourceError::FileInvalidUtf8 {
            path: path.clone(),
            source: std::str::from_utf8(&invalid_bytes).unwrap_err(),
        };

        let source = std::error::Error::source(&utf8_error).unwrap();
        let output =
            format!("{env_error} {env_error:?} {utf8_error} {utf8_error:?} {source} {source:?}");
        assert!(output.contains("secret_env_unavailable"));
        assert!(output.contains("secret_file_invalid_utf8"));
        assert!(!output.contains(env_name));
        assert!(!output.contains(path.to_string_lossy().as_ref()));
        assert!(!output.contains("private-secret-bytes"));
        assert!(!output.contains(&format!("{invalid_bytes:?}")));
    }
}