hyprforge_secret/lib.rs
1//! One implementation of "never render this".
2//!
3//! A keysym name *is* the character it names, and the same is true of a
4//! typed password and a Wi-Fi passphrase: the moment a `Debug` impl, a
5//! `tracing::debug!(?x)`, or a panic message prints the value, it is on
6//! disk in a barely-encoded form, and in an agent session it reaches the
7//! session transcript through tool output. That rule got written by hand
8//! three separate times in this workspace — the lock screen's typed
9//! password, the Wi-Fi passphrase, and the clipboard's remembered content
10//! — and each of those was a fresh chance to get it wrong: to forget a
11//! field, to `#[derive(Debug)]` over it later, to print the value "just
12//! this once" for a bug report.
13//!
14//! [`Secret<T>`] is the one implementation for the two of those that are
15//! a genuine "hide this, entirely" case — a password and a passphrase,
16//! where the *value* itself is the whole risk and nothing about it is
17//! worth describing. Its `Debug` renders a character count and nothing
18//! else, and [`Secret::expose`] is the single accessor: `grep expose` in
19//! any crate that depends on this one finds every place a secret leaves
20//! the wrapper.
21//!
22//! The clipboard is a different shape of the same problem and is
23//! deliberately *not* built on `Secret<T>` — see
24//! `hyprforge-clipboard`'s `types.rs` for why, and [`chars`]/[`bytes`]
25//! for the smaller piece of this crate it does share: the formatting of
26//! "a redacted count", used by a `Debug` impl that describes rather than
27//! hides.
28
29use std::fmt;
30use zeroize::Zeroize;
31
32/// A value that must never reach a log, a panic message, or a debug
33/// dump — only its length may be rendered.
34///
35/// `T` is almost always a `String`: a typed password, a Wi-Fi
36/// passphrase. [`Secret::new`] wraps it, [`Secret::expose`] is the one
37/// sanctioned way back out, and `Debug` is implemented once, here,
38/// instead of by hand at every call site that holds one.
39#[derive(Clone, PartialEq, Eq, Default)]
40pub struct Secret<T: Zeroize>(T);
41
42/// Erased when it goes out of scope.
43///
44/// This is the half `Debug` cannot do. Hiding the value from a log stops
45/// it being *written down*; it does nothing about the copy sitting in
46/// the process's heap until that page is reused, which a core dump or a
47/// swapped-out page can still carry.
48///
49/// It matters more here than it looks, because of how the value is
50/// accumulated. A typed password is not appended to in place — the host
51/// hands the whole string over on every keystroke and the old `Secret`
52/// is dropped — so entering eight characters allocates eight strings,
53/// each holding a prefix of the password, and before this each of them
54/// was freed with its contents intact. Zeroing on drop clears every one
55/// of them at the moment it stops being used.
56///
57/// What it still does not cover, and the README says so: PAM and greetd
58/// keep copies of their own once the answer is handed over, and nothing
59/// on this side can reach those.
60impl<T: Zeroize> Drop for Secret<T> {
61 fn drop(&mut self) {
62 self.0.zeroize();
63 }
64}
65
66impl<T: Zeroize> Secret<T> {
67 /// Wraps a value so it can only leave through [`Secret::expose`] or
68 /// [`Secret::into_inner`]. Always safe: wrapping does not expose
69 /// anything, which is why `Secret<T>: From<T>` also exists as a
70 /// shorthand for this.
71 pub fn new(value: T) -> Self {
72 Secret(value)
73 }
74
75 /// The value. Named to be greppable: every caller is a place the
76 /// secret leaves this type, and there should be exactly one per use
77 /// site — the place it is actually sent to PAM, greetd, or
78 /// NetworkManager.
79 pub fn expose(&self) -> &T {
80 &self.0
81 }
82
83 /// Unwraps by value, for the rare case a secret needs to move
84 /// (`std::mem::take` and hand it to something that owns it next).
85 /// Still not a way to see the value — the caller has to `expose()`
86 /// it separately, same as anyone else.
87 /// Requires `Default` because this type erases itself on drop, and
88 /// Rust will not let a field move out of something with a `Drop`
89 /// impl — so the value is swapped for a default one, which is then
90 /// what gets erased. The caller owns the real value afterwards and
91 /// owns the job of clearing it, exactly as they would have anyway.
92 pub fn into_inner(mut self) -> T
93 where
94 T: Default,
95 {
96 std::mem::take(&mut self.0)
97 }
98}
99
100/// How to count a secret's length without looking at what it is made of.
101///
102/// A password is counted in characters, not bytes, for the same reason
103/// [`crate::chars`] is: it is only ever used to describe the value, never
104/// to validate it against a byte length, and a non-ASCII password should
105/// report what was typed.
106///
107/// Sealed: this exists to let `Secret<T>`'s `Debug` count characters
108/// without caring what `T` is made of, not as an extension point for
109/// callers outside this crate. A public trait with one method is a
110/// promise about its *whole* shape — adding a second method later would
111/// break every external implementer — and sealing is what keeps that
112/// door shut while still letting `SecretLen` appear in a public bound
113/// (`Secret<T>`'s `Debug` impl requires it).
114pub trait SecretLen: sealed::Sealed {
115 /// How many characters this value would render as, if it were ever
116 /// allowed to render at all.
117 fn secret_char_count(&self) -> usize;
118}
119
120mod sealed {
121 pub trait Sealed {}
122}
123
124impl sealed::Sealed for String {}
125impl sealed::Sealed for str {}
126impl<T: sealed::Sealed + ?Sized> sealed::Sealed for &T {}
127
128impl SecretLen for String {
129 fn secret_char_count(&self) -> usize {
130 self.chars().count()
131 }
132}
133
134impl SecretLen for str {
135 fn secret_char_count(&self) -> usize {
136 self.chars().count()
137 }
138}
139
140impl<T: SecretLen + ?Sized> SecretLen for &T {
141 fn secret_char_count(&self) -> usize {
142 (**self).secret_char_count()
143 }
144}
145
146/// Renders `<N chars>`, never the value — the whole point of the type.
147///
148/// This is the one place that decision is made. Every caller that holds
149/// a `Secret<T>`, including one nested inside a `#[derive(Debug)]`
150/// struct, gets this rendering for free and cannot accidentally derive
151/// past it.
152/// Wrapping is always safe, so `.into()` is allowed rather than making
153/// every call site spell out `Secret::new`.
154///
155/// Deliberately one-directional: there is no `From<Secret<T>> for T`,
156/// because taking a value back *out* is the operation that has to stay
157/// greppable, and that is what [`Secret::expose`] is for.
158impl<T: Zeroize> From<T> for Secret<T> {
159 fn from(value: T) -> Self {
160 Secret::new(value)
161 }
162}
163
164impl<T: SecretLen + Zeroize> fmt::Debug for Secret<T> {
165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 write!(f, "{:?}", chars(self.0.secret_char_count()))
167 }
168}
169
170/// A count with a unit, rendered as `<N unit>` — `<28 chars>`,
171/// `<2048 bytes>`.
172///
173/// This is the shared piece for a type that *describes* its content
174/// rather than hiding it entirely (`hyprforge-clipboard`'s `Content`,
175/// which says `Text(<28 chars>)` or `Image(image/png, <2048 bytes>)`
176/// rather than nothing at all). [`Secret<T>`]'s own `Debug` is built out
177/// of the same formatting, so there is exactly one implementation of "a
178/// redacted count looks like this" in the workspace, even though hiding
179/// entirely and describing-with-a-count are different policies.
180pub struct RedactedCount {
181 count: usize,
182 unit: &'static str,
183}
184
185impl fmt::Debug for RedactedCount {
186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187 write!(f, "<{} {}>", self.count, self.unit)
188 }
189}
190
191/// A character count, for text: `<N chars>`.
192pub fn chars(count: usize) -> RedactedCount {
193 RedactedCount { count, unit: "chars" }
194}
195
196/// A byte count, for anything not meaningfully measured in characters
197/// (image bytes, for instance): `<N bytes>`.
198pub fn bytes(count: usize) -> RedactedCount {
199 RedactedCount { count, unit: "bytes" }
200}
201
202#[cfg(test)]
203mod tests {
204 use super::*;
205
206 #[test]
207 fn a_secret_never_renders_its_own_value() {
208 let secret = Secret::new("hunter2-correct-horse".to_string());
209 let rendered = format!("{secret:?}");
210 assert!(!rendered.contains("hunter2"), "leaked: {rendered}");
211 assert_eq!(rendered, "<21 chars>");
212 }
213
214 /// The case that actually bites: a secret is never printed on its
215 /// own, it is printed as a field of something else, usually a
216 /// `#[derive(Debug)]` struct that was written without thinking about
217 /// what it holds.
218 #[test]
219 fn a_secret_nested_inside_a_derived_debug_still_renders_only_a_count() {
220 #[derive(Debug)]
221 #[allow(dead_code)]
222 struct Request {
223 username: String,
224 password: Secret<String>,
225 }
226 let rendered = format!(
227 "{:?}",
228 Request {
229 username: "apost".to_string(),
230 password: Secret::new("swordfish1".to_string()),
231 }
232 );
233 assert!(!rendered.contains("swordfish"), "leaked: {rendered}");
234 assert!(rendered.contains("<10 chars>"), "got {rendered}");
235 }
236
237 #[test]
238 fn the_count_is_characters_not_bytes() {
239 let secret = Secret::new("pässwörd".to_string());
240 assert_eq!(format!("{secret:?}"), "<8 chars>");
241 }
242
243 #[test]
244 fn expose_is_the_only_way_back_to_the_value() {
245 let secret = Secret::new("hunter2".to_string());
246 assert_eq!(secret.expose(), "hunter2");
247 }
248
249 #[test]
250 fn a_redacted_count_renders_a_count_and_a_unit_never_a_value() {
251 assert_eq!(format!("{:?}", chars(28)), "<28 chars>");
252 assert_eq!(format!("{:?}", bytes(2048)), "<2048 bytes>");
253 }
254}
255
256#[cfg(test)]
257mod erasing {
258 use super::*;
259 use std::sync::atomic::{AtomicUsize, Ordering};
260
261 /// Counts how many times it was erased, so the *wiring* can be
262 /// tested without reading freed memory.
263 ///
264 /// Reading the heap after a free to prove the bytes are gone is
265 /// undefined behaviour, and a test built on it reports whatever the
266 /// allocator happened to do — which is the sort of measurement
267 /// CLAUDE.md's "check the instrument" rule is about. What this crate
268 /// can actually get wrong is the wiring: forgetting the `Drop`,
269 /// bounding it so it silently does not apply, or moving the value
270 /// out before it runs. That is what these check. Whether the write
271 /// survives the optimiser is `zeroize`'s own guarantee and its own
272 /// test suite, which is the reason for depending on it rather than
273 /// writing the loop here.
274 /// `Option`, so the empty husk `into_inner` leaves behind counts
275 /// against nothing and erasing it cannot be mistaken for erasing
276 /// the value that was taken out. That is also what `Default` gives
277 /// for free, which is why it is derived.
278 #[derive(Clone, Default)]
279 struct Counted(Option<&'static AtomicUsize>);
280
281 impl Zeroize for Counted {
282 fn zeroize(&mut self) {
283 if let Some(counter) = self.0 {
284 counter.fetch_add(1, Ordering::SeqCst);
285 }
286 }
287 }
288
289 static DROPPED: AtomicUsize = AtomicUsize::new(0);
290 static TAKEN: AtomicUsize = AtomicUsize::new(0);
291
292 #[test]
293 fn a_secret_erases_itself_when_it_goes_out_of_scope() {
294 DROPPED.store(0, Ordering::SeqCst);
295 {
296 let _held = Secret::new(Counted(Some(&DROPPED)));
297 assert_eq!(DROPPED.load(Ordering::SeqCst), 0, "not while it is still in use");
298 }
299 assert_eq!(DROPPED.load(Ordering::SeqCst), 1);
300 }
301
302 /// The case that makes this worth having. A typed password is
303 /// replaced wholesale on every keystroke rather than appended to, so
304 /// each intermediate has to be erased as it is displaced — eight
305 /// characters, eight strings, each holding a prefix.
306 #[test]
307 fn every_displaced_value_is_erased_not_only_the_last() {
308 DROPPED.store(0, Ordering::SeqCst);
309 let mut entered = Secret::new(Counted(Some(&DROPPED)));
310 for _ in 0..8 {
311 entered = Secret::new(Counted(Some(&DROPPED)));
312 }
313 assert_eq!(DROPPED.load(Ordering::SeqCst), 8, "one per displaced value");
314 drop(entered);
315 assert_eq!(DROPPED.load(Ordering::SeqCst), 9);
316 }
317
318 /// `into_inner` hands the value to the caller, so what is erased is
319 /// the default left behind — not the value, which the caller now
320 /// owns and is responsible for.
321 #[test]
322 fn taking_the_value_out_does_not_erase_the_value_that_was_taken() {
323 TAKEN.store(0, Ordering::SeqCst);
324 let held = Secret::new(Counted(Some(&TAKEN)));
325 let out = held.into_inner();
326 // Nothing was counted: what the wrapper erased was the empty
327 // husk left in its place, and the real value went to the
328 // caller untouched.
329 assert_eq!(TAKEN.load(Ordering::SeqCst), 0, "the value that was taken must not be erased");
330 // The real value came out, and nothing erased it on the way —
331 // it is the caller's now, and clearing it is theirs too.
332 assert!(out.0.is_some(), "and it is the real one");
333 }
334
335 /// A real password, through the type the auth stack actually uses —
336 /// so a change that made `String` stop satisfying the bound would
337 /// fail here rather than somewhere far away.
338 #[test]
339 fn a_string_password_is_what_this_is_for() {
340 let password = Secret::new("hunter2".to_string());
341 assert_eq!(password.expose(), "hunter2");
342 assert!(!format!("{password:?}").contains("hunter2"));
343 }
344}