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    /// A typed parser may reject a value before the redacting visitor runs.
28    #[error("invalid JSON for guarded message")]
29    InvalidMessage,
30    /// Unknown field names can contain caller-provided private data.
31    #[error("unknown JSON field in guarded message")]
32    UnknownField,
33}
34
35impl<T: Default + Zeroize, P: crate::ProtoBox<T>> Zeroize for crate::MessageField<T, P> {
36    fn zeroize(&mut self) {
37        if let Some(value) = self.as_option_mut() {
38            value.zeroize();
39        }
40        *self = Self::none();
41    }
42}
43
44/// Wipe every element of `values`, drop them, then wipe the whole allocation.
45///
46/// The allocation guarantee applies when element cleanup and destruction return
47/// normally. A panic in a consumer-provided implementation can interrupt it.
48///
49/// As of zeroize 1.9.1, `Vec::zeroize` invokes each element's cleanup before
50/// dropping it, but does not wipe the slots the dropped elements vacate. Those
51/// slots can still hold an enum discriminant, an inner buffer's pointer and
52/// capacity, or padding. At length zero the entire allocation is `MaybeUninit`
53/// storage, so wiping the spare capacity afterwards covers every vacated slot.
54/// Under earlier zeroize releases the final pass is merely redundant. The
55/// capacity is kept, so the buffer stays available for reuse. Only the current
56/// allocation is covered: buffers an ordinary `Vec` released while growing
57/// were never wiped.
58#[doc(hidden)]
59pub fn zeroize_vec<T: Zeroize>(values: &mut alloc::vec::Vec<T>) {
60    values.zeroize();
61    values.spare_capacity_mut().zeroize();
62}
63
64/// Overwrite a copyable value with its valid default using volatile stores.
65/// Used by generated enums, whose valid default is not necessarily zero.
66#[doc(hidden)]
67pub fn reset_copy<T: Copy + Default>(value: &mut T) {
68    // Construct first: even a panicking custom Default must leave the original
69    // value valid. A typed assignment alone can leave inactive enum bytes behind.
70    let replacement = T::default();
71    let pointer = value as *mut T;
72    // SAFETY: the exclusive slot is valid storage for MaybeUninit<T>, which
73    // permits zero bytes even when T does not. No T is accessed between wiping
74    // the representation and restoring its valid default. Copy has no destructor
75    // or owned allocation that overwriting could leak.
76    unsafe {
77        (&mut *pointer.cast::<core::mem::MaybeUninit<T>>()).zeroize();
78        core::ptr::write_volatile(pointer, replacement);
79    }
80    core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
81}
82
83impl<E: crate::Enumeration + Zeroize> Zeroize for crate::EnumValue<E> {
84    fn zeroize(&mut self) {
85        match self {
86            Self::Unknown(number) => number.zeroize(),
87            Self::Known(value) => value.zeroize(),
88        }
89        // Known discriminants belong to the public enum definition. Replacing
90        // the whole representation also overwrites a previous identifying number.
91        reset_copy(self);
92    }
93}
94
95impl<T: Default + Zeroize + ZeroizeOnDrop, P: crate::ProtoBox<T>> ZeroizeOnDrop
96    for crate::MessageField<T, P>
97{
98}
99
100mod text;
101#[cfg(feature = "json")]
102pub(crate) use text::serialize_decimal;
103pub use text::{FormatError, StackText};
104
105pub(crate) mod view_storage;
106#[doc(hidden)]
107pub use view_storage::IntoIter as ViewIntoIter;
108
109impl<T: Zeroize> Zeroize for crate::MessageFieldView<T> {
110    fn zeroize(&mut self) {
111        if let Some(value) = self.as_mut() {
112            value.zeroize();
113        }
114        *self = Self::unset();
115    }
116}
117#[doc(hidden)]
118pub use crate::erasing::Erasing as Slot;
119
120pub use crate::view::guarded::{MapView, RepeatedView};
121
122#[cfg(test)]
123mod tests {
124    use super::reset_copy;
125    #[test]
126    fn copy_reset_restores_valid_niche_and_tagged_representations() {
127        #[derive(Clone, Copy, Debug, PartialEq)]
128        struct NonZero(core::num::NonZeroU32);
129        impl Default for NonZero {
130            fn default() -> Self {
131                Self(core::num::NonZeroU32::new(7).unwrap())
132            }
133        }
134        let mut value = NonZero(core::num::NonZeroU32::new(37).unwrap());
135        reset_copy(&mut value);
136        assert_eq!(value, NonZero::default());
137
138        #[derive(Clone, Copy, Debug, Default, PartialEq)]
139        enum Slot {
140            #[default]
141            Empty,
142            Number([u64; 4]),
143        }
144        let mut value = Slot::Number([37; 4]);
145        reset_copy(&mut value);
146        assert_eq!(value, Slot::Empty);
147        reset_copy(&mut value);
148        assert_eq!(value, Slot::Empty);
149
150        #[cfg(feature = "std")]
151        {
152            #[derive(Clone, Copy)]
153            struct PanickingDefault(core::num::NonZeroU32);
154            impl Default for PanickingDefault {
155                fn default() -> Self {
156                    panic!("test default failure");
157                }
158            }
159            let mut value = PanickingDefault(core::num::NonZeroU32::new(37).unwrap());
160            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
161                reset_copy(&mut value);
162            }));
163            assert!(result.is_err());
164            assert_eq!(value.0.get(), 37);
165        }
166    }
167}