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