Skip to main content

buffa/sensitive/
mod.rs

1// Modified by ReallyMe Technologies Limited.
2//! Opt-in owned storage for sensitive protobuf messages.
3//!
4//! Collections wipe their values before releasing them. A list also wipes
5//! outgrown allocations; a map keeps keys and values in stable wipe-owned
6//! allocations so tree balancing only moves pointers.
7
8#[cfg(feature = "arbitrary")]
9#[doc(hidden)]
10pub mod arbitrary;
11mod list;
12mod map;
13#[cfg(feature = "arbitrary")]
14pub use arbitrary::GuardedArbitrary;
15pub use list::{IterMut, List};
16pub use map::{Map, MapKey};
17pub use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
18
19/// Fixed diagnostics used by generated guarded JSON visitors.
20#[cfg(feature = "json")]
21#[doc(hidden)]
22#[derive(Debug, thiserror::Error)]
23#[non_exhaustive]
24pub enum JsonErrorReason {
25    /// Unknown field names can contain caller-provided private data.
26    #[error("unknown JSON field in guarded message")]
27    UnknownField,
28}
29
30impl<T: Default + Zeroize, P: crate::ProtoBox<T>> Zeroize for crate::MessageField<T, P> {
31    fn zeroize(&mut self) {
32        if let Some(value) = self.as_option_mut() {
33            value.zeroize();
34        }
35        *self = Self::none();
36    }
37}
38
39/// Overwrite a copyable value with its valid default using volatile stores.
40/// Used by generated enums, whose valid default is not necessarily zero.
41#[doc(hidden)]
42pub fn reset_copy<T: Copy + Default>(value: &mut T) {
43    // Construct first: even a panicking custom Default must leave the original
44    // value valid. A typed assignment alone can leave inactive enum bytes behind.
45    let replacement = T::default();
46    let pointer = value as *mut T;
47    // SAFETY: the exclusive slot is valid storage for MaybeUninit<T>, which
48    // permits zero bytes even when T does not. No T is accessed between wiping
49    // the representation and restoring its valid default. Copy has no destructor
50    // or owned allocation that overwriting could leak.
51    unsafe {
52        (&mut *pointer.cast::<core::mem::MaybeUninit<T>>()).zeroize();
53        core::ptr::write_volatile(pointer, replacement);
54    }
55    core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
56}
57
58impl<E: crate::Enumeration + Zeroize> Zeroize for crate::EnumValue<E> {
59    fn zeroize(&mut self) {
60        match self {
61            Self::Unknown(number) => number.zeroize(),
62            Self::Known(value) => value.zeroize(),
63        }
64        // Known discriminants belong to the public enum definition. Replacing
65        // the whole representation also overwrites a previous identifying number.
66        reset_copy(self);
67    }
68}
69
70impl<T: Default + Zeroize + ZeroizeOnDrop, P: crate::ProtoBox<T>> ZeroizeOnDrop
71    for crate::MessageField<T, P>
72{
73}
74
75mod text;
76#[cfg(feature = "json")]
77pub(crate) use text::serialize_decimal;
78pub use text::{FormatError, StackText};
79
80pub(crate) mod view_storage;
81#[doc(hidden)]
82pub use view_storage::IntoIter as ViewIntoIter;
83
84impl<T: Zeroize> Zeroize for crate::MessageFieldView<T> {
85    fn zeroize(&mut self) {
86        if let Some(value) = self.as_mut() {
87            value.zeroize();
88        }
89        *self = Self::unset();
90    }
91}
92impl<V> Zeroize for crate::LazyMessageFieldView<'_, V> {
93    fn zeroize(&mut self) {
94        *self = Self::default();
95    }
96}
97impl<V> Zeroize for crate::LazyRepeatedView<'_, V> {
98    fn zeroize(&mut self) {
99        *self = Self::default();
100    }
101}
102
103#[doc(hidden)]
104pub use crate::erasing::Erasing as Slot;
105
106pub use crate::view::guarded::{MapView, RepeatedView};
107
108#[cfg(test)]
109mod tests {
110    use super::reset_copy;
111    #[test]
112    fn copy_reset_restores_valid_niche_and_tagged_representations() {
113        #[derive(Clone, Copy, Debug, PartialEq)]
114        struct NonZero(core::num::NonZeroU32);
115        impl Default for NonZero {
116            fn default() -> Self {
117                Self(core::num::NonZeroU32::new(7).unwrap())
118            }
119        }
120        let mut value = NonZero(core::num::NonZeroU32::new(37).unwrap());
121        reset_copy(&mut value);
122        assert_eq!(value, NonZero::default());
123
124        #[derive(Clone, Copy, Debug, Default, PartialEq)]
125        enum Slot {
126            #[default]
127            Empty,
128            Number([u64; 4]),
129        }
130        let mut value = Slot::Number([37; 4]);
131        reset_copy(&mut value);
132        assert_eq!(value, Slot::Empty);
133        reset_copy(&mut value);
134        assert_eq!(value, Slot::Empty);
135
136        #[cfg(feature = "std")]
137        {
138            #[derive(Clone, Copy)]
139            struct PanickingDefault(core::num::NonZeroU32);
140            impl Default for PanickingDefault {
141                fn default() -> Self {
142                    panic!("test default failure");
143                }
144            }
145            let mut value = PanickingDefault(core::num::NonZeroU32::new(37).unwrap());
146            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
147                reset_copy(&mut value);
148            }));
149            assert!(result.is_err());
150            assert_eq!(value.0.get(), 37);
151        }
152    }
153}