footing 0.1.18

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

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.
///
/// 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(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 Clone for SecretString {
    fn clone(&self) -> Self {
        Self::new(self.value.clone())
    }
}

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)
    }
}

/// Binary secret material that zeroizes memory on drop.
#[derive(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 Clone for SecretBytes {
    fn clone(&self) -> Self {
        Self::new(self.value.clone())
    }
}

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.
#[derive(Clone, Eq, PartialEq, Deserialize)]
#[serde(try_from = "SecretSourceWire")]
pub struct SecretSource(SecretSourceKind);

#[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 the value.
    pub fn resolve(&self) -> Result<SecretString, SecretSourceError> {
        match &self.0 {
            SecretSourceKind::Inline(value) => Ok(value.clone()),
            SecretSourceKind::Env(name) => {
                env::var(name)
                    .map(SecretString::new)
                    .map_err(|source| SecretSourceError::Env {
                        name: name.to_owned(),
                        source,
                    })
            }
            SecretSourceKind::File(path) => {
                let value = read_secret_file(path)?;
                Ok(SecretString::new(strip_single_trailing_newline(value)))
            }
        }
    }

    fn from_inline(value: SecretString) -> Result<Self, SecretSourceError> {
        if value.is_empty() {
            return Err(SecretSourceError::EmptyInlineSecret);
        }
        if value.expose_secret() == REDACTED {
            return Err(SecretSourceError::RedactedInlineSecret);
        }
        Ok(Self(SecretSourceKind::Inline(value)))
    }
}

#[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 inline secret is empty.
    EmptyInlineSecret,
    /// Indicates redacted inline secret.
    RedactedInlineSecret,
    /// The env name is empty.
    EmptyEnvName,
    /// The env name is invalid.
    InvalidEnvName,
    /// The file path is empty.
    EmptyFilePath,
    /// Indicates env.
    Env {
        /// The name value.
        name: String,
        /// The source value.
        source: env::VarError,
    },
    /// 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,
        /// The source value.
        source: std::string::FromUtf8Error,
    },
}

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::EmptyInlineSecret => formatter.write_str("inline secret must not be empty"),
            Self::RedactedInlineSecret => {
                formatter.write_str("inline 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::Env { .. } => formatter.write_str("failed to read configured secret env var"),
            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::Env { source, .. } => Some(source),
            Self::File { source, .. } => Some(source),
            Self::FileInvalidUtf8 { source, .. } => Some(source),
            Self::MissingSource
            | Self::AmbiguousSource
            | Self::EmptyInlineSecret
            | Self::RedactedInlineSecret
            | Self::EmptyEnvName
            | Self::InvalidEnvName
            | Self::EmptyFilePath
            | Self::FileTooLarge { .. } => None,
        }
    }
}

impl ClassifyError for SecretSourceError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::MissingSource
            | Self::AmbiguousSource
            | Self::EmptyInlineSecret
            | Self::RedactedInlineSecret
            | Self::EmptyEnvName
            | Self::InvalidEnvName
            | Self::EmptyFilePath
            | Self::FileTooLarge { .. }
            | Self::FileInvalidUtf8 { .. } => ErrorKind::Validation,
            Self::Env { .. } | 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::EmptyInlineSecret => "secret_inline_empty",
            Self::RedactedInlineSecret => "secret_inline_redacted",
            Self::EmptyEnvName => "secret_env_name_empty",
            Self::InvalidEnvName => "secret_env_name_invalid",
            Self::EmptyFilePath => "secret_file_path_empty",
            Self::Env { .. } => "secret_env_unavailable",
            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> {
    let file = fs::File::open(path).map_err(|source| SecretSourceError::File {
        path: path.to_owned(),
        source,
    })?;
    let mut bytes = 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,
        });
    }

    String::from_utf8(bytes).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 path = std::env::temp_dir().join(format!(
            "footing-secret-source-{}-{}.txt",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::write(&path, "secret-value\n").unwrap();
        let source = SecretSource::file(&path).unwrap();

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

        let _ = std::fs::remove_file(path);
    }

    #[test]
    fn secret_source_file_resolution_rejects_oversized_and_invalid_utf8_files() {
        let oversized_path = std::env::temp_dir().join(format!(
            "footing-secret-source-oversized-{}-{}.txt",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        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 _ = std::fs::remove_file(&oversized_path);

        let utf8_path = std::env::temp_dir().join(format!(
            "footing-secret-source-invalid-utf8-{}-{}.txt",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        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");
        let _ = std::fs::remove_file(utf8_path);
    }

    #[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::EmptyInlineSecret)
        ));
        assert!(matches!(
            SecretSource::inline("[REDACTED]"),
            Err(SecretSourceError::RedactedInlineSecret)
        ));
        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 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::Env {
            name: env_name.to_owned(),
            source: std::env::VarError::NotPresent,
        };
        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: String::from_utf8(invalid_bytes.clone()).unwrap_err(),
        };

        let output = format!("{env_error} {env_error:?} {utf8_error} {utf8_error:?}");
        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:?}")));
    }
}