Skip to main content

buffa/sensitive/
owned_view.rs

1// Modified by ReallyMe Technologies Limited.
2//! Eager views whose wire allocation is wiped when the owner is dropped.
3use alloc::vec::Vec;
4use bytes::Bytes;
5
6use crate::view::{ViewLifetimeParametric, ViewReborrow};
7use crate::{DecodeError, DecodeOptions, EncodeSink, Message, MessageView, OwnedView};
8
9use super::{ZeroizeOnDrop, Zeroizing};
10
11/// An error constructing a [`GuardedOwnedView`].
12#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
13#[non_exhaustive]
14pub enum GuardedViewError {
15    /// The input or encoded message exceeds a size limit.
16    #[error("guarded view size limit exceeded")]
17    SizeLimit,
18    /// Reserving the wire allocation failed.
19    #[error("could not reserve guarded view storage")]
20    Allocation,
21    /// The encoder wrote a different length than it reported.
22    #[error("guarded view encoding length mismatch")]
23    EncodingLength,
24    /// The wire bytes could not be decoded as the selected message.
25    #[error("guarded view decode failed: {0}")]
26    Decode(#[from] DecodeError),
27}
28
29/// An eager view with a private wire allocation that is wiped on drop.
30///
31/// This type exposes neither a clonable handle nor the underlying `Bytes`.
32/// The input passed to [`Self::decode`] remains the caller's responsibility.
33/// For a message value, [`Self::from_owned`] encodes directly into the wiping
34/// allocation. It does not stage a second wire buffer. The view may own
35/// decoded values separately; those follow the view type's own cleanup
36/// rules. The owner implements `ZeroizeOnDrop` only when the view does too.
37///
38/// ```compile_fail
39/// use buffa::sensitive::GuardedOwnedView;
40/// fn duplicate<V>(view: &GuardedOwnedView<V>) -> GuardedOwnedView<V> {
41///     (*view).clone()
42/// }
43/// ```
44pub struct GuardedOwnedView<V> {
45    inner: OwnedView<V>,
46}
47
48struct WireOwner(Zeroizing<Vec<u8>>);
49
50impl AsRef<[u8]> for WireOwner {
51    fn as_ref(&self) -> &[u8] {
52        &self.0
53    }
54}
55
56// Restrict writes to the pre-reserved length. A malformed manual Message
57// implementation must not make the buffer reallocate and release unwiped data,
58// or panic when a write exceeds its declared size.
59struct WireSink {
60    bytes: Zeroizing<Vec<u8>>,
61    expected_len: usize,
62    overrun: bool,
63}
64
65impl WireSink {
66    fn new(expected_len: usize) -> Result<Self, GuardedViewError> {
67        let mut bytes = Zeroizing::new(Vec::new());
68        bytes
69            .try_reserve_exact(expected_len)
70            .map_err(|_| GuardedViewError::Allocation)?;
71        Ok(Self {
72            bytes,
73            expected_len,
74            overrun: false,
75        })
76    }
77
78    fn finish(self) -> Result<WireOwner, GuardedViewError> {
79        if self.overrun || self.bytes.len() != self.expected_len {
80            return Err(GuardedViewError::EncodingLength);
81        }
82        Ok(WireOwner(self.bytes))
83    }
84}
85
86impl EncodeSink for WireSink {
87    fn put_u8(&mut self, byte: u8) {
88        self.put_slice(core::slice::from_ref(&byte));
89    }
90    fn put_slice(&mut self, source: &[u8]) {
91        if self.overrun {
92            return;
93        }
94        if self
95            .bytes
96            .len()
97            .checked_add(source.len())
98            .is_some_and(|len| len <= self.expected_len)
99        {
100            self.bytes.extend_from_slice(source);
101        } else {
102            self.overrun = true;
103        }
104    }
105    fn put_u32_le(&mut self, value: u32) {
106        self.put_slice(&value.to_le_bytes());
107    }
108    fn put_u64_le(&mut self, value: u64) {
109        self.put_slice(&value.to_le_bytes());
110    }
111}
112
113impl<V: ViewLifetimeParametric> GuardedOwnedView<V> {
114    /// Copy a borrowed wire buffer into private storage and decode eagerly.
115    ///
116    /// # Errors
117    ///
118    /// Rejects over-limit input before allocating and returns an error on
119    /// wire buffer reservation failure or malformed wire data.
120    pub fn decode(source: &[u8], options: &DecodeOptions) -> Result<Self, GuardedViewError> {
121        Self::check_size(source.len(), options)?;
122        let mut sink = WireSink::new(source.len())?;
123        sink.put_slice(source);
124        Self::admit(sink.finish()?, options)
125    }
126
127    /// Encode directly into private storage, then decode eagerly.
128    ///
129    /// # Errors
130    ///
131    /// Returns an error if the encoded length exceeds a limit, reserving the
132    /// wire buffer fails, the encoder's actual length disagrees, or the view rejects the
133    /// resulting bytes under the supplied options.
134    pub fn from_owned(
135        message: &V::Owned,
136        options: &DecodeOptions,
137    ) -> Result<Self, GuardedViewError> {
138        let mut cache = crate::SizeCache::new();
139        let size = usize::try_from(message.compute_size(&mut cache))
140            .map_err(|_| GuardedViewError::SizeLimit)?;
141        Self::check_size(size, options)?;
142        let mut sink = WireSink::new(size)?;
143        message.write_to(&mut cache, &mut sink);
144        Self::admit(sink.finish()?, options)
145    }
146
147    fn check_size(size: usize, options: &DecodeOptions) -> Result<(), GuardedViewError> {
148        if size > options.max_message_size() {
149            Err(GuardedViewError::SizeLimit)
150        } else {
151            Ok(())
152        }
153    }
154
155    fn admit(owner: WireOwner, options: &DecodeOptions) -> Result<Self, GuardedViewError> {
156        let inner = OwnedView::decode_with_options(Bytes::from_owner(owner), options)?;
157        Ok(Self { inner })
158    }
159}
160
161impl<V: ViewReborrow> GuardedOwnedView<V> {
162    /// Borrow the decoded view for as long as this owner is borrowed.
163    #[must_use]
164    pub fn view(&self) -> &V::Reborrowed<'_> {
165        self.inner.reborrow()
166    }
167
168    /// Borrow the private encoded bytes without transferring ownership.
169    #[must_use]
170    pub fn bytes(&self) -> &[u8] {
171        self.inner.bytes()
172    }
173
174    /// Convert fields to their owned representations without sharing the wire
175    /// allocation. The message's field types determine their own cleanup.
176    ///
177    /// # Errors
178    ///
179    /// Returns the view's conversion error if its owned representation
180    /// cannot be built.
181    pub fn to_owned_message(&self) -> Result<V::Owned, DecodeError> {
182        self.view().to_owned_message()
183    }
184}
185
186impl<V> core::fmt::Debug for GuardedOwnedView<V> {
187    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
188        f.write_str("GuardedOwnedView([REDACTED])")
189    }
190}
191
192impl<V: ZeroizeOnDrop> ZeroizeOnDrop for GuardedOwnedView<V> {}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    #[test]
199    fn bounded_sink_rejects_length_mismatches() {
200        let mut overrun = WireSink::new(2).unwrap();
201        overrun.put_u8(1);
202        overrun.put_slice(&[2, 3]);
203        overrun.put_u8(4);
204        assert_eq!(overrun.bytes.as_slice(), [1]);
205        assert!(matches!(
206            overrun.finish(),
207            Err(GuardedViewError::EncodingLength)
208        ));
209
210        let mut underrun = WireSink::new(2).unwrap();
211        underrun.put_u8(1);
212        assert!(matches!(
213            underrun.finish(),
214            Err(GuardedViewError::EncodingLength)
215        ));
216    }
217}