1#[derive(Clone, PartialEq, Eq, serde::Deserialize)]
3#[serde(transparent)]
4pub struct Secret(String);
5
6impl Secret {
7 pub fn new(value: impl Into<String>) -> Self {
8 Self(value.into())
9 }
10
11 pub fn expose(&self) -> &str {
12 &self.0
13 }
14}
15
16impl std::fmt::Debug for Secret {
17 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18 f.write_str("[redacted]")
19 }
20}
21
22#[cfg(test)]
23mod tests {
24 use super::Secret;
25
26 #[test]
27 fn deserializes_a_string_without_exposing_it_in_debug() {
28 let secret: Secret = serde_json::from_str("\"sentinel\"").unwrap();
29 assert_eq!(secret.expose(), "sentinel");
30 assert_eq!(format!("{secret:?}"), "[redacted]");
31 }
32
33 #[test]
34 fn debug_redacts_the_value() {
35 let secret = Secret::new("sentinel");
36 assert_eq!(format!("{secret:?}"), "[redacted]");
37 assert_eq!(format!("{:?}", Some(&secret)), "Some([redacted])");
38 assert_eq!(secret.expose(), "sentinel");
39 }
40}