Skip to main content

tinyharness_lib/
secret.rs

1use serde::{Deserialize, Serialize, Serializer};
2
3/// Minimal no-new-dependency replacement for `secrecy::SecretString`.
4/// Exposes the secret only on explicit `.expose_secret()` calls. The secret
5/// cannot be implicitly leaked by the `Debug` implementation, e.g. in logs.
6///
7/// Retains serialization/deserialization via `serde`.
8///
9/// Deviations from `secrecy`:
10/// 1. Does not zero on `Drop`: the heap bytes remain after deallocation, and,
11///    e.g., a core dump could contain leaked secrets.
12/// 2. Implements `Clone`: `secrecy` uses its own `SecretBox` smart pointer for
13///    space efficiency. Since we can reasonably expect only a handful of
14///    secrets in memory for TinyHarness, that optimization is not worth the
15///    added complexity.
16#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
17pub struct SecretString(String);
18
19impl SecretString {
20    pub fn new(s: impl Into<String>) -> Self {
21        Self(s.into())
22    }
23
24    /// Expose the underlying secret. Use this as the point the actual value is
25    /// required (e.g., in constructing an HTTP request). Do not log the exposed
26    /// value.
27    pub fn expose_secret(&self) -> &str {
28        &self.0
29    }
30
31    pub fn is_empty(&self) -> bool {
32        self.0.is_empty()
33    }
34
35    pub fn len(&self) -> usize {
36        self.0.len()
37    }
38
39    pub fn masked(&self) -> String {
40        if self.0.is_ascii() && self.len() > 8 {
41            format!("{}...{}", &self.0[..4], &self.0[self.len() - 4..])
42        } else {
43            "****".to_string()
44        }
45    }
46}
47
48impl std::fmt::Debug for SecretString {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        f.write_str("[REDACTED]")
51    }
52}
53
54impl Serialize for SecretString {
55    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
56    where
57        S: Serializer,
58    {
59        serializer.serialize_str(&self.0)
60    }
61}
62
63impl<'de> Deserialize<'de> for SecretString {
64    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
65    where
66        D: serde::Deserializer<'de>,
67    {
68        String::deserialize(deserializer).map(SecretString)
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75
76    #[test]
77    fn debug_redacts_value() {
78        let s = SecretString::new("sk-supersecret");
79        assert_eq!(format!("{:?}", s), "[REDACTED]");
80        assert!(!format!("{:?}", s).contains("sk-supersecret"));
81    }
82
83    #[test]
84    fn expose_secret_returns_inner() {
85        let s = SecretString::new("sk-supersecret");
86        assert_eq!(s.expose_secret(), "sk-supersecret");
87    }
88
89    #[test]
90    fn is_empty_and_len() {
91        assert!(SecretString::new("").is_empty());
92        assert_eq!(SecretString::new("").len(), 0);
93        assert!(!SecretString::new("abc").is_empty());
94        assert_eq!(SecretString::new("abc").len(), 3);
95    }
96
97    #[test]
98    fn masked_long_ascii() {
99        assert_eq!(SecretString::new("abcdef123456").masked(), "abcd...3456");
100    }
101
102    #[test]
103    fn masked_short_ascii() {
104        assert_eq!(SecretString::new("abc").masked(), "****");
105        assert_eq!(SecretString::new("abcdefgh").masked(), "****");
106    }
107
108    #[test]
109    fn masked_exactly_9_chars() {
110        // 9 chars is the threshold: still show first/last 4
111        assert_eq!(SecretString::new("abcdefghi").masked(), "abcd...fghi");
112    }
113
114    #[test]
115    fn masked_non_ascii_falls_through_to_stars() {
116        // Non-ASCII keys of any length are masked fully, since slicing on a
117        // non-ASCII boundary would panic and revealing a slice of UTF-8 bytes
118        // could split a code point.
119        assert_eq!(SecretString::new("пароль12345").masked(), "****");
120    }
121
122    #[test]
123    fn clone_yields_equal_value() {
124        let s = SecretString::new("sk-supersecret");
125        assert_eq!(s.clone(), s);
126    }
127
128    #[test]
129    fn default_is_empty() {
130        let s = SecretString::default();
131        assert!(s.is_empty());
132        assert_eq!(s.expose_secret(), "");
133    }
134
135    #[test]
136    fn serde_round_trip_preserves_value() {
137        let s = SecretString::new("sk-supersecret");
138        let json = serde_json::to_string(&s).unwrap();
139        let back: SecretString = serde_json::from_str(&json).unwrap();
140        assert_eq!(back, s);
141        assert_eq!(back.expose_secret(), "sk-supersecret");
142    }
143
144    #[test]
145    fn serde_wire_format_is_bare_string() {
146        // Pin the on-disk format: a bare JSON string, not a wrapper object.
147        // This is what guarantees `settings.json` keeps loading with no
148        // migration.
149        let s = SecretString::new("sk-supersecret");
150        let v = serde_json::to_value(&s).unwrap();
151        assert_eq!(v, serde_json::Value::String("sk-supersecret".to_string()));
152    }
153}