Skip to main content

base64_ng_sanitization/
v2_protected.rs

1//! Protected two-allocation decode integration for the 2.0 codec.
2
3use 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/// Which protected allocation failed during a two-allocation decode.
15#[derive(Clone, Copy, Debug, Eq, PartialEq)]
16#[non_exhaustive]
17pub enum ProtectedAllocation {
18    /// Private fixed-work decode staging.
19    Staging,
20    /// Final destination returned only after the result gate.
21    Destination,
22}
23
24/// Redacted failure from a 2.0 protected sanitization decode.
25///
26/// The error preserves the failed allocation and failure class without
27/// retaining input bytes, plaintext, secret addresses, or localized invalid
28/// input details.
29#[derive(Clone, Copy, Debug, Eq, PartialEq)]
30#[non_exhaustive]
31pub enum SanitizationProtectedDecodeError {
32    /// Required controls could not be established before decoder work.
33    Protection {
34        /// Allocation whose protection setup failed.
35        allocation: ProtectedAllocation,
36    },
37    /// Canary validation failed for one protected allocation.
38    Integrity {
39        /// Allocation whose integrity check failed.
40        allocation: ProtectedAllocation,
41    },
42    /// The fixed-work secret decoder rejected the frame.
43    Decode(SecretDecodeError),
44    /// A valid frame did not produce the required fixed-size output.
45    LengthMismatch {
46        /// Required public output length.
47        expected: usize,
48        /// Actual public output length.
49        actual: usize,
50    },
51    /// An upstream protected constructor reported an inconsistent length.
52    ProtectedLength {
53        /// Allocation whose protected length was inconsistent.
54        allocation: ProtectedAllocation,
55    },
56    /// A protected destination could not be transferred after initialization.
57    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
93/// 2.0 decode helpers with separately protected staging and destination.
94///
95/// Both mappings are established under the companion's required protection
96/// request before [`SecretFrame`] receives the encoded input. The input,
97/// staging, and destination are separate logical ranges. Invalid input wipes
98/// both mappings before the error is returned.
99///
100/// For provider-owned quarantine, generation accounting, and single-allocation
101/// no-copy finalization, use [`Base64::decode_assured`] with
102/// `base64_ng::assurance::ProtectedSecret` instead. A `sanitization` mapping
103/// cannot be claimed as a core assurance allocation because its raw ownership
104/// and teardown state are intentionally not exported.
105pub trait SanitizationProtectedDecodeExt {
106    /// Decode exactly `N` bytes through protected staging into protected final
107    /// storage.
108    ///
109    /// # Errors
110    ///
111    /// Returns a redacted protection, integrity, decode, or exact-length
112    /// failure. Protection failures occur before decoder work.
113    fn decode_sanitization_protected_bytes<const N: usize>(
114        &self,
115        input: &SecretInput<'_>,
116    ) -> Result<LockedSecretBytes<N>, SanitizationProtectedDecodeError>;
117
118    /// Decode into a protected dynamic destination with public capacity `MAX`.
119    ///
120    /// Both mappings allocate `MAX` bytes before decoder work. This makes the
121    /// Base64-owned allocation shape independent of frame validity while
122    /// bounding memory use to two protected mappings of `MAX` bytes.
123    ///
124    /// # Errors
125    ///
126    /// Returns a redacted protection, integrity, decode, or protected-length
127    /// failure.
128    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}