Skip to main content

second_brain_core/keys/
guard.rs

1use std::fmt;
2
3use anyhow::{Result, anyhow};
4use rand::TryRngCore;
5use rand::rngs::OsRng;
6use zeroize::{Zeroize, ZeroizeOnDrop};
7
8/// Owns secret material on the heap and wipes it when dropped. It is never
9/// `Clone`, and its `Debug` output never shows the contents.
10pub struct KeyGuard<T: Zeroize>(Box<T>);
11
12impl<T: Zeroize> KeyGuard<T> {
13    pub fn new(secret: T) -> Self {
14        Self(Box::new(secret))
15    }
16
17    pub fn expose(&self) -> &T {
18        &self.0
19    }
20
21    pub fn expose_mut(&mut self) -> &mut T {
22        &mut self.0
23    }
24}
25
26impl<const N: usize> KeyGuard<[u8; N]> {
27    /// Fills the bytes from the OS generator in place on the heap, so no
28    /// copy of the secret is left on the stack.
29    pub fn random() -> Result<Self> {
30        let mut guard = Self(Box::new([0u8; N]));
31        OsRng
32            .try_fill_bytes(&mut guard.0[..])
33            .map_err(|e| anyhow!("reading OS randomness: {e}"))?;
34        Ok(guard)
35    }
36}
37
38impl<T: Zeroize> Drop for KeyGuard<T> {
39    fn drop(&mut self) {
40        self.0.zeroize();
41    }
42}
43
44impl<T: Zeroize> ZeroizeOnDrop for KeyGuard<T> {}
45
46impl<T: Zeroize> fmt::Debug for KeyGuard<T> {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        f.write_str("KeyGuard(..)")
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use std::sync::Arc;
55    use std::sync::atomic::{AtomicBool, Ordering};
56
57    use super::*;
58
59    struct Probe {
60        bytes: [u8; 4],
61        wiped: Arc<AtomicBool>,
62    }
63
64    impl Zeroize for Probe {
65        fn zeroize(&mut self) {
66            self.bytes.zeroize();
67            self.wiped.store(true, Ordering::SeqCst);
68        }
69    }
70
71    #[test]
72    fn dropping_a_guard_zeroizes_its_secret() {
73        let wiped = Arc::new(AtomicBool::new(false));
74        let guard = KeyGuard::new(Probe {
75            bytes: [7; 4],
76            wiped: wiped.clone(),
77        });
78        assert_eq!(guard.expose().bytes, [7; 4]);
79        assert!(!wiped.load(Ordering::SeqCst));
80        drop(guard);
81        assert!(wiped.load(Ordering::SeqCst));
82    }
83
84    #[test]
85    fn debug_output_hides_the_secret() {
86        let guard = KeyGuard::new([0xabu8; 32]);
87        let shown = format!("{guard:?}");
88        assert_eq!(shown, "KeyGuard(..)");
89    }
90
91    #[test]
92    fn random_guards_differ() {
93        let a = KeyGuard::<[u8; 32]>::random().unwrap();
94        let b = KeyGuard::<[u8; 32]>::random().unwrap();
95        assert_ne!(a.expose(), b.expose());
96        assert_ne!(a.expose(), &[0u8; 32]);
97    }
98}