env_reader/secret.rs
1//! A configuration value that must not be printed.
2
3use std::fmt;
4
5/// What a secret renders as, everywhere.
6const MASK: &str = "<redacted>";
7
8/// A configuration value that never appears in output.
9///
10/// Wraps a connection string, a password, a shared access key or an API
11/// key. Both [`Debug`] and [`Display`] render `<redacted>`; the value comes
12/// out only through [`Secret::expose`], which is deliberately awkward to
13/// type and easy to grep for.
14///
15/// # Why both `Debug` and `Display`
16///
17/// Deriving `Debug` on a configuration struct is the normal thing to do,
18/// and the resulting line ends up in a log eventually. Masking `Debug`
19/// alone is the common half-measure: it leaves `format!("{secret}")` and
20/// every `Display`-based logging macro wide open. This type masks both.
21///
22/// # Examples
23///
24/// ```
25/// use env_reader::Secret;
26///
27/// #[derive(Debug)]
28/// struct Config {
29/// endpoint: String,
30/// access_key: Secret,
31/// }
32///
33/// let config = Config {
34/// endpoint: "sb://example".into(),
35/// access_key: Secret::new("hunter2"),
36/// };
37///
38/// let printed = format!("{config:?}");
39/// assert!(printed.contains("sb://example"));
40/// assert!(!printed.contains("hunter2"));
41/// assert_eq!(config.access_key.expose(), "hunter2");
42/// ```
43///
44/// # `PartialEq` compares in ordinary time
45///
46/// It is derived, so a comparison is not constant-time. That is right for
47/// what this type is for — comparing two *configurations*, usually in a
48/// test — and wrong for checking a presented credential against a stored
49/// one. Do not use it for the latter.
50#[derive(Clone, PartialEq, Eq)]
51pub struct Secret(String);
52
53impl Secret {
54 /// Wrap a value.
55 ///
56 /// # Examples
57 ///
58 /// ```
59 /// use env_reader::Secret;
60 ///
61 /// assert_eq!(Secret::new("hunter2").to_string(), "<redacted>");
62 /// ```
63 #[must_use]
64 pub fn new(value: impl Into<String>) -> Self {
65 Self(value.into())
66 }
67
68 /// The value itself.
69 ///
70 /// Named to be conspicuous at a call site and in a code review: every
71 /// use of it is a place a secret leaves this type.
72 ///
73 /// # Examples
74 ///
75 /// ```
76 /// use env_reader::Secret;
77 ///
78 /// assert_eq!(Secret::new("hunter2").expose(), "hunter2");
79 /// ```
80 #[must_use]
81 pub fn expose(&self) -> &str {
82 &self.0
83 }
84
85 /// The value itself, consuming this.
86 ///
87 /// For handing ownership to a client library that wants a `String`.
88 #[must_use]
89 pub fn into_exposed(self) -> String {
90 self.0
91 }
92
93 /// Whether the wrapped value is empty.
94 ///
95 /// Lets a caller branch on "is this configured" without exposing it.
96 ///
97 /// # Examples
98 ///
99 /// ```
100 /// use env_reader::Secret;
101 ///
102 /// assert!(Secret::new("").is_empty());
103 /// assert!(!Secret::new("hunter2").is_empty());
104 /// ```
105 #[must_use]
106 pub fn is_empty(&self) -> bool {
107 self.0.is_empty()
108 }
109
110 /// How long the wrapped value is, in bytes.
111 ///
112 /// The one measurement this type will report. Enough to tell a
113 /// truncated key from an absent one in a log line, and nothing more.
114 #[must_use]
115 pub fn len(&self) -> usize {
116 self.0.len()
117 }
118}
119
120impl fmt::Debug for Secret {
121 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
122 formatter.write_str(MASK)
123 }
124}
125
126impl fmt::Display for Secret {
127 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
128 formatter.write_str(MASK)
129 }
130}
131
132impl From<String> for Secret {
133 fn from(value: String) -> Self {
134 Self(value)
135 }
136}
137
138impl From<&str> for Secret {
139 fn from(value: &str) -> Self {
140 Self(value.to_string())
141 }
142}
143
144#[cfg(test)]
145mod tests {
146 use super::*;
147
148 /// A value distinctive enough that finding it anywhere is unambiguous.
149 const MARKER: &str = "SharedAccessKey=NEEDLE-9f2c";
150
151 #[test]
152 fn debug_does_not_print_the_value() {
153 let printed = format!("{:?}", Secret::new(MARKER));
154 assert_eq!(printed, MASK);
155 assert!(!printed.contains("NEEDLE"));
156 }
157
158 #[test]
159 fn display_does_not_print_the_value() {
160 assert!(!Secret::new(MARKER).to_string().contains("NEEDLE"));
161 // The half-measure this type exists to avoid: masking `Debug` only
162 // leaves every `Display`-based logging macro wide open.
163 assert!(!format!("{}", Secret::new(MARKER)).contains("NEEDLE"));
164 }
165
166 #[test]
167 fn a_secret_inside_a_derived_debug_stays_hidden() {
168 // The case that actually happens. The fields are read by the
169 // derived `Debug` and nowhere else, which is what this test is
170 // about.
171 #[derive(Debug)]
172 #[allow(dead_code)]
173 struct Config {
174 /// A field whose presence proves the rest of the struct printed.
175 queue: &'static str,
176 /// The field under test.
177 key: Secret,
178 }
179
180 let printed = format!(
181 "{:?}",
182 Config {
183 queue: "orders",
184 key: Secret::new(MARKER),
185 }
186 );
187 assert!(printed.contains("orders"));
188 assert!(!printed.contains("NEEDLE"));
189 }
190
191 #[test]
192 fn the_value_is_reachable_when_asked_for() {
193 assert_eq!(Secret::new(MARKER).expose(), MARKER);
194 assert_eq!(Secret::new(MARKER).into_exposed(), MARKER);
195 }
196
197 #[test]
198 fn a_length_is_reportable_but_the_content_is_not() {
199 let secret = Secret::new(MARKER);
200 assert_eq!(secret.len(), MARKER.len());
201 assert!(!secret.is_empty());
202 assert!(Secret::new("").is_empty());
203 }
204
205 #[test]
206 fn conversion_from_the_usual_string_types() {
207 assert_eq!(Secret::from("x").expose(), "x");
208 assert_eq!(Secret::from(String::from("y")).expose(), "y");
209 }
210}