Skip to main content

subspace_core/
secret.rs

1use std::fmt;
2
3use serde::Deserialize;
4
5/// A credential value. `Debug` and `Display` print `***`, so a secret cannot
6/// reach a log, an error message or the UI by formatting. It has no
7/// `Serialize`, so it cannot reach the state file either.
8#[derive(Clone, PartialEq, Eq, Deserialize)]
9#[serde(transparent)]
10pub struct Secret(String);
11
12impl Secret {
13    pub fn new(value: impl Into<String>) -> Self {
14        Self(value.into())
15    }
16
17    /// The value, for the one place that sends it: an `Authorization` header.
18    pub fn expose(&self) -> &str {
19        &self.0
20    }
21}
22
23impl fmt::Debug for Secret {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        f.write_str("***")
26    }
27}
28
29// qual:allow(dry, boilerplate) reason: "Credential Display deliberately writes only a fixed mask; the formatting test verifies redaction without exposing the stored value."
30impl fmt::Display for Secret {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        f.write_str("***")
33    }
34}
35
36#[cfg(test)]
37mod tests {
38    use super::Secret;
39
40    #[test]
41    fn formatting_hides_the_value() {
42        let secret = Secret::new("ghp_value");
43        assert_eq!(format!("{secret:?} {secret}"), "*** ***");
44        assert_eq!(format!("{:?}", Some(secret.clone())), "Some(***)");
45        assert_eq!(secret.expose(), "ghp_value");
46    }
47}