1use base64_ng::{
4 Base64, Codec,
5 secret::{SecretDecodeError, SecretFrame, SecretInput},
6};
7use sanitization::{
8 LockedSecretBytes, LockedSecretInitializeError, LockedSecretVec, ProtectedSecretFillError,
9 SecureSanitize,
10};
11
12use crate::locked;
13
14#[derive(Clone, Copy, Debug, Eq, PartialEq)]
16#[non_exhaustive]
17pub enum ProtectedAllocation {
18 Staging,
20 Destination,
22}
23
24#[derive(Clone, Copy, Debug, Eq, PartialEq)]
30#[non_exhaustive]
31pub enum SanitizationProtectedDecodeError {
32 Protection {
34 allocation: ProtectedAllocation,
36 },
37 Integrity {
39 allocation: ProtectedAllocation,
41 },
42 Decode(SecretDecodeError),
44 LengthMismatch {
46 expected: usize,
48 actual: usize,
50 },
51 ProtectedLength {
53 allocation: ProtectedAllocation,
55 },
56 StateTransition,
58}
59
60impl core::fmt::Display for SanitizationProtectedDecodeError {
61 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
62 match self {
63 Self::Protection { allocation } => {
64 write!(
65 formatter,
66 "required {allocation:?} protection is unavailable"
67 )
68 }
69 Self::Integrity { allocation } => {
70 write!(
71 formatter,
72 "{allocation:?} protected-storage integrity failure"
73 )
74 }
75 Self::Decode(error) => error.fmt(formatter),
76 Self::LengthMismatch { expected, actual } => {
77 write!(
78 formatter,
79 "expected {expected} decoded bytes, produced {actual}"
80 )
81 }
82 Self::ProtectedLength { allocation } => {
83 write!(formatter, "{allocation:?} protected-storage length failure")
84 }
85 Self::StateTransition => formatter.write_str("protected destination transition failed"),
86 }
87 }
88}
89
90#[cfg(feature = "std")]
91impl std::error::Error for SanitizationProtectedDecodeError {}
92
93pub trait SanitizationProtectedDecodeExt {
106 fn decode_sanitization_protected_bytes<const N: usize>(
114 &self,
115 input: &SecretInput<'_>,
116 ) -> Result<LockedSecretBytes<N>, SanitizationProtectedDecodeError>;
117
118 fn decode_sanitization_protected_vec<const MAX: usize>(
129 &self,
130 input: &SecretInput<'_>,
131 ) -> Result<LockedSecretVec, SanitizationProtectedDecodeError>;
132}
133
134impl<S: Codec> SanitizationProtectedDecodeExt for Base64<S> {
135 fn decode_sanitization_protected_bytes<const N: usize>(
136 &self,
137 input: &SecretInput<'_>,
138 ) -> Result<LockedSecretBytes<N>, SanitizationProtectedDecodeError> {
139 let request = locked::required_secret_protection();
140 let staging = LockedSecretBytes::<N>::zeroed_with_protection(request).map_err(|_| {
141 SanitizationProtectedDecodeError::Protection {
142 allocation: ProtectedAllocation::Staging,
143 }
144 })?;
145 let mut destination = None;
146 let staging = staging
147 .try_init_with(|staging_bytes| {
148 let target =
149 LockedSecretBytes::<N>::zeroed_with_protection(request).map_err(|_| {
150 SanitizationProtectedDecodeError::Protection {
151 allocation: ProtectedAllocation::Destination,
152 }
153 })?;
154 let target = target
155 .try_init_with(|output| {
156 let written = decode_frame(self, input, staging_bytes, output)?;
157 if written != N {
158 return Err(SanitizationProtectedDecodeError::LengthMismatch {
159 expected: N,
160 actual: written,
161 });
162 }
163 Ok(())
164 })
165 .map_err(map_destination_initialize_error)?;
166 staging_bytes.secure_sanitize();
167 destination = Some(target);
168 Ok(())
169 })
170 .map_err(map_staging_initialize_error)?;
171 drop(staging);
172 destination.ok_or(SanitizationProtectedDecodeError::StateTransition)
173 }
174
175 fn decode_sanitization_protected_vec<const MAX: usize>(
176 &self,
177 input: &SecretInput<'_>,
178 ) -> Result<LockedSecretVec, SanitizationProtectedDecodeError> {
179 let request = locked::required_secret_protection();
180 let mut staging =
181 LockedSecretVec::try_from_exact_len_with_protection(MAX, request, |bytes| {
182 bytes.secure_sanitize();
183 Ok::<(), core::convert::Infallible>(())
184 })
185 .map_err(map_staging_fill_error)?;
186
187 LockedSecretVec::try_from_capacity_bounded_with_protection(MAX, MAX, request, |output| {
188 staging
189 .try_with_secret_mut(|staging_bytes| {
190 decode_frame(self, input, staging_bytes, output)
191 })
192 .map_err(|_| SanitizationProtectedDecodeError::Integrity {
193 allocation: ProtectedAllocation::Staging,
194 })?
195 })
196 .map_err(map_destination_fill_error)
197 }
198}
199
200fn decode_frame<S: Codec>(
201 codec: &Base64<S>,
202 input: &SecretInput<'_>,
203 staging: &mut [u8],
204 output: &mut [u8],
205) -> Result<usize, SanitizationProtectedDecodeError> {
206 let mut frame = SecretFrame::new(codec, output.len(), staging, output)
207 .map_err(SanitizationProtectedDecodeError::Decode)?;
208 frame
209 .update(input)
210 .map_err(SanitizationProtectedDecodeError::Decode)?;
211 let guarded = frame
212 .finish()
213 .map_err(SanitizationProtectedDecodeError::Decode)?;
214 let written = guarded.len();
215 drop(guarded.declassify());
216 Ok(written)
217}
218
219fn map_staging_initialize_error(
220 error: LockedSecretInitializeError<SanitizationProtectedDecodeError>,
221) -> SanitizationProtectedDecodeError {
222 match error {
223 LockedSecretInitializeError::Integrity(_) => SanitizationProtectedDecodeError::Integrity {
224 allocation: ProtectedAllocation::Staging,
225 },
226 LockedSecretInitializeError::Generate(error) => error,
227 }
228}
229
230fn map_destination_initialize_error(
231 error: LockedSecretInitializeError<SanitizationProtectedDecodeError>,
232) -> SanitizationProtectedDecodeError {
233 match error {
234 LockedSecretInitializeError::Integrity(_) => SanitizationProtectedDecodeError::Integrity {
235 allocation: ProtectedAllocation::Destination,
236 },
237 LockedSecretInitializeError::Generate(error) => error,
238 }
239}
240
241fn map_staging_fill_error(
242 error: ProtectedSecretFillError<core::convert::Infallible>,
243) -> SanitizationProtectedDecodeError {
244 map_fill_error(error, ProtectedAllocation::Staging)
245}
246
247fn map_destination_fill_error(
248 error: ProtectedSecretFillError<SanitizationProtectedDecodeError>,
249) -> SanitizationProtectedDecodeError {
250 map_fill_error(error, ProtectedAllocation::Destination)
251}
252
253fn map_fill_error<E>(
254 error: ProtectedSecretFillError<E>,
255 allocation: ProtectedAllocation,
256) -> SanitizationProtectedDecodeError
257where
258 E: IntoSanitizationProtectedDecodeError,
259{
260 match error {
261 ProtectedSecretFillError::CapacityLimit { .. } | ProtectedSecretFillError::Length(_) => {
262 SanitizationProtectedDecodeError::ProtectedLength { allocation }
263 }
264 ProtectedSecretFillError::Protection(_) => {
265 SanitizationProtectedDecodeError::Protection { allocation }
266 }
267 ProtectedSecretFillError::Fill(error) => error.into_decode_error(),
268 ProtectedSecretFillError::Integrity(_) => {
269 SanitizationProtectedDecodeError::Integrity { allocation }
270 }
271 }
272}
273
274trait IntoSanitizationProtectedDecodeError {
275 fn into_decode_error(self) -> SanitizationProtectedDecodeError;
276}
277
278impl IntoSanitizationProtectedDecodeError for SanitizationProtectedDecodeError {
279 fn into_decode_error(self) -> SanitizationProtectedDecodeError {
280 self
281 }
282}
283
284impl IntoSanitizationProtectedDecodeError for core::convert::Infallible {
285 fn into_decode_error(self) -> SanitizationProtectedDecodeError {
286 match self {}
287 }
288}