buffa/sensitive/
owned_view.rs1use 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#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
13#[non_exhaustive]
14pub enum GuardedViewError {
15 #[error("guarded view size limit exceeded")]
17 SizeLimit,
18 #[error("could not reserve guarded view storage")]
20 Allocation,
21 #[error("guarded view encoding length mismatch")]
23 EncodingLength,
24 #[error("guarded view decode failed: {0}")]
26 Decode(#[from] DecodeError),
27}
28
29pub 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
56struct 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 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 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 #[must_use]
164 pub fn view(&self) -> &V::Reborrowed<'_> {
165 self.inner.reborrow()
166 }
167
168 #[must_use]
170 pub fn bytes(&self) -> &[u8] {
171 self.inner.bytes()
172 }
173
174 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}