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