Skip to main content

buffa/sensitive/
list.rs

1// Modified by ReallyMe Technologies Limited.
2use super::{Zeroize, ZeroizeOnDrop};
3use alloc::vec::Vec;
4use core::{fmt, ops::Deref};
5
6/// A repeated collection that wipes live elements, spare capacity and outgrown buffers.
7///
8/// Mutable access is limited to individual elements: mutable slice methods can
9/// allocate temporary copies outside this collection's cleanup owner.
10/// Advisory packed-decode capacity hints are ignored to avoid preallocating
11/// from an attacker-influenced upper bound; growth still wipes prior buffers.
12/// Growth follows the infallible allocation contract of `ProtoList`: capacity
13/// overflow or reservation failure invokes the global allocation-failure handler.
14///
15/// Its serde `Deserialize` asks a human-readable deserializer for any kind, so
16/// a mismatched token is rejected by kind without echoing its value. Formats
17/// that coerce scalars only on a typed request, such as YAML, therefore no
18/// longer coerce here; other deserializers keep the typed request.
19///
20/// ```compile_fail
21/// let mut values: buffa::sensitive::List<u64> = [3, 1, 2].into_iter().collect();
22/// values.sort();
23/// ```
24///
25/// ```compile_fail
26/// let mut values: buffa::sensitive::List<u64> = [3, 1, 2].into_iter().collect();
27/// values.iter_mut().into_slice().sort();
28/// ```
29pub struct List<T: Zeroize>(Vec<T>);
30impl<T: Zeroize> List<T> {
31    /// Append an element without releasing an unwiped old allocation.
32    pub fn push(&mut self, value: T) {
33        if self.0.len() == self.0.capacity() {
34            // This check also covers zero-sized types: their capacity is
35            // usize::MAX, and Vec::push would otherwise panic at that length.
36            let needed = match self.0.len().checked_add(1) {
37                Some(needed) => needed,
38                None => alloc::alloc::handle_alloc_error(alloc::alloc::Layout::new::<T>()),
39            };
40            let capacity = self
41                .0
42                .capacity()
43                .checked_mul(2)
44                .unwrap_or(needed)
45                .max(needed);
46            let mut next = Vec::new();
47            // ProtoList's insertion contract is infallible. Reserve before
48            // copying any secrets and follow the global allocation-failure
49            // handler if the request cannot be satisfied.
50            if next.try_reserve_exact(capacity).is_err() {
51                alloc::alloc::handle_alloc_error(alloc::alloc::Layout::new::<T>());
52            }
53            next.append(&mut self.0);
54            let mut previous = core::mem::replace(&mut self.0, next);
55            // The elements were moved, so only their vacated storage remains.
56            previous.zeroize();
57        }
58        self.0.push(value);
59    }
60    /// The element capacity currently owned by the collection.
61    pub fn capacity(&self) -> usize {
62        self.0.capacity()
63    }
64    /// Mutably borrow one element without exposing a mutable slice.
65    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
66        self.0.get_mut(index)
67    }
68    /// Mutably borrow elements without exposing slice allocation methods.
69    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
70        IterMut(self.0.iter_mut())
71    }
72    /// Erase all elements and spare capacity, leaving the list empty.
73    pub fn clear(&mut self) {
74        // Element slots vacated by the destructors (discriminants, inactive
75        // payload bytes, buffer headers, padding) are wiped once every
76        // destructor has run.
77        super::zeroize_vec(&mut self.0);
78    }
79}
80impl<T: Zeroize> Default for List<T> {
81    fn default() -> Self {
82        Self(Vec::new())
83    }
84}
85impl<T: Zeroize> Zeroize for List<T> {
86    fn zeroize(&mut self) {
87        self.clear();
88    }
89}
90impl<T: Zeroize> Drop for List<T> {
91    fn drop(&mut self) {
92        self.zeroize();
93    }
94}
95impl<T: Zeroize> ZeroizeOnDrop for List<T> {}
96impl<T: Zeroize + Clone> Clone for List<T> {
97    fn clone(&self) -> Self {
98        self.iter().cloned().collect()
99    }
100}
101impl<T: Zeroize + PartialEq> PartialEq for List<T> {
102    fn eq(&self, other: &Self) -> bool {
103        self.0 == other.0
104    }
105}
106impl<T: Zeroize + Eq> Eq for List<T> {}
107impl<T: Zeroize> fmt::Debug for List<T> {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        f.write_str("List([REDACTED])")
110    }
111}
112impl<T: Zeroize> Deref for List<T> {
113    type Target = [T];
114    fn deref(&self) -> &[T] {
115        &self.0
116    }
117}
118impl<T: Zeroize> From<Vec<T>> for List<T> {
119    fn from(value: Vec<T>) -> Self {
120        Self(value)
121    }
122}
123impl<T: Zeroize> FromIterator<T> for List<T> {
124    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
125        let mut list = Self::default();
126        for value in iter {
127            list.push(value);
128        }
129        list
130    }
131}
132impl<T: Zeroize + Clone + PartialEq + Send + Sync> crate::ProtoList<T> for List<T> {
133    fn push(&mut self, value: T) {
134        self.push(value);
135    }
136    fn clear(&mut self) {
137        self.clear();
138    }
139}
140#[cfg(feature = "json")]
141impl<T: Zeroize + serde::Serialize> serde::Serialize for List<T> {
142    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
143        serde::Serialize::serialize(&*self.0, serializer)
144    }
145}
146#[cfg(feature = "json")]
147impl<'de, T: Zeroize + serde::Deserialize<'de>> serde::Deserialize<'de> for List<T> {
148    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
149        struct V<T>(core::marker::PhantomData<T>);
150        impl<'de, T: Zeroize + serde::Deserialize<'de>> serde::de::Visitor<'de> for V<T> {
151            type Value = List<T>;
152            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153                f.write_str("an array")
154            }
155            fn visit_seq<A: serde::de::SeqAccess<'de>>(
156                self,
157                mut seq: A,
158            ) -> Result<Self::Value, A::Error> {
159                let mut list = List::default();
160                while let Some(value) = seq.next_element()? {
161                    list.push(value);
162                }
163                Ok(list)
164            }
165            crate::reject_other_json_kinds!(
166                bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf, unit, map
167            );
168        }
169        // A typed request lets a self-describing parser report a mismatched
170        // token, value included, without consulting the visitor.
171        if deserializer.is_human_readable() {
172            deserializer.deserialize_any(V(core::marker::PhantomData))
173        } else {
174            deserializer.deserialize_seq(V(core::marker::PhantomData))
175        }
176    }
177}
178
179impl<'a, T: Zeroize> IntoIterator for &'a List<T> {
180    type Item = &'a T;
181    type IntoIter = core::slice::Iter<'a, T>;
182    fn into_iter(self) -> Self::IntoIter {
183        self.iter()
184    }
185}
186impl<'a, T: Zeroize> IntoIterator for &'a mut List<T> {
187    type Item = &'a mut T;
188    type IntoIter = IterMut<'a, T>;
189    fn into_iter(self) -> Self::IntoIter {
190        self.iter_mut()
191    }
192}
193
194/// Mutable element borrows that cannot be converted into a mutable slice.
195pub struct IterMut<'a, T>(core::slice::IterMut<'a, T>);
196impl<'a, T> Iterator for IterMut<'a, T> {
197    type Item = &'a mut T;
198    fn next(&mut self) -> Option<Self::Item> {
199        self.0.next()
200    }
201    fn size_hint(&self) -> (usize, Option<usize>) {
202        self.0.size_hint()
203    }
204}
205impl<T> DoubleEndedIterator for IterMut<'_, T> {
206    fn next_back(&mut self) -> Option<Self::Item> {
207        self.0.next_back()
208    }
209}
210impl<T> ExactSizeIterator for IterMut<'_, T> {}
211impl<T> core::iter::FusedIterator for IterMut<'_, T> {}
212impl<T> fmt::Debug for IterMut<'_, T> {
213    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214        f.write_str("IterMut([REDACTED])")
215    }
216}
217
218impl<T: Zeroize> IntoIterator for List<T> {
219    type Item = T;
220    type IntoIter = super::ViewIntoIter<T>;
221    fn into_iter(mut self) -> Self::IntoIter {
222        Self::IntoIter::with_cleanup(core::mem::take(&mut self.0), T::zeroize)
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229    #[test]
230    fn growth_clone_and_clear_keep_values_owned() {
231        let mut values = List::default();
232        for n in 0..100u64 {
233            values.push(n);
234        }
235        assert_eq!(values.len(), 100);
236        let mut cloned = values.clone();
237        *cloned.get_mut(0).unwrap() = 42;
238        assert_eq!(values[0], 0);
239        assert_eq!(cloned[0], 42);
240        values.clear();
241        assert!(values.is_empty());
242        values.push(7);
243        assert_eq!(&*values, &[7]);
244    }
245
246    #[test]
247    fn mutable_iteration_keeps_elements_in_their_cleanup_owner() {
248        let mut values: List<u64> = [1, 2, 3].into_iter().collect();
249        assert!(values.get_mut(3).is_none());
250        let mut iter = values.iter_mut();
251        assert_eq!(iter.len(), 3);
252        *iter.next().unwrap() = 7;
253        *iter.next_back().unwrap() = 9;
254        assert_eq!(iter.len(), 1);
255        assert_eq!(alloc::format!("{iter:?}"), "IterMut([REDACTED])");
256        for value in &mut values {
257            *value += 1;
258        }
259        assert_eq!(&*values, &[8, 3, 10]);
260    }
261
262    #[test]
263    fn unconsumed_elements_are_zeroized_even_without_their_own_drop() {
264        use alloc::rc::Rc;
265        use core::cell::Cell;
266        struct Counted(Rc<Cell<usize>>);
267        impl Zeroize for Counted {
268            fn zeroize(&mut self) {
269                self.0.set(self.0.get() + 1);
270            }
271        }
272        let erased = Rc::new(Cell::new(0));
273        let mut values = List::default();
274        values.push(Counted(erased.clone()));
275        values.push(Counted(erased.clone()));
276        let mut iter = values.into_iter();
277        let mut transferred = iter.next().unwrap();
278        assert_eq!(erased.get(), 0);
279        drop(iter);
280        assert_eq!(erased.get(), 1);
281        transferred.zeroize();
282        assert_eq!(erased.get(), 2);
283    }
284    #[cfg(feature = "json")]
285    #[test]
286    fn native_serde_rejects_later_invalid_elements() {
287        let values: List<u64> = serde_json::from_str("[1,2,3]").unwrap();
288        assert_eq!(&*values, &[1, 2, 3]);
289        assert_eq!(serde_json::to_string(&values).unwrap(), "[1,2,3]");
290        assert!(serde_json::from_str::<List<u64>>("[1,2,[]]").is_err());
291    }
292
293    #[test]
294    fn empty_list_erases_the_allocation_it_still_owns() {
295        let mut allocation = Vec::with_capacity(32);
296        let capacity = allocation.capacity();
297        allocation.resize(capacity, 0xA5_u8);
298        allocation.clear();
299        let mut values = List::from(allocation);
300
301        values.clear();
302
303        assert!(values.is_empty());
304        assert_eq!(values.capacity(), capacity);
305        // SAFETY: every byte was initialized before Vec::clear, which keeps
306        // the allocation. List::clear also retains it; u8 has no padding or
307        // invalid representations. The fresh pointer borrows that live owner.
308        let bytes = unsafe { core::slice::from_raw_parts(values.0.as_ptr(), capacity) };
309        assert!(bytes.iter().all(|byte| *byte == 0));
310    }
311
312    #[test]
313    fn clearing_preserves_valid_elements_until_their_destructors_finish() {
314        use core::num::NonZeroU64;
315        use core::sync::atomic::{AtomicUsize, Ordering};
316
317        static DROPS: AtomicUsize = AtomicUsize::new(0);
318        #[repr(transparent)]
319        struct Element(NonZeroU64);
320        impl Zeroize for Element {
321            fn zeroize(&mut self) {
322                self.0 = NonZeroU64::MIN;
323            }
324        }
325        impl Drop for Element {
326            fn drop(&mut self) {
327                // The backing allocation may be zeroed only after this valid
328                // typed value has finished its lifetime.
329                assert_eq!(self.0, NonZeroU64::MIN);
330                DROPS.fetch_add(1, Ordering::SeqCst);
331            }
332        }
333
334        let mut expected_drops = 0_usize;
335        for explicit_clear in [false, true] {
336            let mut allocation = Vec::with_capacity(4);
337            let capacity = allocation.capacity();
338            allocation.resize_with(capacity, || Element(NonZeroU64::MAX));
339            let mut values = List::from(allocation);
340            if explicit_clear {
341                values.clear();
342                assert!(values.is_empty());
343                assert_eq!(values.capacity(), capacity);
344                let byte_len = capacity
345                    .checked_mul(core::mem::size_of::<Element>())
346                    .unwrap();
347                // SAFETY: repr(transparent) over NonZeroU64 has no padding;
348                // all capacity slots were initialized. Cleanup and Drop leave
349                // initialized bytes, even before the final wipe. At length zero
350                // we inspect only bytes in the still-owned allocation, never an
351                // invalid all-zero Element or released memory.
352                let bytes = unsafe {
353                    core::slice::from_raw_parts(values.0.as_ptr().cast::<u8>(), byte_len)
354                };
355                assert!(bytes.iter().all(|byte| *byte == 0));
356            }
357            drop(values);
358            expected_drops = expected_drops.checked_add(capacity).unwrap();
359            assert_eq!(DROPS.load(Ordering::SeqCst), expected_drops);
360        }
361    }
362
363    #[test]
364    fn zero_sized_elements_are_cleaned_and_dropped_once() {
365        use core::sync::atomic::{AtomicUsize, Ordering};
366
367        static CLEANUPS: AtomicUsize = AtomicUsize::new(0);
368        static DROPS: AtomicUsize = AtomicUsize::new(0);
369        struct Element;
370        impl Zeroize for Element {
371            fn zeroize(&mut self) {
372                CLEANUPS.fetch_add(1, Ordering::SeqCst);
373            }
374        }
375        impl Drop for Element {
376            fn drop(&mut self) {
377                DROPS.fetch_add(1, Ordering::SeqCst);
378            }
379        }
380
381        let mut values = List::default();
382        for _ in 0..3 {
383            values.push(Element);
384        }
385        assert_eq!(values.capacity(), usize::MAX);
386        values.clear();
387        assert!(values.is_empty());
388        assert_eq!(CLEANUPS.load(Ordering::SeqCst), 3);
389        assert_eq!(DROPS.load(Ordering::SeqCst), 3);
390        drop(values);
391        assert_eq!(CLEANUPS.load(Ordering::SeqCst), 3);
392        assert_eq!(DROPS.load(Ordering::SeqCst), 3);
393    }
394}