Skip to main content

burn_after_reading/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3
4#[derive(zeroize::ZeroizeOnDrop, Default)]
5#[repr(transparent)]
6pub struct Bar<S: zeroize::Zeroize>(Option<S>);
7
8#[cfg(feature = "serde")]
9impl<'de, S: zeroize::Zeroize> ::serde_core::Deserialize<'de> for Bar<S>
10where
11    S: ::serde_core::Deserialize<'de>,
12{
13    #[inline]
14    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
15    where
16        D: ::serde_core::Deserializer<'de>,
17    {
18        S::deserialize(deserializer).map(|value| Self(Some(value)))
19    }
20}
21
22#[cfg(feature = "serde")]
23impl<T: zeroize::Zeroize> ::serde_core::Serialize for Bar<T>
24where
25    T: ::serde_core::Serialize,
26{
27    #[inline]
28    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
29    where
30        S: serde_core::Serializer,
31    {
32        use ::serde_core::ser::Error as _;
33        let Some(inner) = &self.0 else {
34            return Err(S::Error::custom("Value already consumed, cannot serialize"));
35        };
36
37        inner.serialize(serializer)
38    }
39}
40
41#[derive(zeroize::ZeroizeOnDrop)]
42pub struct BarGuard<'a, S: zeroize::Zeroize> {
43    source: &'a mut Bar<S>,
44    value: S,
45    #[zeroize(skip)]
46    mlock_guard: region::LockGuard,
47}
48
49impl<'a, S: zeroize::Zeroize> std::ops::Deref for BarGuard<'a, S> {
50    type Target = S;
51
52    fn deref(&self) -> &Self::Target {
53        &self.value
54    }
55}
56
57impl<S: zeroize::Zeroize> From<S> for Bar<S> {
58    fn from(value: S) -> Self {
59        Self::wrap(value)
60    }
61}
62
63impl<S: zeroize::Zeroize> Bar<S> {
64    pub fn wrap(value: S) -> Self {
65        Self(Some(value))
66    }
67
68    #[must_use]
69    /// Consumes the `Bar` and tentatively tries to `mlock(2)` on applicable platforms.
70    /// If the value was already consumed or mlock cannot be performed, returns `None`
71    pub fn read(&mut self) -> Option<BarGuard<'_, S>> {
72        self.0.take().and_then(|value| {
73            Some(BarGuard {
74                source: self,
75                mlock_guard: mlock(&value)?,
76                value,
77            })
78        })
79    }
80}
81
82#[cfg(target_family = "wasm")]
83// Shim for region crate not available there
84mod region {
85    pub(crate) struct LockGuard;
86}
87
88#[allow(unused_variables)]
89fn mlock<S>(value: &S) -> Option<region::LockGuard> {
90    cfg_select! {
91        target_family = "wasm" => {Some(region::LockGuard)},
92        _ => { region::lock(value as *const S, std::mem::size_of_val(value)).ok() }
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use std::assert_matches;
99
100    use crate::Bar;
101
102    #[test]
103    fn value_is_erased_after_reading() {
104        const HW: &str = "hello world";
105        let value = String::from(HW);
106        let mut bar = Bar::wrap(value);
107
108        assert_matches!(bar.0.as_deref(), Some(HW));
109        let guard = bar.read().unwrap();
110        // You normally cannot uncomment this because of the mutable borrow
111        // by the guard on the Bar
112        // assert!(bar.0.is_none());
113        assert_eq!(guard.as_str(), HW);
114        drop(guard);
115
116        // Now that the guard has been dropped, you can, and it should be empty
117        assert!(bar.0.is_none());
118    }
119}