Skip to main content

sanitization/
owned.rs

1#[cfg(feature = "alloc")]
2use alloc::{boxed::Box, string::String, vec::Vec};
3use core::{
4    fmt,
5    hint::black_box,
6    marker::PhantomData,
7    sync::atomic::{compiler_fence, Ordering},
8};
9
10use crate::{ct, wipe, wipe_backend};
11
12/// Error returned when a caller provides a buffer with the wrong length.
13#[derive(Clone, Copy, Debug, Eq, PartialEq)]
14pub struct LengthError {
15    /// Number of bytes required by the operation.
16    pub expected: usize,
17    /// Number of bytes provided by the caller.
18    pub actual: usize,
19}
20
21impl fmt::Display for LengthError {
22    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
23        write!(
24            formatter,
25            "length mismatch: expected {} bytes, got {} bytes",
26            self.expected, self.actual
27        )
28    }
29}
30
31#[cfg(feature = "std")]
32impl std::error::Error for LengthError {}
33
34/// Clear the currently reachable sensitive contents owned by a value.
35///
36/// The crate implements this trait for common scalar types, arrays, slices,
37/// `Option<T>`, `Result<T, E>`, and, with `alloc`, `Box<T>`, `Vec<T>`, and
38/// `String`. Opaque third-party types cannot be implemented here without
39/// taking dependencies on them; wrap those values in a local newtype and
40/// implement this trait there.
41///
42/// # Implementer contract
43///
44/// An implementation must:
45///
46/// - be idempotent;
47/// - avoid panicking where reasonably possible;
48/// - allocate no new storage while sanitizing;
49/// - leave the value valid for later sanitization and drop;
50/// - clear every currently owned secret element and all reachable
51///   secret-bearing allocation capacity;
52/// - clear secret-bearing storage before releasing, replacing, or transferring
53///   that storage; and
54/// - when called from a destructor path, never trigger destruction of that
55///   same value while its sanitization call is still active;
56/// - document external allocations, shared storage, historical copies,
57///   representation padding, allocator metadata, platform copies, or other
58///   secret-bearing state that it cannot reach.
59///
60/// This contract covers the value and storage reachable when
61/// [`SecureSanitize::secure_sanitize`] is called. It does not imply that the
62/// type's other safe operations preserve storage, and it cannot recover
63/// allocations or copies that were already released.
64///
65/// References, shared owners such as `Rc` and `Arc`, `NonZero*`,
66/// `MaybeUninit<T>`, unions, and types whose all-zero representation is invalid
67/// need type-specific review. The crate intentionally provides no blanket
68/// implementation for those categories.
69///
70/// Raw pointers and arbitrary user-defined `Copy` types are not accepted by
71/// the built-in representation wipe:
72///
73/// ```compile_fail
74/// use sanitization::SecureSanitize;
75///
76/// let byte = 7_u8;
77/// let mut pointer = &byte as *const u8;
78/// pointer.secure_sanitize();
79/// ```
80///
81/// ```compile_fail
82/// use sanitization::SecureSanitize;
83///
84/// #[derive(Clone, Copy)]
85/// struct Unreviewed(u32);
86///
87/// let mut value = Unreviewed(7);
88/// value.secure_sanitize();
89/// ```
90pub trait SecureSanitize {
91    /// Clear the sensitive bytes owned by this value.
92    fn secure_sanitize(&mut self);
93}
94
95/// Security contract for calling [`SecureSanitize`] from the value's destructor.
96///
97/// Implementing this marker asserts that `secure_sanitize` preserves all
98/// aggregate cleanup behavior when called from `Drop` and cannot destroy,
99/// replace, or otherwise recursively enter destruction of the same value while
100/// that call remains active. The implementation must remain valid when the
101/// value is logically pinned; generated drop code separately requires
102/// [`Unpin`](core::marker::Unpin) before obtaining `&mut Self`.
103///
104/// This is a normal trait because an incorrect implementation violates a
105/// security and availability contract, but must not be relied on for Rust
106/// memory safety. Manual implementations are an explicit review point and
107/// should include a `DROP SANITIZE CONTRACT` comment covering external
108/// storage, ordering requirements, and why the sanitizer cannot recursively
109/// destroy `Self`.
110///
111/// `#[derive(SecureSanitize)]` and [`crate::secure_sanitize_struct!`] implement this
112/// marker automatically for their generated field-wise sanitizers. Types with
113/// reviewed manual aggregate sanitizers must implement it explicitly before
114/// deriving `SecureSanitizeOnDrop`.
115#[diagnostic::on_unimplemented(
116    message = "`{Self}` is not approved for destructor-path sanitization",
117    label = "`SecureSanitizeOnDrop` requires `DropSafeSanitize`",
118    note = "derive `SecureSanitize` for a generated field-wise sanitizer, or explicitly implement `DropSafeSanitize` after reviewing a manual aggregate sanitizer"
119)]
120pub trait DropSafeSanitize: SecureSanitize {}
121
122/// Security contract for secret storage exposed through shared references.
123///
124/// Implementing this marker asserts:
125///
126/// > No safe operation provided by the type and reachable through `&self`
127/// > releases, transfers, replaces, or schedules later release of
128/// > secret-bearing storage without clearing it first.
129///
130/// The assertion covers inherent and trait methods, interior mutation,
131/// returned guards and destructors, callbacks invoked by those methods, and
132/// deferred cleanup they schedule. The type must retain a valid later
133/// [`SecureSanitize`] and drop path and document external, shared, deferred, or
134/// historical storage it cannot reach.
135///
136/// This is a normal trait rather than an `unsafe trait`: an incorrect
137/// implementation violates a security promise but must never be relied on for
138/// Rust memory safety. Generic guarantees are conditional on downstream
139/// implementations satisfying this contract.
140///
141/// High-assurance applications should not accept arbitrary third-party
142/// implementations merely because they satisfy this public marker. Maintain an
143/// application-level allow-list of reviewed concrete types, or expose only
144/// constructors and APIs whose generic bounds are closed over that reviewed
145/// set. The crate keeps this trait public so downstream fixed-storage types can
146/// opt in without making their implementations part of this crate.
147///
148/// Deliberate copying, logging, `mem::replace`, or calls to external code by an
149/// exposure closure remain caller responsibility. This marker describes the
150/// operations supplied by the marked type; it does not make hostile closure
151/// code safe.
152///
153/// # Manual implementations
154///
155/// Manual implementations should include a `STORAGE CONTRACT` comment that
156/// identifies every safe shared operation and explains why none can release
157/// uncleared secret storage:
158///
159/// ```
160/// use sanitization::{SecureSanitize, StableSharedSecretStorage};
161///
162/// struct FixedRecord {
163///     key: [u8; 32],
164/// }
165///
166/// impl SecureSanitize for FixedRecord {
167///     fn secure_sanitize(&mut self) {
168///         self.key.secure_sanitize();
169///     }
170/// }
171///
172/// // STORAGE CONTRACT: shared methods only inspect the inline byte array.
173/// impl StableSharedSecretStorage for FixedRecord {}
174/// ```
175///
176/// Types with interior mutation are not stable merely because their
177/// `SecureSanitize` implementation clears the current value:
178///
179/// ```compile_fail
180/// use std::cell::RefCell;
181/// use sanitization::{wipe, SecureSanitize, StableSharedSecretStorage};
182///
183/// struct Rotating {
184///     bytes: RefCell<Vec<u8>>,
185/// }
186///
187/// impl SecureSanitize for Rotating {
188///     fn secure_sanitize(&mut self) {
189///         let bytes = self.bytes.get_mut();
190///         wipe::bytes(bytes.as_mut_slice());
191///         bytes.clear();
192///     }
193/// }
194///
195/// fn require_shared_stability<T: StableSharedSecretStorage>() {}
196///
197/// // Rejected: `Rotating` can replace its allocation through `&self`.
198/// require_shared_stability::<Rotating>();
199/// ```
200#[diagnostic::on_unimplemented(
201    message = "`{Self}` does not guarantee stable shared secret storage",
202    label = "generic shared secret exposure requires `StableSharedSecretStorage`",
203    note = "use a dedicated secret container or implement and document the storage contract for a reviewed fixed-storage type"
204)]
205pub trait StableSharedSecretStorage: SecureSanitize {}
206
207/// Security contract for secret storage exposed through mutable references.
208///
209/// This extends [`StableSharedSecretStorage`] and asserts that no safe operation
210/// provided by the type and reachable through `&mut self` releases, transfers,
211/// replaces, or schedules later release of secret-bearing storage without
212/// clearing it first.
213///
214/// The same interior-mutation, guard, callback, destructor, deferred-cleanup,
215/// documentation, and caller-responsibility rules described by
216/// [`StableSharedSecretStorage`] apply. Manual implementations should include a
217/// `STORAGE CONTRACT` comment covering both shared and mutable operations.
218///
219/// The crate intentionally does not implement this trait for `Vec<T>`,
220/// `String`, `Box<T>`, references, shared owners, or arbitrary third-party
221/// containers.
222///
223/// ```compile_fail
224/// use sanitization::{wipe, SecureSanitize, StableMutableSecretStorage};
225///
226/// struct Reallocating(Vec<u8>);
227///
228/// impl Reallocating {
229///     fn replace_without_clearing(&mut self, replacement: Vec<u8>) {
230///         self.0 = replacement;
231///     }
232/// }
233///
234/// impl SecureSanitize for Reallocating {
235///     fn secure_sanitize(&mut self) {
236///         wipe::bytes(self.0.as_mut_slice());
237///         self.0.clear();
238///     }
239/// }
240///
241/// fn require_mutable_stability<T: StableMutableSecretStorage>() {}
242///
243/// // Rejected: the old allocation can be released by a safe mutable method.
244/// require_mutable_stability::<Reallocating>();
245/// ```
246#[diagnostic::on_unimplemented(
247    message = "`{Self}` does not guarantee stable mutable secret storage",
248    label = "generic mutable secret exposure requires `StableMutableSecretStorage`",
249    note = "use a dedicated secret container or implement and document the storage contract for a reviewed fixed-storage type"
250)]
251pub trait StableMutableSecretStorage: StableSharedSecretStorage {}
252
253/// Application-controlled allow-list for concrete secret storage types.
254///
255/// This policy is an additional gate, not a replacement for
256/// [`StableSharedSecretStorage`] or [`StableMutableSecretStorage`]. A policy
257/// implementation approves one exact `T` for one application-owned policy
258/// type. [`AllowlistedSecret`] still requires the relevant storage-stability
259/// contract before exposing `T`.
260///
261/// High-assurance applications should define one private or crate-visible
262/// policy type in a reviewed module and implement this trait only for accepted
263/// concrete storage types. Dependencies cannot name a non-public policy. A
264/// public policy may be implementable by a dependency for a storage type that
265/// dependency owns under Rust's orphan rules. Prefer
266/// [`crate::define_secret_storage_policy!`] with no visibility or `pub(crate)` so
267/// every approval stays local and carries a review rationale in one searchable
268/// declaration.
269///
270/// This trait does not prove that `T` satisfies its storage contract. It makes
271/// the deployment's concrete-type decision explicit and centrally auditable.
272#[diagnostic::on_unimplemented(
273    message = "`{Self}` does not allow-list `{T}` as secret storage",
274    label = "this exact storage type is absent from the selected policy",
275    note = "review the type and add it with `define_secret_storage_policy!`, or select an already approved type"
276)]
277pub trait SecretStoragePolicy<T: SecureSanitize> {
278    /// Human-readable reason this exact type is accepted by the policy.
279    const RATIONALE: &'static str;
280}
281
282/// Define an application-owned concrete-type allow-list for
283/// [`AllowlistedSecret`].
284///
285/// Each entry requires a non-empty literal rationale that is not solely ASCII
286/// whitespace. The generated policy is an uninhabited marker type and
287/// implements [`SecretStoragePolicy<T>`] only for the listed exact types.
288///
289/// ```
290/// use sanitization::{
291///     define_secret_storage_policy, AllowlistedSecret, SecureSanitize,
292///     StableMutableSecretStorage, StableSharedSecretStorage,
293/// };
294///
295/// struct Credentials([u8; 32]);
296///
297/// impl SecureSanitize for Credentials {
298///     fn secure_sanitize(&mut self) {
299///         self.0.secure_sanitize();
300///     }
301/// }
302///
303/// // STORAGE CONTRACT: all safe operations retain the inline byte array.
304/// impl StableSharedSecretStorage for Credentials {}
305/// impl StableMutableSecretStorage for Credentials {}
306///
307/// define_secret_storage_policy! {
308///     pub(crate) DeploymentStoragePolicy {
309///         Credentials => "reviewed fixed inline storage with no interior mutation",
310///     }
311/// }
312///
313/// let mut secret =
314///     AllowlistedSecret::<Credentials, DeploymentStoragePolicy>::new(
315///         Credentials([7; 32]),
316///     );
317/// assert_eq!(secret.with_secret(|value| value.0[0]), 7);
318/// secret.with_secret_mut(|value| value.0[0] = 9);
319/// ```
320#[macro_export]
321macro_rules! define_secret_storage_policy {
322    (
323        $(#[$metadata:meta])*
324        $visibility:vis $policy:ident {
325            $($storage:ty => $reason:literal),+ $(,)?
326        }
327    ) => {
328        $(#[$metadata])*
329        $visibility enum $policy {}
330
331        $(
332            const _: () = {
333                let reason: &str = $reason;
334                let bytes = reason.as_bytes();
335                let mut index = 0;
336                let mut has_content = false;
337                while index < bytes.len() {
338                    let byte = bytes[index];
339                    if byte != b' '
340                        && byte != b'\t'
341                        && byte != b'\n'
342                        && byte != b'\r'
343                        && byte != 0x0b
344                        && byte != 0x0c
345                    {
346                        has_content = true;
347                    }
348                    index += 1;
349                }
350                assert!(
351                    has_content,
352                    "secret storage policy rationale must not be empty or ASCII-whitespace-only",
353                );
354            };
355
356            impl $crate::SecretStoragePolicy<$storage> for $policy {
357                const RATIONALE: &'static str = $reason;
358            }
359        )+
360    };
361}
362
363/// Sanitize a value before replacing it.
364///
365/// This is the safe replacement pattern for values whose previous contents may
366/// hold secrets, especially manually implemented enums that move from a
367/// secret-bearing variant to a non-secret variant. Calling `secure_sanitize`
368/// after assigning a unit or empty variant is too late; use `secure_replace` to
369/// clear first. Derive macros reject enums because they cannot enforce this
370/// transition discipline.
371#[inline]
372pub fn secure_replace<T: SecureSanitize>(slot: &mut T, replacement: T) {
373    slot.secure_sanitize();
374    *slot = replacement;
375}
376
377/// Sanitize one application-owned root value and then deliberately abort.
378///
379/// This helper is only for fatal paths that explicitly choose to abort. It
380/// sanitizes `root` before invoking [`std::process::abort`]. Aggregate all
381/// reachable secret owners into a struct or tuple when more than one value must
382/// be cleared.
383///
384/// This does **not** install a panic, signal, or process-wide abort hook. It
385/// cannot clear compiler temporaries, external copies, unrelated owners, or
386/// secrets when another component aborts directly. Ordinary destructors still
387/// do not run after process abort.
388#[cfg(feature = "std")]
389#[inline(never)]
390pub fn sanitize_then_abort<T: SecureSanitize + ?Sized>(root: &mut T) -> ! {
391    root.secure_sanitize();
392    compiler_fence(Ordering::SeqCst);
393    black_box(&mut *root);
394    std::process::abort()
395}
396
397macro_rules! impl_secure_sanitize_scalar {
398    ($($ty:ty),+ $(,)?) => {
399        $(
400            impl SecureSanitize for $ty {
401                #[inline(never)]
402                fn secure_sanitize(&mut self) {
403                    wipe_backend::erase_plain_data(self);
404                }
405            }
406
407            impl StableSharedSecretStorage for $ty {}
408            impl StableMutableSecretStorage for $ty {}
409        )+
410    };
411}
412
413impl_secure_sanitize_scalar!(
414    u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, bool, char, f32, f64,
415);
416
417/// Declare a struct and generate [`SecureSanitize`] for all fields.
418///
419/// This is a dependency-free alternative to a derive macro. Each field type
420/// must implement [`SecureSanitize`]. The macro does not implement [`Drop`], so
421/// use this form when the type needs custom drop behavior or is wrapped in
422/// [`Secret`].
423///
424/// This macro intentionally supports named-field structs without generics or
425/// `where` clauses. For generic structs, implement [`SecureSanitize`] manually
426/// so the impl generics and bounds stay explicit.
427///
428/// ```
429/// use sanitization::{secure_sanitize_struct, SecretBytes, SecureSanitize};
430///
431/// secure_sanitize_struct! {
432///     struct Credentials {
433///         key: SecretBytes<32>,
434///         nonce: SecretBytes<12>,
435///     }
436/// }
437///
438/// let mut credentials = Credentials {
439///     key: SecretBytes::from_array([1; 32]),
440///     nonce: SecretBytes::from_array([2; 12]),
441/// };
442///
443/// credentials.secure_sanitize();
444/// ```
445#[macro_export]
446macro_rules! secure_sanitize_struct {
447    (
448        $(#[$attr:meta])*
449        $vis:vis struct $name:ident {
450            $(
451                $(#[$field_attr:meta])*
452                $field_vis:vis $field:ident: $field_ty:ty
453            ),* $(,)?
454        }
455    ) => {
456        $(#[$attr])*
457        $vis struct $name {
458            $(
459                $(#[$field_attr])*
460                $field_vis $field: $field_ty,
461            )*
462        }
463
464        impl $crate::SecureSanitize for $name {
465            #[inline]
466            fn secure_sanitize(&mut self) {
467                $(
468                    $crate::SecureSanitize::secure_sanitize(&mut self.$field);
469                )*
470            }
471        }
472
473        impl $crate::DropSafeSanitize for $name {}
474    };
475}
476
477/// Declare a struct and generate [`SecureSanitize`] plus [`Drop`].
478///
479/// This macro owns the type's [`Drop`] implementation. Use
480/// [`crate::secure_sanitize_struct!`] instead when custom drop behavior is required.
481/// The generated destructor requires the declared struct to implement
482/// [`DropSafeSanitize`] and [`Unpin`](core::marker::Unpin), then calls its
483/// complete [`SecureSanitize`] implementation. The generated sanitizer is
484/// field-wise, so the marker is provided automatically.
485///
486/// This macro intentionally supports named-field structs without generics or
487/// `where` clauses. For generic structs, implement [`SecureSanitize`] and
488/// [`Drop`] manually so the impl generics and bounds stay explicit.
489///
490/// ```
491/// use sanitization::{secure_drop_struct, SecretBytes};
492///
493/// secure_drop_struct! {
494///     struct Credentials {
495///         key: SecretBytes<32>,
496///         nonce: SecretBytes<12>,
497///     }
498/// }
499/// ```
500#[macro_export]
501macro_rules! secure_drop_struct {
502    (
503        $(#[$attr:meta])*
504        $vis:vis struct $name:ident {
505            $(
506                $(#[$field_attr:meta])*
507                $field_vis:vis $field:ident: $field_ty:ty
508            ),* $(,)?
509        }
510    ) => {
511        $crate::secure_sanitize_struct! {
512            $(#[$attr])*
513            $vis struct $name {
514                $(
515                    $(#[$field_attr])*
516                    $field_vis $field: $field_ty,
517                )*
518            }
519        }
520
521        impl Drop for $name {
522            #[inline]
523            fn drop(&mut self) {
524                fn require_drop_contract<T: ?Sized + $crate::DropSafeSanitize + ::core::marker::Unpin>() {}
525                require_drop_contract::<Self>();
526                $crate::SecureSanitize::secure_sanitize(self);
527            }
528        }
529    };
530}
531
532#[cfg(feature = "alloc")]
533#[inline(never)]
534pub(crate) fn sanitize_vec_capacity(bytes: &mut Vec<u8>) {
535    wipe::vec(bytes);
536}
537
538#[cfg(all(feature = "alloc", feature = "multi-pass-clear"))]
539#[inline(never)]
540fn sanitize_vec_capacity_multi_pass(bytes: &mut Vec<u8>) {
541    wipe::vec_multi_pass(bytes);
542}
543
544#[cfg(feature = "alloc")]
545#[inline]
546fn next_secret_capacity(current: usize, required: usize) -> usize {
547    current.saturating_mul(2).max(required).max(8)
548}
549
550#[cfg(feature = "alloc")]
551const MAX_UTF8_CHAR_BYTES: usize = 4;
552
553impl<T: SecureSanitize> SecureSanitize for [T] {
554    #[inline(never)]
555    fn secure_sanitize(&mut self) {
556        for item in self.iter_mut() {
557            item.secure_sanitize();
558        }
559        compiler_fence(Ordering::SeqCst);
560    }
561}
562
563impl<T: SecureSanitize, const N: usize> SecureSanitize for [T; N] {
564    #[inline(never)]
565    fn secure_sanitize(&mut self) {
566        self.as_mut_slice().secure_sanitize();
567    }
568}
569
570impl<T: StableSharedSecretStorage> StableSharedSecretStorage for [T] {}
571impl<T: StableMutableSecretStorage> StableMutableSecretStorage for [T] {}
572
573impl<T: StableSharedSecretStorage, const N: usize> StableSharedSecretStorage for [T; N] {}
574impl<T: StableMutableSecretStorage, const N: usize> StableMutableSecretStorage for [T; N] {}
575
576impl SecureSanitize for () {
577    #[inline]
578    fn secure_sanitize(&mut self) {}
579}
580
581impl StableSharedSecretStorage for () {}
582impl StableMutableSecretStorage for () {}
583
584macro_rules! impl_tuple_storage_contracts {
585    ($(($($type:ident:$index:tt),+)),+ $(,)?) => {
586        $(
587            impl<$($type: SecureSanitize),+> SecureSanitize for ($($type,)+) {
588                #[inline]
589                fn secure_sanitize(&mut self) {
590                    $(
591                        self.$index.secure_sanitize();
592                    )+
593                    compiler_fence(Ordering::SeqCst);
594                }
595            }
596
597            impl<$($type: StableSharedSecretStorage),+> StableSharedSecretStorage
598                for ($($type,)+)
599            {}
600
601            impl<$($type: StableMutableSecretStorage),+> StableMutableSecretStorage
602                for ($($type,)+)
603            {}
604        )+
605    };
606}
607
608impl_tuple_storage_contracts!(
609    (A:0),
610    (A:0, B:1),
611    (A:0, B:1, C:2),
612    (A:0, B:1, C:2, D:3),
613    (A:0, B:1, C:2, D:3, E:4),
614    (A:0, B:1, C:2, D:3, E:4, F:5),
615    (A:0, B:1, C:2, D:3, E:4, F:5, G:6),
616    (A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7),
617    (A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8),
618    (A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9),
619    (A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10),
620    (A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11),
621);
622
623impl<T: SecureSanitize> SecureSanitize for Option<T> {
624    #[inline]
625    fn secure_sanitize(&mut self) {
626        if let Some(value) = self.as_mut() {
627            value.secure_sanitize();
628        }
629        *self = None;
630        compiler_fence(Ordering::SeqCst);
631    }
632}
633
634impl<T: SecureSanitize, E: SecureSanitize> SecureSanitize for Result<T, E> {
635    #[inline]
636    fn secure_sanitize(&mut self) {
637        match self {
638            Ok(value) => value.secure_sanitize(),
639            Err(error) => error.secure_sanitize(),
640        }
641        compiler_fence(Ordering::SeqCst);
642    }
643}
644
645impl<T> SecureSanitize for PhantomData<T> {
646    #[inline]
647    fn secure_sanitize(&mut self) {}
648}
649
650impl<T> StableSharedSecretStorage for PhantomData<T> {}
651impl<T> StableMutableSecretStorage for PhantomData<T> {}
652
653#[cfg(feature = "alloc")]
654/// Field-wise sanitization for the currently boxed value.
655///
656/// This does not clear unknown representation padding and cannot recover a
657/// different allocation previously released by caller-controlled replacement.
658/// Byte workloads needing complete fixed-allocation wiping should use
659/// [`SecretBoxBytes`].
660impl<T: SecureSanitize + ?Sized> SecureSanitize for Box<T> {
661    #[inline]
662    fn secure_sanitize(&mut self) {
663        self.as_mut().secure_sanitize();
664    }
665}
666
667/// In-place sanitization for UTF-8 string slices.
668///
669/// Every byte is replaced with `0`, which remains valid UTF-8. This supports
670/// fixed boxed string storage without allocating or changing its length.
671impl SecureSanitize for str {
672    #[inline]
673    fn secure_sanitize(&mut self) {
674        crate::wipe_backend::erase_str(self);
675    }
676}
677
678impl StableSharedSecretStorage for str {}
679
680impl StableMutableSecretStorage for str {}
681
682#[cfg(feature = "alloc")]
683/// Sanitization for the vector's currently reachable allocation.
684///
685/// This sanitizes every live element, drops those elements, and then wipes the
686/// current allocation capacity as bytes. It cannot recover allocations already
687/// released by prior caller-controlled growth or replacement. Byte workloads
688/// should prefer [`SecretVec`] for managed wipe-before-grow behavior or
689/// [`SecretBoxBytes`] when the runtime length is fixed.
690impl<T: SecureSanitize> SecureSanitize for Vec<T> {
691    #[inline]
692    fn secure_sanitize(&mut self) {
693        for item in self.iter_mut() {
694            item.secure_sanitize();
695        }
696        self.clear();
697        wipe_backend::erase(
698            self.as_mut_ptr().cast::<u8>(),
699            self.capacity().saturating_mul(core::mem::size_of::<T>()),
700        );
701        compiler_fence(Ordering::SeqCst);
702    }
703}
704
705#[cfg(feature = "alloc")]
706impl SecureSanitize for String {
707    #[inline(never)]
708    fn secure_sanitize(&mut self) {
709        crate::wipe::string(self);
710    }
711}
712
713#[inline]
714pub(crate) fn constant_time_eq_slices(left: &[u8], right: &[u8]) -> bool {
715    if left.len() != right.len() {
716        return false;
717    }
718
719    constant_time_eq_equal_len(left, right)
720}
721
722#[inline]
723pub(crate) fn constant_time_eq_equal_len(left: &[u8], right: &[u8]) -> bool {
724    debug_assert_eq!(left.len(), right.len());
725
726    #[cfg(all(
727        feature = "asm-compare",
728        any(target_arch = "x86_64", target_arch = "aarch64"),
729        not(miri)
730    ))]
731    {
732        crate::compare_asm::constant_time_eq_equal_len(left, right)
733    }
734
735    #[cfg(not(all(
736        feature = "asm-compare",
737        any(target_arch = "x86_64", target_arch = "aarch64"),
738        not(miri)
739    )))]
740    {
741        portable_constant_time_eq_equal_len(left, right)
742    }
743}
744
745#[inline]
746#[cfg_attr(
747    all(
748        feature = "asm-compare",
749        any(target_arch = "x86_64", target_arch = "aarch64"),
750        not(miri)
751    ),
752    allow(dead_code)
753)]
754pub(crate) fn portable_constant_time_eq_equal_len(left: &[u8], right: &[u8]) -> bool {
755    debug_assert_eq!(left.len(), right.len());
756
757    let mut diff = 0usize;
758    let mut index = 0;
759    while index < left.len() {
760        diff = black_box(diff | usize::from(left[index] ^ right[index]));
761        index += 1;
762    }
763    black_box(diff) == 0
764}
765
766#[cfg(kani)]
767mod kani_verification {
768    use super::*;
769    use core::cmp::Ordering;
770
771    fn assert_ct_ordering_matches(ordering: ct::CtOrdering, expected: Ordering) {
772        match expected {
773            Ordering::Less => {
774                assert_eq!(
775                    ordering
776                        .is_less()
777                        .declassify_u8("test or verification observes normalized choice"),
778                    1
779                );
780                assert_eq!(
781                    ordering
782                        .is_equal()
783                        .declassify_u8("test or verification observes normalized choice"),
784                    0
785                );
786                assert_eq!(
787                    ordering
788                        .is_greater()
789                        .declassify_u8("test or verification observes normalized choice"),
790                    0
791                );
792            }
793            Ordering::Equal => {
794                assert_eq!(
795                    ordering
796                        .is_less()
797                        .declassify_u8("test or verification observes normalized choice"),
798                    0
799                );
800                assert_eq!(
801                    ordering
802                        .is_equal()
803                        .declassify_u8("test or verification observes normalized choice"),
804                    1
805                );
806                assert_eq!(
807                    ordering
808                        .is_greater()
809                        .declassify_u8("test or verification observes normalized choice"),
810                    0
811                );
812            }
813            Ordering::Greater => {
814                assert_eq!(
815                    ordering
816                        .is_less()
817                        .declassify_u8("test or verification observes normalized choice"),
818                    0
819                );
820                assert_eq!(
821                    ordering
822                        .is_equal()
823                        .declassify_u8("test or verification observes normalized choice"),
824                    0
825                );
826                assert_eq!(
827                    ordering
828                        .is_greater()
829                        .declassify_u8("test or verification observes normalized choice"),
830                    1
831                );
832            }
833        }
834    }
835
836    fn lexicographic_cmp_4(left: &[u8; 4], right: &[u8; 4]) -> Ordering {
837        let mut index = 0;
838        while index < 4 {
839            if left[index] < right[index] {
840                return Ordering::Less;
841            }
842            if left[index] > right[index] {
843                return Ordering::Greater;
844            }
845            index += 1;
846        }
847        Ordering::Equal
848    }
849
850    #[kani::proof]
851    fn prove_wipe_bytes_clears_fixed_buffer() {
852        let mut bytes: [u8; 4] = kani::any();
853
854        wipe::bytes(&mut bytes);
855
856        assert_eq!(bytes, [0; 4]);
857    }
858
859    #[kani::proof]
860    fn prove_secret_bytes_clear_erases_visible_contents() {
861        let source: [u8; 4] = kani::any();
862        let mut secret = SecretBytes::<4>::from_array(source);
863        let mut output = [0xA5; 4];
864
865        secret.secure_clear();
866        assert!(secret
867            .export_to_slice("test exports bytes for verification output", &mut output)
868            .is_ok());
869
870        assert_eq!(output, [0; 4]);
871    }
872
873    #[kani::proof]
874    fn prove_secret_bytes_constant_time_eq_matches_byte_equality() {
875        let left: [u8; 4] = kani::any();
876        let right: [u8; 4] = kani::any();
877        let secret = SecretBytes::<4>::from_array(left);
878
879        let mut expected = true;
880        let mut index = 0;
881        while index < 4 {
882            expected &= left[index] == right[index];
883            index += 1;
884        }
885
886        assert_eq!(secret.constant_time_eq(&right), expected);
887    }
888
889    #[kani::proof]
890    fn prove_ct_choice_is_normalized() {
891        let value: u8 = kani::any();
892        let choice = ct::Choice::from_u8(value);
893        let unwrapped = choice.declassify_u8("test or verification observes normalized choice");
894
895        assert!(unwrapped == 0 || unwrapped == 1);
896    }
897
898    #[kani::proof]
899    fn prove_ct_choice_boolean_algebra_matches_public_bits() {
900        let left_byte: u8 = kani::any();
901        let right_byte: u8 = kani::any();
902        let left = ct::Choice::from_u8(left_byte);
903        let right = ct::Choice::from_u8(right_byte);
904        let left_bit = left.declassify_u8("test or verification observes normalized choice");
905        let right_bit = right.declassify_u8("test or verification observes normalized choice");
906
907        assert_eq!(
908            (left & right).declassify_u8("test or verification observes normalized choice"),
909            left_bit & right_bit
910        );
911        assert_eq!(
912            (left | right).declassify_u8("test or verification observes normalized choice"),
913            left_bit | right_bit
914        );
915        assert_eq!(
916            (left ^ right).declassify_u8("test or verification observes normalized choice"),
917            left_bit ^ right_bit
918        );
919        assert_eq!(
920            (!left).declassify_u8("test or verification observes normalized choice"),
921            left_bit ^ 1
922        );
923    }
924
925    #[kani::proof]
926    fn prove_ct_fixed_equality_matches_byte_equality() {
927        let left: [u8; 4] = kani::any();
928        let right: [u8; 4] = kani::any();
929
930        let mut expected = true;
931        let mut index = 0;
932        while index < 4 {
933            expected &= left[index] == right[index];
934            index += 1;
935        }
936
937        assert_eq!(
938            ct::eq_fixed(&left, &right)
939                .declassify_u8("test or verification observes normalized choice")
940                == 1,
941            expected
942        );
943    }
944
945    #[kani::proof]
946    fn prove_ct_public_length_equality_rejects_mismatch() {
947        let left: [u8; 4] = kani::any();
948        let right: [u8; 3] = kani::any();
949
950        assert_eq!(
951            ct::eq_public_len(&left, &right)
952                .declassify_u8("test or verification observes normalized choice"),
953            0
954        );
955    }
956
957    #[kani::proof]
958    fn prove_ct_fixed_ordering_matches_lexicographic_ordering() {
959        let left: [u8; 4] = kani::any();
960        let right: [u8; 4] = kani::any();
961
962        assert_ct_ordering_matches(
963            ct::cmp_fixed(&left, &right),
964            lexicographic_cmp_4(&left, &right),
965        );
966    }
967
968    #[kani::proof]
969    fn prove_ct_unsigned_ordering_matches_rust_ordering() {
970        let left: u16 = kani::any();
971        let right: u16 = kani::any();
972
973        assert_ct_ordering_matches(
974            <u16 as ct::ConstantTimeOrd>::ct_cmp(&left, &right),
975            left.cmp(&right),
976        );
977    }
978
979    #[kani::proof]
980    fn prove_ct_signed_ordering_matches_rust_ordering() {
981        let left: i16 = kani::any();
982        let right: i16 = kani::any();
983
984        assert_ct_ordering_matches(
985            <i16 as ct::ConstantTimeOrd>::ct_cmp(&left, &right),
986            left.cmp(&right),
987        );
988    }
989
990    #[kani::proof]
991    fn prove_ct_conditional_copy_matches_choice() {
992        let initial: [u8; 4] = kani::any();
993        let source: [u8; 4] = kani::any();
994        let choice_byte: u8 = kani::any();
995        let choice = ct::Choice::from_u8(choice_byte);
996        let mut destination = initial;
997
998        assert!(ct::conditional_copy(&mut destination, &source, choice).is_ok());
999
1000        if choice.declassify_u8("test or verification observes normalized choice") == 1 {
1001            assert_eq!(destination, source);
1002        } else {
1003            assert_eq!(destination, initial);
1004        }
1005    }
1006
1007    #[kani::proof]
1008    fn prove_ct_conditional_swap_matches_choice() {
1009        let initial_left: [u8; 4] = kani::any();
1010        let initial_right: [u8; 4] = kani::any();
1011        let choice_byte: u8 = kani::any();
1012        let choice = ct::Choice::from_u8(choice_byte);
1013        let mut left = initial_left;
1014        let mut right = initial_right;
1015
1016        assert!(ct::conditional_swap(&mut left, &mut right, choice).is_ok());
1017
1018        if choice.declassify_u8("test or verification observes normalized choice") == 1 {
1019            assert_eq!(left, initial_right);
1020            assert_eq!(right, initial_left);
1021        } else {
1022            assert_eq!(left, initial_left);
1023            assert_eq!(right, initial_right);
1024        }
1025    }
1026
1027    #[kani::proof]
1028    fn prove_ct_oblivious_lookup_matches_public_index() {
1029        let table: [u8; 4] = kani::any();
1030        let fallback: u8 = kani::any();
1031        let index: usize = kani::any();
1032
1033        let selected = ct::oblivious_lookup(&table, ct::SecretIndex::new(index), &fallback);
1034
1035        if index < 4 {
1036            assert_eq!(selected, table[index]);
1037        } else {
1038            assert_eq!(selected, fallback);
1039        }
1040    }
1041
1042    #[kani::proof]
1043    fn prove_ct_select_slice_matches_choice() {
1044        let left: [u8; 4] = kani::any();
1045        let right: [u8; 4] = kani::any();
1046        let choice_byte: u8 = kani::any();
1047        let choice = ct::Choice::from_u8(choice_byte);
1048        let mut destination = [0u8; 4];
1049
1050        assert!(ct::select_slice(&mut destination, &left, &right, choice).is_ok());
1051
1052        if choice.declassify_u8("test or verification observes normalized choice") == 1 {
1053            assert_eq!(destination, right);
1054        } else {
1055            assert_eq!(destination, left);
1056        }
1057    }
1058
1059    #[kani::proof]
1060    fn prove_ct_option_unwrap_or_matches_presence() {
1061        let value: u8 = kani::any();
1062        let fallback: u8 = kani::any();
1063        let presence_byte: u8 = kani::any();
1064        let presence = ct::Choice::from_u8(presence_byte);
1065        let option = ct::PublicCtOption::new(value, presence);
1066
1067        let selected = option.unwrap_or(&fallback);
1068
1069        if presence.declassify_u8("test or verification observes normalized choice") == 1 {
1070            assert_eq!(selected, value);
1071        } else {
1072            assert_eq!(selected, fallback);
1073        }
1074    }
1075
1076    #[kani::proof]
1077    fn prove_ct_option_and_or_match_presence_bits() {
1078        let left_value: u8 = kani::any();
1079        let right_value: u8 = kani::any();
1080        let fallback: u8 = kani::any();
1081        let left_presence_byte: u8 = kani::any();
1082        let right_presence_byte: u8 = kani::any();
1083        let left_presence = ct::Choice::from_u8(left_presence_byte);
1084        let right_presence = ct::Choice::from_u8(right_presence_byte);
1085        let left = ct::PublicCtOption::new(left_value, left_presence);
1086        let right = ct::PublicCtOption::new(right_value, right_presence);
1087
1088        let and_selected = left.and(right).unwrap_or(&fallback);
1089        let or_selected = left.or(right).unwrap_or(&fallback);
1090
1091        if left_presence.declassify_u8("test or verification observes normalized choice") == 1
1092            && right_presence.declassify_u8("test or verification observes normalized choice") == 1
1093        {
1094            assert_eq!(and_selected, right_value);
1095        } else {
1096            assert_eq!(and_selected, fallback);
1097        }
1098
1099        if left_presence.declassify_u8("test or verification observes normalized choice") == 1 {
1100            assert_eq!(or_selected, left_value);
1101        } else if right_presence.declassify_u8("test or verification observes normalized choice")
1102            == 1
1103        {
1104            assert_eq!(or_selected, right_value);
1105        } else {
1106            assert_eq!(or_selected, fallback);
1107        }
1108    }
1109
1110    #[kani::proof]
1111    fn prove_ct_result_unwrap_or_and_maps_match_success_bit() {
1112        let value: u8 = kani::any();
1113        let error: u8 = kani::any();
1114        let fallback: u8 = kani::any();
1115        let success_byte: u8 = kani::any();
1116        let success = ct::Choice::from_u8(success_byte);
1117        let result = ct::PublicCtResult::new(value, error, success);
1118
1119        let selected = result.unwrap_or(&fallback);
1120        let mapped = result.map(|inner| inner.wrapping_add(1));
1121        let mapped_error = result.map_err(|inner| inner.wrapping_add(1));
1122
1123        if success.declassify_u8("test or verification observes normalized choice") == 1 {
1124            assert_eq!(selected, value);
1125            assert_eq!(
1126                mapped.declassify("Kani exposes mapped success bit"),
1127                Ok(value.wrapping_add(1))
1128            );
1129            assert_eq!(
1130                mapped_error.declassify("Kani exposes mapped success bit"),
1131                Ok(value)
1132            );
1133        } else {
1134            assert_eq!(selected, fallback);
1135            assert_eq!(
1136                mapped.declassify("Kani exposes mapped error bit"),
1137                Err(error)
1138            );
1139            assert_eq!(
1140                mapped_error.declassify("Kani exposes mapped error bit"),
1141                Err(error.wrapping_add(1))
1142            );
1143        }
1144    }
1145
1146    #[kani::proof]
1147    fn prove_ct_option_and_result_conditional_select_match_choice() {
1148        let left_value: u8 = kani::any();
1149        let right_value: u8 = kani::any();
1150        let choice_byte: u8 = kani::any();
1151        let choice = ct::Choice::from_u8(choice_byte);
1152        let left_option = ct::PublicCtOption::some(left_value);
1153        let right_option = ct::PublicCtOption::some(right_value);
1154        let left_result = ct::PublicCtResult::new(left_value, 11u8, ct::Choice::TRUE);
1155        let right_result = ct::PublicCtResult::new(right_value, 22u8, ct::Choice::TRUE);
1156
1157        let selected_option =
1158            <ct::PublicCtOption<u8> as ct::ConditionallySelectable>::conditional_select(
1159                &left_option,
1160                &right_option,
1161                choice,
1162            );
1163        let selected_result =
1164            <ct::PublicCtResult<u8, u8> as ct::ConditionallySelectable>::conditional_select(
1165                &left_result,
1166                &right_result,
1167                choice,
1168            );
1169
1170        if choice.declassify_u8("test or verification observes normalized choice") == 1 {
1171            assert_eq!(selected_option.unwrap_or(&0), right_value);
1172            assert_eq!(selected_result.unwrap_or(&0), right_value);
1173        } else {
1174            assert_eq!(selected_option.unwrap_or(&0), left_value);
1175            assert_eq!(selected_result.unwrap_or(&0), left_value);
1176        }
1177    }
1178
1179    #[kani::proof]
1180    fn prove_constant_time_eq_rejects_length_mismatch() {
1181        let left: [u8; 4] = kani::any();
1182        let right: [u8; 3] = kani::any();
1183
1184        assert!(!constant_time_eq_slices(&left, &right));
1185    }
1186
1187    #[kani::proof]
1188    fn prove_secret_bytes_replacement_commits_complete_new_value() {
1189        let initial: [u8; 4] = kani::any();
1190        let replacement: [u8; 4] = kani::any();
1191        let mut secret = SecretBytes::<4>::from_array(initial);
1192        let mut observed = [0_u8; 4];
1193
1194        secret.copy_from_slice(&replacement).unwrap();
1195        secret
1196            .export_to_slice("test exports bytes for verification output", &mut observed)
1197            .unwrap();
1198
1199        assert_eq!(observed, replacement);
1200    }
1201
1202    #[kani::proof]
1203    #[cfg(feature = "alloc")]
1204    fn prove_next_secret_capacity_never_under_allocates() {
1205        let current: usize = kani::any();
1206        let required: usize = kani::any();
1207
1208        let capacity = next_secret_capacity(current, required);
1209
1210        assert!(capacity >= required);
1211        assert!(capacity >= 8);
1212    }
1213}
1214
1215struct TemporaryBytes<'a, const N: usize> {
1216    bytes: &'a mut [u8; N],
1217}
1218
1219impl<const N: usize> Drop for TemporaryBytes<'_, N> {
1220    #[inline]
1221    fn drop(&mut self) {
1222        wipe::bytes(self.bytes);
1223    }
1224}
1225
1226pub(crate) fn expose_array_copy<const N: usize, R>(
1227    source: &[u8; N],
1228    inspect: impl FnOnce(&[u8; N]) -> R,
1229) -> R {
1230    let mut temporary = [0; N];
1231    temporary.copy_from_slice(source);
1232    compiler_fence(Ordering::SeqCst);
1233    let guard = TemporaryBytes {
1234        bytes: &mut temporary,
1235    };
1236    let result = inspect(guard.bytes);
1237    // Clear eagerly before returning. The guard repeats the clear on normal
1238    // return and clears during unwinding as defense in depth.
1239    wipe::bytes(guard.bytes);
1240    result
1241}
1242
1243#[cfg(all(test, feature = "std"))]
1244mod temporary_bytes_tests {
1245    use super::TemporaryBytes;
1246    use std::panic::{catch_unwind, AssertUnwindSafe};
1247
1248    #[test]
1249    fn temporary_bytes_clear_during_unwind() {
1250        let mut bytes = [7_u8; 32];
1251
1252        let result = catch_unwind(AssertUnwindSafe(|| {
1253            let _guard = TemporaryBytes { bytes: &mut bytes };
1254            panic!("exercise temporary cleanup");
1255        }));
1256
1257        assert!(result.is_err());
1258        assert_eq!(bytes, [0; 32]);
1259    }
1260}
1261
1262/// Fixed-size secret byte storage with automatic sanitization on drop.
1263///
1264/// Bytes are stored in a plain `[u8; N]` and all clearing routes through the
1265/// crate's internal volatile wipe backend. This gives the same clearing behavior
1266/// on targets with and without native byte atomics.
1267///
1268/// # Platform Notes
1269///
1270/// This type is `Sync` because it contains only plain bytes. Mutating and
1271/// clearing operations require `&mut self` to prevent partially-cleared
1272/// multi-byte observations through shared references.
1273///
1274/// `SecretBytes<N>` stores `N` bytes inline. [`SecretBytes::expose_secret`]
1275/// borrows that storage directly and does not intentionally construct a
1276/// full-size temporary array. [`SecretBytes::export_secret_copy`] is the
1277/// explicit copy-based alternative.
1278///
1279/// The type deliberately does not implement `Clone`, `Copy`, `Deref`,
1280/// `AsRef<[u8]>`, `PartialEq`, or secret-printing `Debug`.
1281pub struct SecretBytes<const N: usize> {
1282    bytes: [u8; N],
1283}
1284
1285impl<const N: usize> SecretBytes<N> {
1286    /// Create an all-zero secret buffer.
1287    #[must_use]
1288    #[inline]
1289    pub const fn zeroed() -> Self {
1290        Self { bytes: [0; N] }
1291    }
1292
1293    /// Create a secret from an array, then volatile-clear the input array.
1294    ///
1295    /// For the strongest move hygiene, prefer [`SecretBytes::from_fn`] or
1296    /// [`SecretBytes::copy_from_slice`] so callers can avoid building a normal
1297    /// byte array first.
1298    #[must_use]
1299    #[inline]
1300    pub fn from_array(mut bytes: [u8; N]) -> Self {
1301        let mut secret = Self::zeroed();
1302        for (index, byte) in bytes.iter().copied().enumerate() {
1303            secret.store(index, byte);
1304        }
1305        secret.after_secret_write();
1306        wipe::bytes(&mut bytes);
1307        secret
1308    }
1309
1310    /// Create a secret by producing each byte directly.
1311    ///
1312    /// This avoids requiring a full temporary `[u8; N]` at the call boundary.
1313    #[must_use]
1314    #[inline]
1315    pub fn from_fn(mut make_byte: impl FnMut(usize) -> u8) -> Self {
1316        let mut secret = Self::zeroed();
1317        let mut index = 0;
1318        while index < N {
1319            secret.store(index, make_byte(index));
1320            index += 1;
1321        }
1322        secret.after_secret_write();
1323        secret
1324    }
1325
1326    /// Create a secret by producing each byte directly with a fallible
1327    /// generator.
1328    ///
1329    /// If `make_byte` returns an error, any bytes generated before the error
1330    /// are cleared before the error is returned.
1331    #[inline]
1332    pub fn try_from_fn<E>(mut make_byte: impl FnMut(usize) -> Result<u8, E>) -> Result<Self, E> {
1333        let mut secret = Self::zeroed();
1334        let mut index = 0;
1335        while index < N {
1336            let byte = make_byte(index)?;
1337            secret.store(index, byte);
1338            index += 1;
1339        }
1340        secret.after_secret_write();
1341        Ok(secret)
1342    }
1343
1344    /// Number of bytes stored in this secret.
1345    #[must_use]
1346    #[inline]
1347    pub const fn len(&self) -> usize {
1348        N
1349    }
1350
1351    /// Returns true when the secret has zero length.
1352    #[must_use]
1353    #[inline]
1354    pub const fn is_empty(&self) -> bool {
1355        N == 0
1356    }
1357
1358    /// Replace all bytes from a same-length slice.
1359    #[inline]
1360    pub fn copy_from_slice(&mut self, source: &[u8]) -> Result<(), LengthError> {
1361        if source.len() != N {
1362            return Err(LengthError {
1363                expected: N,
1364                actual: source.len(),
1365            });
1366        }
1367
1368        for (index, byte) in source.iter().copied().enumerate() {
1369            self.store(index, byte);
1370        }
1371        self.after_secret_write();
1372        Ok(())
1373    }
1374
1375    /// Replace all bytes from an owned array, then volatile-clear that input
1376    /// array.
1377    ///
1378    /// Prefer this over [`SecretBytes::copy_from_slice`] when the caller has an
1379    /// owned `[u8; N]` that should be wiped after rotation.
1380    #[inline]
1381    pub fn replace_from_array(&mut self, mut bytes: [u8; N]) {
1382        for (index, byte) in bytes.iter().copied().enumerate() {
1383            self.store(index, byte);
1384        }
1385        self.after_secret_write();
1386        wipe::bytes(&mut bytes);
1387    }
1388
1389    /// Replace all bytes with generated bytes.
1390    ///
1391    /// The new bytes are generated into a fresh clear-on-drop value before the
1392    /// old value is cleared and replaced. If `make_byte` panics, the old value
1393    /// remains unchanged and partial generated bytes are cleared during
1394    /// unwinding.
1395    #[inline]
1396    pub fn replace_from_fn(&mut self, make_byte: impl FnMut(usize) -> u8) {
1397        let mut replacement = Self::from_fn(make_byte);
1398        self.secure_clear();
1399        core::mem::swap(self, &mut replacement);
1400    }
1401
1402    /// Replace all bytes with generated bytes from a fallible generator.
1403    ///
1404    /// The new bytes are generated into a fresh clear-on-drop value before the
1405    /// old value is cleared and replaced. If `make_byte` returns an error, the
1406    /// old value remains unchanged and partial generated bytes are cleared
1407    /// before the error is returned.
1408    #[inline]
1409    pub fn try_replace_from_fn<E>(
1410        &mut self,
1411        make_byte: impl FnMut(usize) -> Result<u8, E>,
1412    ) -> Result<(), E> {
1413        let mut replacement = Self::try_from_fn(make_byte)?;
1414        self.secure_clear();
1415        core::mem::swap(self, &mut replacement);
1416        Ok(())
1417    }
1418
1419    /// Mutate the secret bytes in place.
1420    ///
1421    /// The closure receives direct mutable access to the fixed-size storage
1422    /// owned by this container. It can still intentionally copy bytes
1423    /// elsewhere, so keep this API at cryptographic transformation boundaries
1424    /// such as key derivation, masking, or protocol-specific normalization.
1425    #[inline]
1426    pub fn transform(&mut self, edit: impl FnOnce(&mut [u8; N])) {
1427        edit(&mut self.bytes);
1428        self.after_secret_write();
1429    }
1430
1431    /// Fallible variant of [`SecretBytes::transform`].
1432    ///
1433    /// If the closure returns an error after partially mutating the value,
1434    /// those mutations remain in place. Use [`SecretBytes::try_replace_from_fn`]
1435    /// when the old value must remain unchanged on error.
1436    #[inline]
1437    pub fn try_transform<E>(
1438        &mut self,
1439        edit: impl FnOnce(&mut [u8; N]) -> Result<(), E>,
1440    ) -> Result<(), E> {
1441        edit(&mut self.bytes)?;
1442        self.after_secret_write();
1443        Ok(())
1444    }
1445
1446    /// Derive a new fixed-size secret without exposing either buffer through a
1447    /// temporary stack copy.
1448    ///
1449    /// The closure receives read-only access to this secret's storage and
1450    /// mutable access to the new output secret's storage. This is intended for
1451    /// KDFs, key hierarchy expansion, and similar operations where the output
1452    /// should be written directly into a clear-on-drop container.
1453    #[must_use]
1454    #[inline]
1455    pub fn derive<const M: usize>(
1456        &self,
1457        derive: impl FnOnce(&[u8; N], &mut [u8; M]),
1458    ) -> SecretBytes<M> {
1459        let mut output = SecretBytes::<M>::zeroed();
1460        derive(&self.bytes, &mut output.bytes);
1461        output.after_secret_write();
1462        output
1463    }
1464
1465    /// Fallible variant of [`SecretBytes::derive`].
1466    ///
1467    /// If derivation fails, the partially written output is dropped and
1468    /// volatile-cleared before the error is returned.
1469    #[inline]
1470    pub fn try_derive<const M: usize, E>(
1471        &self,
1472        derive: impl FnOnce(&[u8; N], &mut [u8; M]) -> Result<(), E>,
1473    ) -> Result<SecretBytes<M>, E> {
1474        let mut output = SecretBytes::<M>::zeroed();
1475        derive(&self.bytes, &mut output.bytes)?;
1476        output.after_secret_write();
1477        Ok(output)
1478    }
1479
1480    /// Export a temporary copy into caller-owned storage.
1481    ///
1482    /// The destination is outside this container's clearing guarantee. The
1483    /// caller must clear it. `reason` is an audit label identifying why this
1484    /// copy is allowed to cross the secret-container boundary.
1485    #[inline]
1486    pub fn export_to_slice(
1487        &self,
1488        reason: &'static str,
1489        destination: &mut [u8],
1490    ) -> Result<(), LengthError> {
1491        black_box(reason);
1492        if destination.len() != N {
1493            return Err(LengthError {
1494                expected: N,
1495                actual: destination.len(),
1496            });
1497        }
1498
1499        for (index, byte) in destination.iter_mut().enumerate() {
1500            *byte = self.load(index);
1501        }
1502        compiler_fence(Ordering::SeqCst);
1503        black_box(destination);
1504        Ok(())
1505    }
1506
1507    /// Export one byte from the secret.
1508    ///
1509    /// The returned scalar is an unmanaged copy that may remain in registers or
1510    /// compiler temporaries. `reason` is an audit label identifying the public
1511    /// boundary that permits this extraction.
1512    #[must_use]
1513    #[inline]
1514    pub fn export_byte(&self, reason: &'static str, index: usize) -> Option<u8> {
1515        black_box(reason);
1516        if index < N {
1517            Some(self.load(index))
1518        } else {
1519            None
1520        }
1521    }
1522
1523    /// Replace one byte.
1524    #[inline]
1525    pub fn write_byte(&mut self, index: usize, value: u8) -> Result<(), LengthError> {
1526        if index >= N {
1527            return Err(LengthError {
1528                expected: N,
1529                actual: index.saturating_add(1),
1530            });
1531        }
1532
1533        self.store(index, value);
1534        self.after_secret_write();
1535        Ok(())
1536    }
1537
1538    /// Call a closure with direct shared access to the owned fixed-size bytes.
1539    ///
1540    /// This method does not intentionally construct an additional `[u8; N]`
1541    /// temporary. The closure can still cause compiler spills or deliberately
1542    /// copy bytes elsewhere, so use it only at reviewed cryptographic or
1543    /// protocol boundaries.
1544    ///
1545    /// The returned value cannot borrow the secret:
1546    ///
1547    /// ```compile_fail
1548    /// use sanitization::SecretBytes;
1549    ///
1550    /// let secret = SecretBytes::<4>::from_array([1, 2, 3, 4]);
1551    /// let escaped = secret.expose_secret(|bytes| bytes);
1552    /// let _ = escaped;
1553    /// ```
1554    #[inline]
1555    pub fn expose_secret<R>(&self, inspect: impl FnOnce(&[u8; N]) -> R) -> R {
1556        inspect(&self.bytes)
1557    }
1558
1559    /// Call a closure with a temporary array copy, then volatile-clear it.
1560    ///
1561    /// This explicitly creates an additional `N`-byte stack array. The copy is
1562    /// cleared eagerly on normal return and by an RAII guard during unwinding.
1563    /// It cannot be cleared if the process aborts, including under
1564    /// `panic = "abort"`.
1565    ///
1566    /// Prefer [`SecretBytes::expose_secret`] unless the callee must receive
1567    /// storage that is independent from the secret container.
1568    #[inline]
1569    pub fn export_secret_copy<R>(
1570        &self,
1571        reason: &'static str,
1572        inspect: impl FnOnce(&[u8; N]) -> R,
1573    ) -> R {
1574        black_box(reason);
1575        expose_array_copy(&self.bytes, inspect)
1576    }
1577
1578    /// Compare against a slice without early exit for equal-length inputs.
1579    ///
1580    /// Length mismatch returns immediately because the provided slice length is
1581    /// treated as public metadata. Prefer fixed-size inputs where possible.
1582    ///
1583    /// The portable fallback is intended to avoid data-dependent early exit, but
1584    /// it is not a formal hardware-level constant-time guarantee. On x86_64,
1585    /// enable `asm-compare` for a stronger compiler boundary. Use a dedicated
1586    /// constant-time comparison crate if your protocol requires externally
1587    /// audited timing guarantees.
1588    #[must_use]
1589    #[inline]
1590    pub fn constant_time_eq(&self, other: &[u8]) -> bool {
1591        constant_time_eq_slices(self.bytes.as_slice(), other)
1592    }
1593
1594    /// Compare against another secret without early exit.
1595    ///
1596    /// See [`SecretBytes::constant_time_eq`] for the portable fallback timing
1597    /// limits.
1598    #[must_use]
1599    #[inline]
1600    pub fn constant_time_eq_secret(&self, other: &Self) -> bool {
1601        constant_time_eq_equal_len(self.bytes.as_slice(), other.bytes.as_slice())
1602    }
1603
1604    /// Clear all bytes now. This is also called from `Drop`.
1605    #[inline(never)]
1606    pub fn secure_clear(&mut self) {
1607        wipe_backend::erase(self.bytes.as_mut_ptr(), N);
1608    }
1609
1610    /// Clear all bytes now with an explicit three-pass volatile pattern.
1611    ///
1612    /// Available with the `multi-pass-clear` feature. This is intended for
1613    /// policy or audit compatibility; for volatile RAM, the default
1614    /// [`SecretBytes::secure_clear`] remains the normal security boundary.
1615    #[cfg(feature = "multi-pass-clear")]
1616    #[inline(never)]
1617    pub fn secure_clear_multi_pass(&mut self) {
1618        wipe_backend::erase_multi_pass(self.bytes.as_mut_ptr(), N);
1619    }
1620
1621    /// Consume this value after first clearing the fixed-size storage.
1622    ///
1623    /// Drop still runs after this method returns, so the storage is cleared a
1624    /// second time on the normal path.
1625    #[inline]
1626    pub fn into_cleared(mut self) {
1627        self.secure_clear();
1628    }
1629
1630    /// Clear all bytes now with volatile writes, then flush the cache lines
1631    /// covering the fixed-size storage.
1632    #[cfg(feature = "cache-flush")]
1633    #[inline(never)]
1634    pub fn secure_clear_and_flush(
1635        &mut self,
1636    ) -> Result<crate::cache_flush::CacheFlushReport, crate::cache_flush::CacheFlushError> {
1637        crate::cache_flush::cache_flush_sanitize_bytes(self.bytes.as_mut_slice())
1638    }
1639
1640    #[inline]
1641    fn load(&self, index: usize) -> u8 {
1642        self.bytes[index]
1643    }
1644
1645    #[inline]
1646    pub(crate) fn store(&mut self, index: usize, value: u8) {
1647        self.bytes[index] = value;
1648    }
1649
1650    #[inline]
1651    pub(crate) fn after_secret_write(&self) {
1652        compiler_fence(Ordering::SeqCst);
1653    }
1654}
1655
1656impl<const N: usize> Default for SecretBytes<N> {
1657    #[inline]
1658    fn default() -> Self {
1659        Self::zeroed()
1660    }
1661}
1662
1663impl<const N: usize> Drop for SecretBytes<N> {
1664    #[inline]
1665    fn drop(&mut self) {
1666        self.secure_clear();
1667    }
1668}
1669
1670impl<const N: usize> SecureSanitize for SecretBytes<N> {
1671    #[inline]
1672    fn secure_sanitize(&mut self) {
1673        self.secure_clear();
1674    }
1675}
1676
1677impl<const N: usize> StableSharedSecretStorage for SecretBytes<N> {}
1678impl<const N: usize> StableMutableSecretStorage for SecretBytes<N> {}
1679
1680impl<const N: usize> fmt::Debug for SecretBytes<N> {
1681    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1682        formatter
1683            .debug_struct("SecretBytes")
1684            .field("len", &N)
1685            .field("contents", &"<redacted>")
1686            .finish()
1687    }
1688}
1689
1690impl<const N: usize> ct::ConstantTimeEq for SecretBytes<N> {
1691    #[inline]
1692    fn ct_eq(&self, other: &Self) -> ct::Choice {
1693        ct::eq_fixed(&self.bytes, &other.bytes)
1694    }
1695}
1696
1697impl<const N: usize> ct::ConstantTimeEq<[u8]> for SecretBytes<N> {
1698    #[inline]
1699    fn ct_eq(&self, other: &[u8]) -> ct::Choice {
1700        ct::eq_public_len(self.bytes.as_slice(), other)
1701    }
1702}
1703
1704impl<const N: usize> ct::ConditionallySelectable for SecretBytes<N> {
1705    #[inline]
1706    fn conditional_select(left: &Self, right: &Self, choice: ct::Choice) -> Self {
1707        let mut output = Self::zeroed();
1708        let mut index = 0usize;
1709        while index < N {
1710            output.bytes[index] = <u8 as ct::ConditionallySelectable>::conditional_select(
1711                &left.bytes[index],
1712                &right.bytes[index],
1713                choice,
1714            );
1715            index += 1;
1716        }
1717        output.after_secret_write();
1718        output
1719    }
1720}
1721
1722/// Error returned by split-secret construction.
1723#[cfg(feature = "split-secret")]
1724#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1725pub enum SplitSecretError {
1726    /// XOR split storage requires at least two shares.
1727    TooFewShares,
1728    /// The generated mask shares were trivially constant.
1729    ///
1730    /// This usually means the caller passed a stub, deterministic test
1731    /// generator, all-zero generator, or otherwise unsuitable random source.
1732    TrivialMask,
1733}
1734
1735#[cfg(feature = "split-secret")]
1736impl fmt::Display for SplitSecretError {
1737    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1738        match self {
1739            Self::TooFewShares => formatter.write_str("split secrets require at least two shares"),
1740            Self::TrivialMask => formatter.write_str(
1741                "split-secret mask shares are trivially constant; use cryptographically random mask bytes",
1742            ),
1743        }
1744    }
1745}
1746
1747#[cfg(all(feature = "split-secret", feature = "std"))]
1748impl std::error::Error for SplitSecretError {}
1749
1750/// Fixed-size N-of-N XOR split secret storage.
1751///
1752/// This type is available with the `split-secret` feature. It stores a secret
1753/// as `SHARES` independent-looking fixed-size shares where XORing every share
1754/// reconstructs the original bytes. It is not threshold secret sharing: all
1755/// shares are required, and the caller must provide cryptographically random
1756/// bytes for every mask share through the generator closure.
1757///
1758/// # Security
1759///
1760/// The generator is trusted. Passing a deterministic, low-entropy, or reused
1761/// generator can make the split provide no confidentiality. Construction
1762/// rejects trivially constant mask shares and trivially constant combined mask
1763/// accumulators in all build profiles, but that cheap heuristic is not a
1764/// substitute for a CSPRNG.
1765#[cfg(feature = "split-secret")]
1766pub struct SplitSecretBytes<const N: usize, const SHARES: usize> {
1767    shares: [SecretBytes<N>; SHARES],
1768}
1769
1770#[cfg(feature = "split-secret")]
1771impl<const N: usize, const SHARES: usize> SplitSecretBytes<N, SHARES> {
1772    /// Split an owned secret array into `SHARES` XOR shares, then clear the
1773    /// input array.
1774    ///
1775    /// `make_mask_byte(share_index, byte_index)` is called for shares
1776    /// `0..SHARES - 1`. It must return cryptographically random mask bytes for
1777    /// the split to provide meaningful protection.
1778    pub fn from_array_with_generator(
1779        mut secret: [u8; N],
1780        mut make_mask_byte: impl FnMut(usize, usize) -> u8,
1781    ) -> Result<Self, SplitSecretError> {
1782        let guard = TemporaryBytes { bytes: &mut secret };
1783
1784        if SHARES < 2 {
1785            return Err(SplitSecretError::TooFewShares);
1786        }
1787
1788        let split = Self::from_secret_bytes_with_generator(guard.bytes, &mut make_mask_byte)?;
1789        wipe::bytes(guard.bytes);
1790        Ok(split)
1791    }
1792
1793    /// Split an existing [`SecretBytes`] value into `SHARES` XOR shares.
1794    ///
1795    /// The source secret is not cleared by this method. Use
1796    /// [`SecretBytes::secure_clear`] afterwards if ownership policy requires
1797    /// moving the secret exclusively into the split representation.
1798    pub fn from_secret_with_generator(
1799        secret: &SecretBytes<N>,
1800        mut make_mask_byte: impl FnMut(usize, usize) -> u8,
1801    ) -> Result<Self, SplitSecretError> {
1802        if SHARES < 2 {
1803            return Err(SplitSecretError::TooFewShares);
1804        }
1805
1806        Self::from_secret_bytes_with_generator(&secret.bytes, &mut make_mask_byte)
1807    }
1808
1809    /// Split an owned [`SecretBytes`] value into `SHARES` XOR shares, then clear
1810    /// the source secret before returning.
1811    pub fn from_secret_consuming_with_generator(
1812        mut secret: SecretBytes<N>,
1813        mut make_mask_byte: impl FnMut(usize, usize) -> u8,
1814    ) -> Result<Self, SplitSecretError> {
1815        let split = Self::from_secret_bytes_with_generator(&secret.bytes, &mut make_mask_byte)?;
1816        secret.secure_clear();
1817        Ok(split)
1818    }
1819
1820    /// Reconstruct all shares into a new [`SecretBytes`] value.
1821    #[must_use]
1822    pub fn reconstruct(&self) -> SecretBytes<N> {
1823        let mut output = SecretBytes::<N>::zeroed();
1824        let mut byte_index = 0;
1825        while byte_index < N {
1826            let mut value = 0;
1827            let mut share_index = 0;
1828            while share_index < SHARES {
1829                value ^= self.shares[share_index].load(byte_index);
1830                share_index += 1;
1831            }
1832            output.store(byte_index, value);
1833            byte_index += 1;
1834        }
1835        output.after_secret_write();
1836        output
1837    }
1838
1839    /// Reconstruct into a temporary clear-on-drop value and expose that copy.
1840    ///
1841    /// Split storage has no contiguous plaintext representation to borrow
1842    /// directly. This method is therefore explicitly copy-based: it creates a
1843    /// temporary [`SecretBytes<N>`], reconstructs every byte into it, and
1844    /// clears it on normal return or unwinding. The temporary cannot be cleared
1845    /// if the process aborts.
1846    #[inline]
1847    pub fn expose_secret_copy<R>(&self, inspect: impl FnOnce(&[u8; N]) -> R) -> R {
1848        let reconstructed = self.reconstruct();
1849        reconstructed.expose_secret(inspect)
1850    }
1851
1852    /// Borrow all shares.
1853    #[must_use]
1854    #[inline]
1855    pub const fn shares(&self) -> &[SecretBytes<N>; SHARES] {
1856        &self.shares
1857    }
1858
1859    /// Borrow one share by index.
1860    #[must_use]
1861    #[inline]
1862    pub fn share(&self, index: usize) -> Option<&SecretBytes<N>> {
1863        self.shares.get(index)
1864    }
1865
1866    /// Consume the split storage and return the underlying shares.
1867    #[must_use]
1868    #[inline]
1869    pub fn into_shares(self) -> [SecretBytes<N>; SHARES] {
1870        self.shares
1871    }
1872
1873    fn from_secret_bytes_with_generator(
1874        secret: &[u8; N],
1875        make_mask_byte: &mut impl FnMut(usize, usize) -> u8,
1876    ) -> Result<Self, SplitSecretError> {
1877        if SHARES < 2 {
1878            return Err(SplitSecretError::TooFewShares);
1879        }
1880
1881        let mut shares = core::array::from_fn(|_| SecretBytes::<N>::zeroed());
1882
1883        let mut byte_index = 0;
1884        while byte_index < N {
1885            let mut accumulator = 0;
1886            let mut share_index = 0;
1887            while share_index + 1 < SHARES {
1888                let mask = make_mask_byte(share_index, byte_index);
1889                shares[share_index].store(byte_index, mask);
1890                accumulator ^= mask;
1891                share_index += 1;
1892            }
1893
1894            shares[SHARES - 1].store(byte_index, secret[byte_index] ^ accumulator);
1895            byte_index += 1;
1896        }
1897
1898        let trivial_mask = u8::from(Self::mask_shares_are_trivially_constant(&shares))
1899            | u8::from(Self::mask_accumulator_is_trivial(&shares));
1900        if trivial_mask != 0 {
1901            shares.secure_sanitize();
1902            return Err(SplitSecretError::TrivialMask);
1903        }
1904
1905        for share in shares.iter() {
1906            share.after_secret_write();
1907        }
1908
1909        Ok(Self { shares })
1910    }
1911
1912    #[inline]
1913    fn mask_shares_are_trivially_constant(shares: &[SecretBytes<N>; SHARES]) -> bool {
1914        if N < 2 {
1915            return false;
1916        }
1917
1918        let mut any_trivial = false;
1919        let mut share_index = 0;
1920        while share_index + 1 < SHARES {
1921            let first = shares[share_index].load(0);
1922            let mut byte_index = 1;
1923            let mut all_same = true;
1924            while byte_index < N {
1925                let diff = shares[share_index].load(byte_index) ^ first;
1926                all_same &= diff == 0;
1927                byte_index += 1;
1928            }
1929
1930            any_trivial |= all_same;
1931            share_index += 1;
1932        }
1933
1934        any_trivial
1935    }
1936
1937    #[inline]
1938    fn mask_accumulator_is_trivial(shares: &[SecretBytes<N>; SHARES]) -> bool {
1939        if N == 0 || SHARES < 2 {
1940            return false;
1941        }
1942
1943        let mut first_accumulator = 0u8;
1944        let mut share_index = 0;
1945        while share_index + 1 < SHARES {
1946            first_accumulator ^= shares[share_index].load(0);
1947            share_index += 1;
1948        }
1949
1950        let mut all_same = true;
1951        let mut byte_index = 1;
1952        while byte_index < N {
1953            let mut accumulator = 0u8;
1954            let mut share_index = 0;
1955            while share_index + 1 < SHARES {
1956                accumulator ^= shares[share_index].load(byte_index);
1957                share_index += 1;
1958            }
1959
1960            all_same &= accumulator == first_accumulator;
1961            byte_index += 1;
1962        }
1963
1964        if N == 1 {
1965            first_accumulator == 0
1966        } else {
1967            all_same
1968        }
1969    }
1970}
1971
1972#[cfg(feature = "split-secret")]
1973impl<const N: usize, const SHARES: usize> SecureSanitize for SplitSecretBytes<N, SHARES> {
1974    #[inline]
1975    fn secure_sanitize(&mut self) {
1976        self.shares.secure_sanitize();
1977    }
1978}
1979
1980#[cfg(feature = "split-secret")]
1981impl<const N: usize, const SHARES: usize> StableSharedSecretStorage
1982    for SplitSecretBytes<N, SHARES>
1983{
1984}
1985
1986#[cfg(feature = "split-secret")]
1987impl<const N: usize, const SHARES: usize> StableMutableSecretStorage
1988    for SplitSecretBytes<N, SHARES>
1989{
1990}
1991
1992#[cfg(feature = "split-secret")]
1993impl<const N: usize, const SHARES: usize> fmt::Debug for SplitSecretBytes<N, SHARES> {
1994    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1995        formatter
1996            .debug_struct("SplitSecretBytes")
1997            .field("len", &N)
1998            .field("shares", &SHARES)
1999            .field("contents", &"<redacted>")
2000            .finish()
2001    }
2002}
2003
2004/// Error returned when an expiring secret has exceeded its configured lifetime.
2005#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2006pub struct SecretExpiredError;
2007
2008impl fmt::Display for SecretExpiredError {
2009    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2010        formatter.write_str("secret has expired")
2011    }
2012}
2013
2014#[cfg(feature = "std")]
2015impl std::error::Error for SecretExpiredError {}
2016
2017/// Error returned by expiring secret operations.
2018#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2019pub enum ExpiringSecretError {
2020    /// The secret has exceeded its configured lifetime.
2021    Expired(SecretExpiredError),
2022    /// The caller provided a buffer with the wrong length.
2023    Length(LengthError),
2024}
2025
2026impl fmt::Display for ExpiringSecretError {
2027    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2028        match self {
2029            Self::Expired(error) => error.fmt(formatter),
2030            Self::Length(error) => error.fmt(formatter),
2031        }
2032    }
2033}
2034
2035#[cfg(feature = "std")]
2036impl std::error::Error for ExpiringSecretError {
2037    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2038        match self {
2039            Self::Expired(error) => Some(error),
2040            Self::Length(error) => Some(error),
2041        }
2042    }
2043}
2044
2045impl From<SecretExpiredError> for ExpiringSecretError {
2046    #[inline]
2047    fn from(error: SecretExpiredError) -> Self {
2048        Self::Expired(error)
2049    }
2050}
2051
2052impl From<LengthError> for ExpiringSecretError {
2053    #[inline]
2054    fn from(error: LengthError) -> Self {
2055        Self::Length(error)
2056    }
2057}
2058
2059/// Caller-provided monotonic tick source for no-`std` expiring secrets.
2060///
2061/// The unit is intentionally application-defined: milliseconds, RTOS ticks,
2062/// counter increments, or another monotonic unit. Implementations must not move
2063/// backward for a given secret lifetime window.
2064pub trait MonotonicClock {
2065    /// Return the current monotonic tick value.
2066    fn now(&self) -> u64;
2067}
2068
2069impl<C: MonotonicClock + ?Sized> MonotonicClock for &C {
2070    #[inline]
2071    fn now(&self) -> u64 {
2072        (**self).now()
2073    }
2074}
2075
2076/// Fixed-size secret bytes with caller-provided monotonic lifetime enforcement.
2077///
2078/// This is the `no_std` counterpart to [`ExpiringSecretBytes`]. It wraps
2079/// [`SecretBytes<N>`], stores a caller-provided [`MonotonicClock`], and rejects
2080/// exposure after `max_age` ticks. On expiration, fallible
2081/// read/exposure/comparison methods clear the wrapped secret before returning
2082/// [`SecretExpiredError`].
2083///
2084/// `max_age` is measured in caller-defined ticks. A value of `0` means the
2085/// secret is immediately expired: access methods clear the value and return
2086/// [`SecretExpiredError`]. Use a large policy value, such as `u64::MAX`, when a
2087/// deployment needs an expiration window that should not be reached in normal
2088/// operation.
2089///
2090/// The clock must not move backward for a live value. If a caller-provided tick
2091/// counter wraps so that `now < created_at`, [`Self::age_ticks`] returns `0`
2092/// through saturating arithmetic and the secret appears freshly created.
2093/// Callers using short-period hardware counters must extend or normalize their
2094/// clock before passing it to this type.
2095///
2096/// There is no background task. Expiration is checked only when a method is
2097/// called.
2098pub struct MonotonicExpiringSecretBytes<const N: usize, C: MonotonicClock> {
2099    inner: SecretBytes<N>,
2100    clock: C,
2101    created_at: u64,
2102    max_age: u64,
2103}
2104
2105impl<const N: usize, C: MonotonicClock> MonotonicExpiringSecretBytes<N, C> {
2106    /// Create an all-zero expiring secret.
2107    ///
2108    /// `max_age == 0` creates a secret that is expired immediately on first
2109    /// access. If the caller-provided clock wraps backward, age calculation
2110    /// saturates to `0`; wraparound must be handled by the clock
2111    /// implementation.
2112    #[must_use]
2113    #[inline]
2114    pub fn zeroed(clock: C, max_age: u64) -> Self {
2115        let created_at = clock.now();
2116        Self {
2117            inner: SecretBytes::zeroed(),
2118            clock,
2119            created_at,
2120            max_age,
2121        }
2122    }
2123
2124    /// Create an expiring secret from an array, then volatile-clear the input
2125    /// array.
2126    #[must_use]
2127    #[inline]
2128    pub fn from_array(bytes: [u8; N], clock: C, max_age: u64) -> Self {
2129        let created_at = clock.now();
2130        Self {
2131            inner: SecretBytes::from_array(bytes),
2132            clock,
2133            created_at,
2134            max_age,
2135        }
2136    }
2137
2138    /// Create an expiring secret by producing each byte directly.
2139    #[must_use]
2140    #[inline]
2141    pub fn from_fn(clock: C, max_age: u64, make_byte: impl FnMut(usize) -> u8) -> Self {
2142        let created_at = clock.now();
2143        Self {
2144            inner: SecretBytes::from_fn(make_byte),
2145            clock,
2146            created_at,
2147            max_age,
2148        }
2149    }
2150
2151    /// Create an expiring secret by fallibly producing each byte directly.
2152    ///
2153    /// If `make_byte` returns an error, any bytes generated before the error
2154    /// are cleared before the error is returned.
2155    #[inline]
2156    pub fn try_from_fn<E>(
2157        clock: C,
2158        max_age: u64,
2159        make_byte: impl FnMut(usize) -> Result<u8, E>,
2160    ) -> Result<Self, E> {
2161        let created_at = clock.now();
2162        Ok(Self {
2163            inner: SecretBytes::try_from_fn(make_byte)?,
2164            clock,
2165            created_at,
2166            max_age,
2167        })
2168    }
2169
2170    /// Wrap an existing [`SecretBytes<N>`] and start a new lifetime window.
2171    #[must_use]
2172    #[inline]
2173    pub fn from_secret(secret: SecretBytes<N>, clock: C, max_age: u64) -> Self {
2174        let created_at = clock.now();
2175        Self {
2176            inner: secret,
2177            clock,
2178            created_at,
2179            max_age,
2180        }
2181    }
2182
2183    /// Number of bytes stored in this secret.
2184    #[must_use]
2185    #[inline]
2186    pub const fn len(&self) -> usize {
2187        N
2188    }
2189
2190    /// Returns true when the secret has zero length.
2191    #[must_use]
2192    #[inline]
2193    pub const fn is_empty(&self) -> bool {
2194        N == 0
2195    }
2196
2197    /// Configured maximum age in caller-defined clock ticks.
2198    ///
2199    /// A value of `0` means immediate expiry.
2200    #[must_use]
2201    #[inline]
2202    pub const fn max_age_ticks(&self) -> u64 {
2203        self.max_age
2204    }
2205
2206    /// Elapsed lifetime in caller-defined clock ticks.
2207    ///
2208    /// If the caller-provided clock has moved backward or wrapped around, this
2209    /// returns `0` through saturating arithmetic.
2210    #[must_use]
2211    #[inline]
2212    pub fn age_ticks(&self) -> u64 {
2213        self.clock.now().saturating_sub(self.created_at)
2214    }
2215
2216    /// Returns true when the current secret value has expired.
2217    #[must_use]
2218    #[inline]
2219    pub fn is_expired(&self) -> bool {
2220        self.age_ticks() >= self.max_age
2221    }
2222
2223    /// Borrow the monotonic clock stored by this value.
2224    #[must_use]
2225    #[inline]
2226    pub const fn clock(&self) -> &C {
2227        &self.clock
2228    }
2229
2230    /// Replace all bytes and restart the lifetime window.
2231    ///
2232    /// The replacement is validated and staged first. The old value is then
2233    /// volatile-cleared before the replacement is installed.
2234    #[inline]
2235    pub fn replace_from_slice(&mut self, source: &[u8]) -> Result<(), LengthError> {
2236        if source.len() != N {
2237            if self.is_expired() {
2238                self.inner.secure_clear();
2239            }
2240            return Err(LengthError {
2241                expected: N,
2242                actual: source.len(),
2243            });
2244        }
2245
2246        let mut replacement = SecretBytes::<N>::zeroed();
2247        replacement.copy_from_slice(source)?;
2248        self.inner.secure_clear();
2249        self.inner = replacement;
2250        self.created_at = self.clock.now();
2251        Ok(())
2252    }
2253
2254    /// Replace all bytes from an owned array, clear that input array, and
2255    /// restart the lifetime window.
2256    #[inline]
2257    pub fn replace_from_array(&mut self, bytes: [u8; N]) {
2258        let replacement = SecretBytes::from_array(bytes);
2259        self.inner.secure_clear();
2260        self.inner = replacement;
2261        self.created_at = self.clock.now();
2262    }
2263
2264    /// Replace all bytes from a generator and restart the lifetime window.
2265    #[inline]
2266    pub fn replace_from_fn(&mut self, make_byte: impl FnMut(usize) -> u8) {
2267        let expired = self.is_expired();
2268        if expired {
2269            self.inner.secure_clear();
2270        }
2271
2272        let replacement = SecretBytes::from_fn(make_byte);
2273        if !expired {
2274            self.inner.secure_clear();
2275        }
2276        self.inner = replacement;
2277        self.created_at = self.clock.now();
2278    }
2279
2280    /// Replace all bytes from a fallible generator and restart the lifetime
2281    /// window.
2282    ///
2283    /// If the old value is still live and generation fails, the old value
2284    /// remains unchanged. If the old value has already expired, it is cleared
2285    /// before generation and remains cleared if generation fails.
2286    #[inline]
2287    pub fn try_replace_from_fn<E>(
2288        &mut self,
2289        make_byte: impl FnMut(usize) -> Result<u8, E>,
2290    ) -> Result<(), E> {
2291        let expired = self.is_expired();
2292        if expired {
2293            self.inner.secure_clear();
2294        }
2295
2296        let replacement = SecretBytes::try_from_fn(make_byte)?;
2297        if !expired {
2298            self.inner.secure_clear();
2299        }
2300        self.inner = replacement;
2301        self.created_at = self.clock.now();
2302        Ok(())
2303    }
2304
2305    /// Fill a caller-provided destination with a copy of the secret bytes if
2306    /// the secret has not expired.
2307    #[inline]
2308    pub fn try_export_to_slice(
2309        &mut self,
2310        reason: &'static str,
2311        destination: &mut [u8],
2312    ) -> Result<(), ExpiringSecretError> {
2313        self.enforce_live()?;
2314        self.inner
2315            .export_to_slice(reason, destination)
2316            .map_err(Into::into)
2317    }
2318
2319    /// Run a closure with direct shared access if the secret has not expired.
2320    #[inline]
2321    pub fn try_expose_secret<R>(
2322        &mut self,
2323        inspect: impl FnOnce(&[u8; N]) -> R,
2324    ) -> Result<R, SecretExpiredError> {
2325        self.enforce_live()?;
2326        Ok(self.inner.expose_secret(inspect))
2327    }
2328
2329    /// Run a closure with a temporary array copy if the secret has not expired.
2330    ///
2331    /// This is the monotonic-clock variant of
2332    /// [`SecretBytes::export_secret_copy`].
2333    #[inline]
2334    pub fn try_export_secret_copy<R>(
2335        &mut self,
2336        reason: &'static str,
2337        inspect: impl FnOnce(&[u8; N]) -> R,
2338    ) -> Result<R, SecretExpiredError> {
2339        self.enforce_live()?;
2340        Ok(self.inner.export_secret_copy(reason, inspect))
2341    }
2342
2343    /// Compare against a slice if the secret has not expired.
2344    ///
2345    /// Length mismatch remains public metadata and returns `Ok(false)`.
2346    #[inline]
2347    pub fn try_constant_time_eq(&mut self, other: &[u8]) -> Result<bool, SecretExpiredError> {
2348        self.enforce_live()?;
2349        Ok(self.inner.constant_time_eq(other))
2350    }
2351
2352    /// Clear the wrapped secret immediately.
2353    #[inline(never)]
2354    pub fn secure_clear(&mut self) {
2355        self.inner.secure_clear();
2356    }
2357
2358    /// Consume this value after first clearing the wrapped secret.
2359    #[inline]
2360    pub fn into_cleared(mut self) {
2361        self.secure_clear();
2362    }
2363
2364    #[inline]
2365    fn enforce_live(&mut self) -> Result<(), SecretExpiredError> {
2366        if self.is_expired() {
2367            self.inner.secure_clear();
2368            Err(SecretExpiredError)
2369        } else {
2370            Ok(())
2371        }
2372    }
2373}
2374
2375impl<const N: usize, C: MonotonicClock> Drop for MonotonicExpiringSecretBytes<N, C> {
2376    #[inline]
2377    fn drop(&mut self) {
2378        self.secure_clear();
2379    }
2380}
2381
2382impl<const N: usize, C: MonotonicClock> SecureSanitize for MonotonicExpiringSecretBytes<N, C> {
2383    #[inline]
2384    fn secure_sanitize(&mut self) {
2385        self.secure_clear();
2386    }
2387}
2388
2389impl<const N: usize, C: MonotonicClock> fmt::Debug for MonotonicExpiringSecretBytes<N, C> {
2390    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2391        formatter
2392            .debug_struct("MonotonicExpiringSecretBytes")
2393            .field("len", &N)
2394            .field("age_ticks", &self.age_ticks())
2395            .field("max_age_ticks", &self.max_age)
2396            .field("contents", &"<redacted>")
2397            .finish()
2398    }
2399}
2400
2401/// Fixed-size secret bytes with `std` lifetime enforcement.
2402///
2403/// This type is available with the `std` feature. It wraps [`SecretBytes<N>`],
2404/// tracks creation time with [`std::time::Instant`], and rejects exposure after
2405/// the configured maximum age. On expiration, fallible read/exposure/comparison
2406/// methods clear the wrapped secret before returning [`SecretExpiredError`].
2407///
2408/// There is no background task. Expiration is checked only when a method is
2409/// called.
2410#[cfg(feature = "std")]
2411pub struct ExpiringSecretBytes<const N: usize> {
2412    inner: SecretBytes<N>,
2413    created_at: std::time::Instant,
2414    max_age: std::time::Duration,
2415}
2416
2417#[cfg(feature = "std")]
2418impl<const N: usize> ExpiringSecretBytes<N> {
2419    /// Create an all-zero expiring secret.
2420    #[must_use]
2421    #[inline]
2422    pub fn zeroed(max_age: std::time::Duration) -> Self {
2423        Self {
2424            inner: SecretBytes::zeroed(),
2425            created_at: std::time::Instant::now(),
2426            max_age,
2427        }
2428    }
2429
2430    /// Create an expiring secret from an array, then volatile-clear the input
2431    /// array.
2432    #[must_use]
2433    #[inline]
2434    pub fn from_array(bytes: [u8; N], max_age: std::time::Duration) -> Self {
2435        Self {
2436            inner: SecretBytes::from_array(bytes),
2437            created_at: std::time::Instant::now(),
2438            max_age,
2439        }
2440    }
2441
2442    /// Create an expiring secret by producing each byte directly.
2443    #[must_use]
2444    #[inline]
2445    pub fn from_fn(max_age: std::time::Duration, make_byte: impl FnMut(usize) -> u8) -> Self {
2446        Self {
2447            inner: SecretBytes::from_fn(make_byte),
2448            created_at: std::time::Instant::now(),
2449            max_age,
2450        }
2451    }
2452
2453    /// Create an expiring secret by fallibly producing each byte directly.
2454    ///
2455    /// If `make_byte` returns an error, any bytes generated before the error
2456    /// are cleared before the error is returned.
2457    #[inline]
2458    pub fn try_from_fn<E>(
2459        max_age: std::time::Duration,
2460        make_byte: impl FnMut(usize) -> Result<u8, E>,
2461    ) -> Result<Self, E> {
2462        Ok(Self {
2463            inner: SecretBytes::try_from_fn(make_byte)?,
2464            created_at: std::time::Instant::now(),
2465            max_age,
2466        })
2467    }
2468
2469    /// Wrap an existing [`SecretBytes<N>`] and start a new lifetime window.
2470    #[must_use]
2471    #[inline]
2472    pub fn from_secret(secret: SecretBytes<N>, max_age: std::time::Duration) -> Self {
2473        Self {
2474            inner: secret,
2475            created_at: std::time::Instant::now(),
2476            max_age,
2477        }
2478    }
2479
2480    /// Number of bytes stored in this secret.
2481    #[must_use]
2482    #[inline]
2483    pub const fn len(&self) -> usize {
2484        N
2485    }
2486
2487    /// Returns true when the secret has zero length.
2488    #[must_use]
2489    #[inline]
2490    pub const fn is_empty(&self) -> bool {
2491        N == 0
2492    }
2493
2494    /// Configured maximum age for the current secret value.
2495    #[must_use]
2496    #[inline]
2497    pub const fn max_age(&self) -> std::time::Duration {
2498        self.max_age
2499    }
2500
2501    /// Elapsed lifetime of the current secret value.
2502    #[must_use]
2503    #[inline]
2504    pub fn age(&self) -> std::time::Duration {
2505        self.created_at.elapsed()
2506    }
2507
2508    /// Returns true when the current secret value has expired.
2509    #[must_use]
2510    #[inline]
2511    pub fn is_expired(&self) -> bool {
2512        self.age() >= self.max_age
2513    }
2514
2515    /// Replace all bytes and restart the lifetime window.
2516    ///
2517    /// The replacement is validated and staged first. The old value is then
2518    /// volatile-cleared before the replacement is installed.
2519    #[inline]
2520    pub fn replace_from_slice(&mut self, source: &[u8]) -> Result<(), LengthError> {
2521        if source.len() != N {
2522            if self.is_expired() {
2523                self.inner.secure_clear();
2524            }
2525            return Err(LengthError {
2526                expected: N,
2527                actual: source.len(),
2528            });
2529        }
2530
2531        let mut replacement = SecretBytes::<N>::zeroed();
2532        replacement.copy_from_slice(source)?;
2533        self.inner.secure_clear();
2534        self.inner = replacement;
2535        self.created_at = std::time::Instant::now();
2536        Ok(())
2537    }
2538
2539    /// Replace all bytes from an owned array, clear that input array, and
2540    /// restart the lifetime window.
2541    ///
2542    /// The replacement is staged first. The old value is then volatile-cleared
2543    /// before the replacement is installed.
2544    #[inline]
2545    pub fn replace_from_array(&mut self, bytes: [u8; N]) {
2546        let replacement = SecretBytes::from_array(bytes);
2547        self.inner.secure_clear();
2548        self.inner = replacement;
2549        self.created_at = std::time::Instant::now();
2550    }
2551
2552    /// Replace all bytes from a generator and restart the lifetime window.
2553    ///
2554    /// If the previous value has already expired, it is cleared before the new
2555    /// value is generated. If `make_byte` panics and the old value was still
2556    /// live, the old value remains unchanged.
2557    #[inline]
2558    pub fn replace_from_fn(&mut self, make_byte: impl FnMut(usize) -> u8) {
2559        let expired = self.is_expired();
2560        if expired {
2561            self.inner.secure_clear();
2562        }
2563
2564        let replacement = SecretBytes::from_fn(make_byte);
2565        if !expired {
2566            self.inner.secure_clear();
2567        }
2568        self.inner = replacement;
2569        self.created_at = std::time::Instant::now();
2570    }
2571
2572    /// Replace all bytes from a fallible generator and restart the lifetime
2573    /// window.
2574    ///
2575    /// If the old value is still live and generation fails, the old value
2576    /// remains unchanged. If the old value has already expired, it is cleared
2577    /// before generation and remains cleared if generation fails.
2578    #[inline]
2579    pub fn try_replace_from_fn<E>(
2580        &mut self,
2581        make_byte: impl FnMut(usize) -> Result<u8, E>,
2582    ) -> Result<(), E> {
2583        let expired = self.is_expired();
2584        if expired {
2585            self.inner.secure_clear();
2586        }
2587
2588        let replacement = SecretBytes::try_from_fn(make_byte)?;
2589        if !expired {
2590            self.inner.secure_clear();
2591        }
2592        self.inner = replacement;
2593        self.created_at = std::time::Instant::now();
2594        Ok(())
2595    }
2596
2597    /// Fill a caller-provided destination with a copy of the secret bytes if
2598    /// the secret has not expired.
2599    #[inline]
2600    pub fn try_export_to_slice(
2601        &mut self,
2602        reason: &'static str,
2603        destination: &mut [u8],
2604    ) -> Result<(), ExpiringSecretError> {
2605        self.enforce_live()?;
2606        self.inner
2607            .export_to_slice(reason, destination)
2608            .map_err(Into::into)
2609    }
2610
2611    /// Run a closure with direct shared access if the secret has not expired.
2612    #[inline]
2613    pub fn try_expose_secret<R>(
2614        &mut self,
2615        inspect: impl FnOnce(&[u8; N]) -> R,
2616    ) -> Result<R, SecretExpiredError> {
2617        self.enforce_live()?;
2618        Ok(self.inner.expose_secret(inspect))
2619    }
2620
2621    /// Run a closure with a temporary array copy if the secret has not expired.
2622    ///
2623    /// This is the expiring variant of [`SecretBytes::export_secret_copy`].
2624    #[inline]
2625    pub fn try_export_secret_copy<R>(
2626        &mut self,
2627        reason: &'static str,
2628        inspect: impl FnOnce(&[u8; N]) -> R,
2629    ) -> Result<R, SecretExpiredError> {
2630        self.enforce_live()?;
2631        Ok(self.inner.export_secret_copy(reason, inspect))
2632    }
2633
2634    /// Compare against a slice if the secret has not expired.
2635    ///
2636    /// Length mismatch remains public metadata and returns `Ok(false)`.
2637    ///
2638    /// This delegates to [`SecretBytes::constant_time_eq`]; see that method for
2639    /// portable fallback timing limits.
2640    #[inline]
2641    pub fn try_constant_time_eq(&mut self, other: &[u8]) -> Result<bool, SecretExpiredError> {
2642        self.enforce_live()?;
2643        Ok(self.inner.constant_time_eq(other))
2644    }
2645
2646    /// Clear the wrapped secret immediately.
2647    #[inline(never)]
2648    pub fn secure_clear(&mut self) {
2649        self.inner.secure_clear();
2650    }
2651
2652    /// Consume this value after first clearing the wrapped secret.
2653    ///
2654    /// Drop still runs after this method returns, so the wrapped storage is
2655    /// cleared a second time on the normal path.
2656    #[inline]
2657    pub fn into_cleared(mut self) {
2658        self.secure_clear();
2659    }
2660
2661    #[inline]
2662    fn enforce_live(&mut self) -> Result<(), SecretExpiredError> {
2663        if self.is_expired() {
2664            self.inner.secure_clear();
2665            Err(SecretExpiredError)
2666        } else {
2667            Ok(())
2668        }
2669    }
2670}
2671
2672#[cfg(feature = "std")]
2673impl<const N: usize> Drop for ExpiringSecretBytes<N> {
2674    #[inline]
2675    fn drop(&mut self) {
2676        self.secure_clear();
2677    }
2678}
2679
2680#[cfg(feature = "std")]
2681impl<const N: usize> SecureSanitize for ExpiringSecretBytes<N> {
2682    #[inline]
2683    fn secure_sanitize(&mut self) {
2684        self.secure_clear();
2685    }
2686}
2687
2688#[cfg(feature = "std")]
2689impl<const N: usize> StableSharedSecretStorage for ExpiringSecretBytes<N> {}
2690
2691#[cfg(feature = "std")]
2692impl<const N: usize> StableMutableSecretStorage for ExpiringSecretBytes<N> {}
2693
2694#[cfg(feature = "std")]
2695impl<const N: usize> fmt::Debug for ExpiringSecretBytes<N> {
2696    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2697        formatter
2698            .debug_struct("ExpiringSecretBytes")
2699            .field("len", &N)
2700            .field("max_age", &self.max_age)
2701            .field("contents", &"<redacted>")
2702            .finish()
2703    }
2704}
2705
2706/// Fixed-allocation secret bytes with a runtime length.
2707///
2708/// This type is available with the `alloc` feature. Unlike [`SecretVec`], its
2709/// public API cannot grow or shrink the private backing allocation after
2710/// construction. Mutable exposure receives only `&mut [u8]`, so safe
2711/// operations cannot reallocate it. The private `Vec<u8>` representation exists
2712/// so bounded constructors can use fallible reservation; the safe API never
2713/// exposes vector growth or ownership extraction.
2714///
2715/// Replacement requires the same public length. A replacement value is fully
2716/// constructed in a separate clear-on-drop allocation before the old
2717/// allocation is cleared and exchanged. Use [`SecretVec`] when the secret
2718/// length must change over time.
2719///
2720/// Clearing covers the backing allocation's full capacity, including any
2721/// allocator-provided spare bytes.
2722///
2723/// The type deliberately does not implement `Clone`, `Copy`, `Deref`,
2724/// `AsRef<[u8]>`, `PartialEq`, or secret-printing `Debug`.
2725#[cfg(feature = "alloc")]
2726pub struct SecretBoxBytes {
2727    pub(crate) inner: Vec<u8>,
2728}
2729
2730#[cfg(feature = "alloc")]
2731impl SecretBoxBytes {
2732    /// Allocate `len` zeroed secret bytes.
2733    ///
2734    /// `len` must already be validated as trusted public metadata. Like
2735    /// ordinary infallible Rust allocation APIs, allocation failure may abort
2736    /// the process. Use [`SecretBoxBytes::try_zeroed`] for untrusted lengths or
2737    /// availability-sensitive code.
2738    #[must_use]
2739    #[inline]
2740    pub fn zeroed(len: usize) -> Self {
2741        Self {
2742            inner: alloc::vec![0; len],
2743        }
2744    }
2745
2746    /// Allocate a bounded fixed-length secret without aborting on reserve
2747    /// failure.
2748    ///
2749    /// The public maximum is checked before allocation. After
2750    /// `try_reserve_exact` succeeds, resizing to `len` cannot allocate.
2751    #[inline]
2752    pub fn try_zeroed(len: usize, maximum: usize) -> Result<Self, SecretBoxBytesBuildError> {
2753        if len > maximum {
2754            return Err(SecretBoxBytesBuildError::TooLong {
2755                maximum,
2756                actual: len,
2757            });
2758        }
2759
2760        let mut inner = Vec::new();
2761        inner
2762            .try_reserve_exact(len)
2763            .map_err(SecretBoxBytesBuildError::Allocation)?;
2764        inner.resize(len, 0);
2765        Ok(Self { inner })
2766    }
2767
2768    /// Take ownership of an existing boxed byte slice.
2769    ///
2770    /// The allocation is not copied. Its complete length is volatile-cleared
2771    /// when this value is cleared or dropped.
2772    #[must_use]
2773    #[inline]
2774    pub fn from_boxed_slice(inner: Box<[u8]>) -> Self {
2775        Self {
2776            inner: inner.into_vec(),
2777        }
2778    }
2779
2780    /// Allocate fixed-length storage and copy bytes into it.
2781    ///
2782    /// The slice length must already be validated when it comes from untrusted
2783    /// metadata. Use [`SecretBoxBytes::try_from_slice`] to apply a public bound
2784    /// and return allocation failure.
2785    #[must_use]
2786    #[inline]
2787    pub fn from_slice(bytes: &[u8]) -> Self {
2788        Self {
2789            inner: Vec::from(bytes),
2790        }
2791    }
2792
2793    /// Copy a bounded slice into fallibly allocated fixed-length storage.
2794    #[inline]
2795    pub fn try_from_slice(bytes: &[u8], maximum: usize) -> Result<Self, SecretBoxBytesBuildError> {
2796        let mut secret = Self::try_zeroed(bytes.len(), maximum)?;
2797        secret.inner.copy_from_slice(bytes);
2798        Ok(secret)
2799    }
2800
2801    /// Generate each byte directly into fixed-length clear-on-drop storage.
2802    ///
2803    /// If the generator panics, the partially initialized value is cleared
2804    /// during unwinding. `len` must already be trusted and bounded; allocation
2805    /// failure may abort. Use [`SecretBoxBytes::try_from_fn_bounded`] for
2806    /// untrusted lengths.
2807    #[must_use]
2808    #[inline]
2809    pub fn from_fn(len: usize, mut make_byte: impl FnMut(usize) -> u8) -> Self {
2810        let mut secret = Self::zeroed(len);
2811        let mut index = 0;
2812        while index < len {
2813            secret.inner[index] = make_byte(index);
2814            index += 1;
2815        }
2816        secret
2817    }
2818
2819    /// Generate each byte with a fallible generator.
2820    ///
2821    /// If generation fails, the partially initialized allocation is cleared
2822    /// before the error is returned. This method only reports generator errors;
2823    /// `len` must already be trusted and bounded, and allocation failure may
2824    /// abort. Use [`SecretBoxBytes::try_from_fn_bounded`] when allocation must
2825    /// also be fallible.
2826    #[inline]
2827    pub fn try_from_fn<E>(
2828        len: usize,
2829        mut make_byte: impl FnMut(usize) -> Result<u8, E>,
2830    ) -> Result<Self, E> {
2831        let mut secret = Self::zeroed(len);
2832        let mut index = 0;
2833        while index < len {
2834            secret.inner[index] = make_byte(index)?;
2835            index += 1;
2836        }
2837        Ok(secret)
2838    }
2839
2840    /// Generate a bounded fixed-length secret with fallible allocation and
2841    /// fallible byte generation.
2842    #[inline]
2843    pub fn try_from_fn_bounded<E>(
2844        len: usize,
2845        maximum: usize,
2846        mut make_byte: impl FnMut(usize) -> Result<u8, E>,
2847    ) -> Result<Self, SecretBoxBytesGenerateError<E>> {
2848        let mut secret =
2849            Self::try_zeroed(len, maximum).map_err(SecretBoxBytesGenerateError::Build)?;
2850        let mut index = 0;
2851        while index < len {
2852            secret.inner[index] =
2853                make_byte(index).map_err(SecretBoxBytesGenerateError::Generate)?;
2854            index += 1;
2855        }
2856        Ok(secret)
2857    }
2858
2859    /// Number of initialized bytes in the fixed allocation.
2860    #[must_use]
2861    #[inline]
2862    pub const fn len(&self) -> usize {
2863        self.inner.len()
2864    }
2865
2866    /// Returns true when the fixed allocation has length zero.
2867    #[must_use]
2868    #[inline]
2869    pub const fn is_empty(&self) -> bool {
2870        self.inner.is_empty()
2871    }
2872
2873    /// Run a closure with direct shared access to the fixed allocation.
2874    ///
2875    /// The returned value cannot borrow the secret:
2876    ///
2877    /// ```compile_fail
2878    /// use sanitization::SecretBoxBytes;
2879    ///
2880    /// let secret = SecretBoxBytes::from_slice(b"token");
2881    /// let escaped = secret.with_secret(|bytes| bytes);
2882    /// let _ = escaped;
2883    /// ```
2884    #[inline]
2885    pub fn with_secret<R>(&self, inspect: impl FnOnce(&[u8]) -> R) -> R {
2886        inspect(self.inner.as_slice())
2887    }
2888
2889    /// Run a closure with direct mutable access to the fixed allocation.
2890    ///
2891    /// A mutable slice cannot resize or replace the backing allocation.
2892    #[inline]
2893    pub fn with_secret_mut<R>(&mut self, edit: impl FnOnce(&mut [u8]) -> R) -> R {
2894        edit(self.inner.as_mut_slice())
2895    }
2896
2897    /// Copy the secret into a caller-provided slice of the same public length.
2898    #[inline]
2899    pub fn copy_to_slice(&self, destination: &mut [u8]) -> Result<(), LengthError> {
2900        if destination.len() != self.len() {
2901            return Err(LengthError {
2902                expected: self.len(),
2903                actual: destination.len(),
2904            });
2905        }
2906
2907        destination.copy_from_slice(self.inner.as_slice());
2908        Ok(())
2909    }
2910
2911    /// Replace the secret from a same-length slice.
2912    ///
2913    /// The replacement allocation is constructed before the old allocation is
2914    /// cleared. A length mismatch leaves the existing secret unchanged.
2915    #[inline]
2916    pub fn replace_from_slice(&mut self, bytes: &[u8]) -> Result<(), LengthError> {
2917        self.ensure_replacement_len(bytes.len())?;
2918        let replacement = Self::from_slice(bytes);
2919        self.replace_staged(replacement);
2920        Ok(())
2921    }
2922
2923    /// Replace the secret by taking ownership of a same-length boxed slice.
2924    ///
2925    /// On length mismatch, the rejected boxed bytes are cleared before this
2926    /// method returns the error.
2927    #[inline]
2928    pub fn replace_from_boxed_slice(&mut self, bytes: Box<[u8]>) -> Result<(), LengthError> {
2929        let replacement = Self::from_boxed_slice(bytes);
2930        self.ensure_replacement_len(replacement.len())?;
2931        self.replace_staged(replacement);
2932        Ok(())
2933    }
2934
2935    /// Replace the secret with same-length generated bytes.
2936    ///
2937    /// The replacement is generated in a fresh clear-on-drop allocation. If
2938    /// generation panics, the old value remains unchanged.
2939    #[inline]
2940    pub fn replace_from_fn(&mut self, make_byte: impl FnMut(usize) -> u8) {
2941        let replacement = Self::from_fn(self.len(), make_byte);
2942        self.replace_staged(replacement);
2943    }
2944
2945    /// Replace the secret with same-length fallibly generated bytes.
2946    ///
2947    /// If generation fails, the old value remains unchanged and the partial
2948    /// replacement is cleared before the error is returned.
2949    #[inline]
2950    pub fn try_replace_from_fn<E>(
2951        &mut self,
2952        make_byte: impl FnMut(usize) -> Result<u8, E>,
2953    ) -> Result<(), E> {
2954        let replacement = Self::try_from_fn(self.len(), make_byte)?;
2955        self.replace_staged(replacement);
2956        Ok(())
2957    }
2958
2959    /// Clear every byte while retaining the fixed allocation and length.
2960    #[inline(never)]
2961    pub fn clear_secret(&mut self) {
2962        wipe_backend::erase(self.inner.as_mut_ptr(), self.inner.capacity());
2963    }
2964
2965    /// Consume this value after clearing its complete allocation.
2966    #[inline]
2967    pub fn into_cleared(mut self) {
2968        self.clear_secret();
2969    }
2970
2971    /// Compare against a slice without early exit for equal-length inputs.
2972    ///
2973    /// Length is treated as public metadata.
2974    #[must_use]
2975    #[inline]
2976    pub fn constant_time_eq(&self, other: &[u8]) -> bool {
2977        constant_time_eq_slices(self.inner.as_slice(), other)
2978    }
2979
2980    #[inline]
2981    fn ensure_replacement_len(&self, actual: usize) -> Result<(), LengthError> {
2982        if actual == self.len() {
2983            Ok(())
2984        } else {
2985            Err(LengthError {
2986                expected: self.len(),
2987                actual,
2988            })
2989        }
2990    }
2991
2992    #[inline]
2993    fn replace_staged(&mut self, mut replacement: Self) {
2994        self.clear_secret();
2995        core::mem::swap(&mut self.inner, &mut replacement.inner);
2996    }
2997}
2998
2999#[cfg(feature = "alloc")]
3000impl Drop for SecretBoxBytes {
3001    #[inline]
3002    fn drop(&mut self) {
3003        self.clear_secret();
3004    }
3005}
3006
3007#[cfg(feature = "alloc")]
3008impl Default for SecretBoxBytes {
3009    #[inline]
3010    fn default() -> Self {
3011        Self::zeroed(0)
3012    }
3013}
3014
3015#[cfg(feature = "alloc")]
3016impl SecureSanitize for SecretBoxBytes {
3017    #[inline]
3018    fn secure_sanitize(&mut self) {
3019        self.clear_secret();
3020    }
3021}
3022
3023#[cfg(feature = "alloc")]
3024impl StableSharedSecretStorage for SecretBoxBytes {}
3025
3026#[cfg(feature = "alloc")]
3027impl StableMutableSecretStorage for SecretBoxBytes {}
3028
3029#[cfg(feature = "alloc")]
3030impl fmt::Debug for SecretBoxBytes {
3031    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3032        formatter
3033            .debug_struct("SecretBoxBytes")
3034            .field("len", &self.len())
3035            .field("contents", &"<redacted>")
3036            .finish()
3037    }
3038}
3039
3040#[cfg(feature = "alloc")]
3041impl ct::ConstantTimeEq for SecretBoxBytes {
3042    #[inline]
3043    fn ct_eq(&self, other: &Self) -> ct::Choice {
3044        ct::eq_public_len(self.inner.as_slice(), other.inner.as_slice())
3045    }
3046}
3047
3048#[cfg(feature = "alloc")]
3049impl ct::ConstantTimeEq<[u8]> for SecretBoxBytes {
3050    #[inline]
3051    fn ct_eq(&self, other: &[u8]) -> ct::Choice {
3052        ct::eq_public_len(self.inner.as_slice(), other)
3053    }
3054}
3055
3056/// Error returned when fallible dynamic secret allocation fails.
3057///
3058/// Public lengths and configured maxima are not treated as secret data.
3059#[cfg(feature = "alloc")]
3060#[derive(Debug)]
3061pub enum SecretAllocationError {
3062    /// The requested public length exceeded the caller's maximum.
3063    TooLong {
3064        /// Maximum accepted length.
3065        maximum: usize,
3066        /// Rejected requested length.
3067        actual: usize,
3068    },
3069    /// Arithmetic for the required allocation capacity overflowed.
3070    CapacityOverflow,
3071    /// The allocator could not reserve the requested storage.
3072    Allocation(alloc::collections::TryReserveError),
3073}
3074
3075#[cfg(feature = "alloc")]
3076impl From<alloc::collections::TryReserveError> for SecretAllocationError {
3077    #[inline]
3078    fn from(error: alloc::collections::TryReserveError) -> Self {
3079        Self::Allocation(error)
3080    }
3081}
3082
3083#[cfg(feature = "alloc")]
3084impl fmt::Display for SecretAllocationError {
3085    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3086        match self {
3087            Self::TooLong { maximum, actual } => write!(
3088                formatter,
3089                "secret length exceeds limit: maximum {maximum} bytes, got {actual} bytes"
3090            ),
3091            Self::CapacityOverflow => formatter.write_str("secret capacity calculation overflowed"),
3092            Self::Allocation(error) => write!(formatter, "secret allocation failed: {error}"),
3093        }
3094    }
3095}
3096
3097#[cfg(feature = "std")]
3098impl std::error::Error for SecretAllocationError {
3099    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
3100        match self {
3101            Self::TooLong { .. } | Self::CapacityOverflow => None,
3102            Self::Allocation(error) => Some(error),
3103        }
3104    }
3105}
3106
3107/// Error returned by fallible dynamic secret generation.
3108///
3109/// Partially generated storage remains owned by a clear-on-drop value on every
3110/// error path.
3111#[cfg(feature = "alloc")]
3112#[derive(Debug)]
3113pub enum SecretGenerateError<E> {
3114    /// Allocation or public-length validation failed.
3115    Build(SecretAllocationError),
3116    /// The caller's generator failed.
3117    Generate(E),
3118}
3119
3120#[cfg(feature = "alloc")]
3121impl<E> From<SecretAllocationError> for SecretGenerateError<E> {
3122    #[inline]
3123    fn from(error: SecretAllocationError) -> Self {
3124        Self::Build(error)
3125    }
3126}
3127
3128#[cfg(feature = "alloc")]
3129impl<E: fmt::Display> fmt::Display for SecretGenerateError<E> {
3130    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3131        match self {
3132            Self::Build(error) => error.fmt(formatter),
3133            Self::Generate(error) => write!(formatter, "secret generation failed: {error}"),
3134        }
3135    }
3136}
3137
3138#[cfg(feature = "std")]
3139impl<E> std::error::Error for SecretGenerateError<E>
3140where
3141    E: std::error::Error + 'static,
3142{
3143    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
3144        match self {
3145            Self::Build(error) => Some(error),
3146            Self::Generate(error) => Some(error),
3147        }
3148    }
3149}
3150
3151/// Compatibility name for fixed-allocation build failures.
3152#[cfg(feature = "alloc")]
3153pub type SecretBoxBytesBuildError = SecretAllocationError;
3154
3155/// Compatibility name for fixed-allocation generation failures.
3156#[cfg(feature = "alloc")]
3157pub type SecretBoxBytesGenerateError<E> = SecretGenerateError<E>;
3158
3159/// Heap-allocated secret bytes with clear-on-drop behavior.
3160///
3161/// This type is available with the `alloc` feature. It is intended for
3162/// integration boundaries where the secret length is dynamic, such as decoded
3163/// tokens or PEM/DER material. Clearing uses volatile writes over the full
3164/// allocation capacity before the vector length is set to zero.
3165///
3166/// With the `serde` feature, deserialization rejects inputs larger than
3167/// [`DEFAULT_SECRET_VEC_SERDE_MAX_LEN`]. Use [`BoundedSecretVec<MAX>`] at
3168/// boundaries that require a different application-defined maximum.
3169#[cfg(feature = "alloc")]
3170pub struct SecretVec {
3171    pub(crate) inner: Vec<u8>,
3172}
3173
3174/// Default maximum accepted by serde deserialization into [`SecretVec`].
3175///
3176/// The 1 MiB ceiling prevents accidental unbounded allocation while remaining
3177/// large enough for typical encoded keys, tokens, and certificate material.
3178/// Use [`BoundedSecretVec<MAX>`] when a protocol requires a different limit.
3179#[cfg(feature = "alloc")]
3180pub const DEFAULT_SECRET_VEC_SERDE_MAX_LEN: usize = 1024 * 1024;
3181
3182#[cfg(feature = "alloc")]
3183impl SecretVec {
3184    /// Wrap a vector using volatile clearing on drop.
3185    #[must_use]
3186    #[inline]
3187    pub const fn new(inner: Vec<u8>) -> Self {
3188        Self { inner }
3189    }
3190
3191    /// Wrap an existing vector using volatile clearing on drop.
3192    ///
3193    /// This is an explicit ownership-taking alias for [`SecretVec::new`]. The
3194    /// vector is not copied; its full capacity will be volatile-cleared when
3195    /// this `SecretVec` is cleared or dropped.
3196    #[must_use]
3197    #[inline]
3198    pub const fn from_vec(bytes: Vec<u8>) -> Self {
3199        Self::new(bytes)
3200    }
3201
3202    /// Create an empty secret vector.
3203    #[must_use]
3204    #[inline]
3205    pub const fn empty() -> Self {
3206        Self::new(Vec::new())
3207    }
3208
3209    /// Create an empty secret vector with at least the requested capacity.
3210    ///
3211    /// `capacity` must be trusted and bounded. Allocation failure may abort;
3212    /// use [`SecretVec::try_with_capacity`] when it must be reported.
3213    #[must_use]
3214    #[inline]
3215    pub fn with_capacity(capacity: usize) -> Self {
3216        Self::new(Vec::with_capacity(capacity))
3217    }
3218
3219    /// Create an empty secret vector using fallible allocation.
3220    ///
3221    /// Unlike [`SecretVec::with_capacity`], this reports capacity overflow or
3222    /// allocation failure instead of panicking or invoking the allocation
3223    /// error handler.
3224    #[inline]
3225    pub fn try_with_capacity(capacity: usize) -> Result<Self, SecretAllocationError> {
3226        let mut inner = Vec::new();
3227        inner
3228            .try_reserve_exact(capacity)
3229            .map_err(SecretAllocationError::Allocation)?;
3230        Ok(Self::new(inner))
3231    }
3232
3233    /// Create a secret vector by copying bytes from a slice.
3234    ///
3235    /// The public length must be trusted and bounded. Use
3236    /// [`SecretVec::try_from_slice_bounded`] at untrusted boundaries.
3237    #[must_use]
3238    #[inline]
3239    pub fn from_slice(bytes: &[u8]) -> Self {
3240        Self::new(Vec::from(bytes))
3241    }
3242
3243    /// Copy a slice after enforcing a public byte-length ceiling and using
3244    /// fallible allocation.
3245    ///
3246    /// Length validation happens before allocation. The borrowed source is not
3247    /// cleared by this method.
3248    #[inline]
3249    pub fn try_from_slice_bounded(
3250        bytes: &[u8],
3251        maximum: usize,
3252    ) -> Result<Self, SecretAllocationError> {
3253        if bytes.len() > maximum {
3254            return Err(SecretAllocationError::TooLong {
3255                maximum,
3256                actual: bytes.len(),
3257            });
3258        }
3259
3260        let mut secret = Self::try_with_capacity(bytes.len())?;
3261        secret.inner.extend_from_slice(bytes);
3262        Ok(secret)
3263    }
3264
3265    /// Create a secret vector by generating each byte directly into a
3266    /// clear-on-drop allocation.
3267    ///
3268    /// If `make_byte` panics, any bytes generated before the panic are still
3269    /// owned by a `SecretVec` local and are cleared during unwinding.
3270    /// `len` must be trusted and bounded; allocation failure may abort.
3271    #[must_use]
3272    #[inline]
3273    pub fn from_fn(len: usize, mut make_byte: impl FnMut(usize) -> u8) -> Self {
3274        let mut secret = Self::with_capacity(len);
3275        let mut index = 0;
3276        while index < len {
3277            secret.inner.push(make_byte(index));
3278            index += 1;
3279        }
3280        secret
3281    }
3282
3283    /// Create a secret vector by generating each byte with a fallible
3284    /// generator.
3285    ///
3286    /// If `make_byte` returns an error, any bytes generated before the error
3287    /// are cleared before the error is returned. This method reports both
3288    /// allocation failure through `SecretGenerateError::Build` and generator
3289    /// failure through `SecretGenerateError::Generate`. It does not enforce an
3290    /// application maximum; use [`SecretVec::try_from_fn_bounded`] when needed.
3291    #[inline]
3292    pub fn try_from_fn<E>(
3293        len: usize,
3294        mut make_byte: impl FnMut(usize) -> Result<u8, E>,
3295    ) -> Result<Self, SecretGenerateError<E>> {
3296        let mut secret = Self::try_with_capacity(len).map_err(SecretGenerateError::Build)?;
3297        let mut index = 0;
3298        while index < len {
3299            let byte = make_byte(index).map_err(SecretGenerateError::Generate)?;
3300            secret.inner.push(byte);
3301            index += 1;
3302        }
3303        Ok(secret)
3304    }
3305
3306    /// Create a secret vector with a caller-enforced public length ceiling.
3307    ///
3308    /// Length validation happens before allocation and before the generator is
3309    /// called. Allocation and generator failures remain distinguishable.
3310    #[inline]
3311    pub fn try_from_fn_bounded<E>(
3312        len: usize,
3313        maximum: usize,
3314        make_byte: impl FnMut(usize) -> Result<u8, E>,
3315    ) -> Result<Self, SecretGenerateError<E>> {
3316        if len > maximum {
3317            return Err(SecretGenerateError::Build(SecretAllocationError::TooLong {
3318                maximum,
3319                actual: len,
3320            }));
3321        }
3322        Self::try_from_fn(len, make_byte)
3323    }
3324
3325    /// Number of bytes currently held.
3326    #[must_use]
3327    #[inline]
3328    pub fn len(&self) -> usize {
3329        self.inner.len()
3330    }
3331
3332    /// Returns true when no bytes are held.
3333    #[must_use]
3334    #[inline]
3335    pub fn is_empty(&self) -> bool {
3336        self.inner.is_empty()
3337    }
3338
3339    /// Current allocation capacity in bytes.
3340    #[must_use]
3341    #[inline]
3342    pub fn capacity(&self) -> usize {
3343        self.inner.capacity()
3344    }
3345
3346    /// Run a closure with read-only access to the secret bytes.
3347    #[inline]
3348    pub fn with_secret<R>(&self, inspect: impl FnOnce(&[u8]) -> R) -> R {
3349        inspect(self.inner.as_slice())
3350    }
3351
3352    /// Run a closure with mutable access to the secret bytes.
3353    #[inline]
3354    pub fn with_secret_mut<R>(&mut self, edit: impl FnOnce(&mut [u8]) -> R) -> R {
3355        edit(self.inner.as_mut_slice())
3356    }
3357
3358    /// Append bytes to the secret vector.
3359    ///
3360    /// If capacity must grow, the previous allocation is wiped before it is
3361    /// dropped. Prefer constructing with enough capacity in callers that append
3362    /// repeatedly.
3363    #[inline]
3364    pub fn extend_from_slice(&mut self, bytes: &[u8]) {
3365        self.grow_for(bytes.len());
3366        self.inner.extend_from_slice(bytes);
3367    }
3368
3369    /// Replace all bytes with a new slice.
3370    ///
3371    /// If capacity must grow, the old allocation is wiped before it is dropped
3372    /// and the old secret bytes are not copied into the replacement allocation.
3373    #[inline]
3374    pub fn replace_from_slice(&mut self, bytes: &[u8]) {
3375        if bytes.len() > self.inner.capacity() {
3376            let new_capacity = next_secret_capacity(self.inner.capacity(), bytes.len());
3377            let mut replacement = Vec::with_capacity(new_capacity);
3378            replacement.extend_from_slice(bytes);
3379            self.clear_secret();
3380            self.inner = replacement;
3381            return;
3382        }
3383
3384        self.clear_secret();
3385        self.inner.extend_from_slice(bytes);
3386    }
3387
3388    /// Replace all bytes by taking ownership of an existing vector.
3389    ///
3390    /// The old allocation is cleared before the provided vector becomes the
3391    /// secret storage. The provided vector is not copied; its full capacity will
3392    /// be volatile-cleared when this `SecretVec` is later cleared or dropped.
3393    #[inline]
3394    pub fn replace_from_vec(&mut self, bytes: Vec<u8>) {
3395        self.clear_secret();
3396        self.inner = bytes;
3397    }
3398
3399    /// Replace all bytes with generated bytes.
3400    ///
3401    /// The new bytes are generated into a fresh clear-on-drop allocation before
3402    /// the old value is cleared and replaced. If `make_byte` panics, the old
3403    /// value remains unchanged and partial generated bytes are cleared during
3404    /// unwinding.
3405    #[inline]
3406    pub fn replace_from_fn(&mut self, len: usize, make_byte: impl FnMut(usize) -> u8) {
3407        let mut replacement = Self::from_fn(len, make_byte);
3408        self.clear_secret();
3409        core::mem::swap(&mut self.inner, &mut replacement.inner);
3410    }
3411
3412    /// Replace all bytes with generated bytes from a fallible generator.
3413    ///
3414    /// The new bytes are generated into a fresh clear-on-drop allocation before
3415    /// the old value is cleared and replaced. If `make_byte` returns an error,
3416    /// the old value remains unchanged and partial generated bytes are cleared
3417    /// before the error is returned.
3418    #[inline]
3419    pub fn try_replace_from_fn<E>(
3420        &mut self,
3421        len: usize,
3422        make_byte: impl FnMut(usize) -> Result<u8, E>,
3423    ) -> Result<(), SecretGenerateError<E>> {
3424        let mut replacement = Self::try_from_fn(len, make_byte)?;
3425        self.clear_secret();
3426        core::mem::swap(&mut self.inner, &mut replacement.inner);
3427        Ok(())
3428    }
3429
3430    /// Clear this value immediately with volatile writes.
3431    #[inline(never)]
3432    pub fn clear_secret(&mut self) {
3433        sanitize_vec_capacity(&mut self.inner);
3434    }
3435
3436    /// Clear this value immediately with an explicit three-pass volatile
3437    /// pattern over the full allocation capacity.
3438    ///
3439    /// Available with the `multi-pass-clear` feature. This is intended for
3440    /// policy or audit compatibility; for volatile RAM, the default
3441    /// [`SecretVec::clear_secret`] remains the normal security boundary.
3442    #[cfg(feature = "multi-pass-clear")]
3443    #[inline(never)]
3444    pub fn clear_secret_multi_pass(&mut self) {
3445        sanitize_vec_capacity_multi_pass(&mut self.inner);
3446    }
3447
3448    /// Clear this value immediately with volatile writes, then flush the cache
3449    /// lines covering the heap allocation.
3450    #[cfg(feature = "cache-flush")]
3451    #[inline(never)]
3452    pub fn clear_secret_and_flush(
3453        &mut self,
3454    ) -> Result<crate::cache_flush::CacheFlushReport, crate::cache_flush::CacheFlushError> {
3455        crate::cache_flush::cache_flush_sanitize_vec(&mut self.inner)
3456    }
3457
3458    /// Compare against a byte slice without early exit for equal-length inputs.
3459    ///
3460    /// Length mismatch returns immediately because the provided slice length is
3461    /// treated as public metadata.
3462    ///
3463    /// The portable fallback is intended to avoid data-dependent early exit, but
3464    /// it is not a formal hardware-level constant-time guarantee. On x86_64,
3465    /// enable `asm-compare` for a stronger compiler boundary. Use a dedicated
3466    /// constant-time comparison crate if your protocol requires externally
3467    /// audited timing guarantees.
3468    #[must_use]
3469    #[inline]
3470    pub fn constant_time_eq(&self, other: &[u8]) -> bool {
3471        constant_time_eq_slices(self.inner.as_slice(), other)
3472    }
3473
3474    /// Consume the wrapper after first clearing the wrapped bytes.
3475    #[inline]
3476    pub fn into_cleared(mut self) {
3477        self.clear_secret();
3478    }
3479
3480    /// Convert this byte container into secret UTF-8 text without reallocating.
3481    ///
3482    /// The existing heap allocation is transferred to [`SecretString`] after
3483    /// UTF-8 validation. If validation fails, the full allocation capacity is
3484    /// volatile-cleared before the error is returned.
3485    #[inline]
3486    pub fn try_into_secret_string(self) -> Result<SecretString, core::str::Utf8Error> {
3487        SecretString::from_secret_vec(self)
3488    }
3489
3490    fn grow_for(&mut self, additional: usize) {
3491        let required = self.inner.len().saturating_add(additional);
3492        if required <= self.inner.capacity() {
3493            return;
3494        }
3495
3496        let new_capacity = next_secret_capacity(self.inner.capacity(), required);
3497        let mut replacement = Vec::with_capacity(new_capacity);
3498        replacement.extend_from_slice(self.inner.as_slice());
3499        self.clear_secret();
3500        self.inner = replacement;
3501    }
3502}
3503
3504#[cfg(feature = "alloc")]
3505impl Drop for SecretVec {
3506    #[inline]
3507    fn drop(&mut self) {
3508        self.clear_secret();
3509    }
3510}
3511
3512#[cfg(feature = "alloc")]
3513impl Default for SecretVec {
3514    #[inline]
3515    fn default() -> Self {
3516        Self::empty()
3517    }
3518}
3519
3520#[cfg(feature = "alloc")]
3521impl SecureSanitize for SecretVec {
3522    #[inline]
3523    fn secure_sanitize(&mut self) {
3524        self.clear_secret();
3525    }
3526}
3527
3528#[cfg(feature = "alloc")]
3529impl fmt::Debug for SecretVec {
3530    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3531        formatter
3532            .debug_struct("SecretVec")
3533            .field("len", &self.inner.len())
3534            .field("contents", &"<redacted>")
3535            .finish()
3536    }
3537}
3538
3539#[cfg(feature = "alloc")]
3540impl ct::ConstantTimeEq for SecretVec {
3541    #[inline]
3542    fn ct_eq(&self, other: &Self) -> ct::Choice {
3543        ct::eq_public_len(self.inner.as_slice(), other.inner.as_slice())
3544    }
3545}
3546
3547#[cfg(feature = "alloc")]
3548impl ct::ConstantTimeEq<[u8]> for SecretVec {
3549    #[inline]
3550    fn ct_eq(&self, other: &[u8]) -> ct::Choice {
3551        ct::eq_public_len(self.inner.as_slice(), other)
3552    }
3553}
3554
3555/// Error returned when a dynamic secret exceeds its declared public limit.
3556#[cfg(feature = "alloc")]
3557#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3558pub struct SecretVecLimitError {
3559    /// Maximum accepted secret length.
3560    pub maximum: usize,
3561    /// Length that was rejected.
3562    pub actual: usize,
3563}
3564
3565#[cfg(feature = "alloc")]
3566impl fmt::Display for SecretVecLimitError {
3567    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3568        write!(
3569            formatter,
3570            "secret length exceeds limit: maximum {} bytes, got {} bytes",
3571            self.maximum, self.actual
3572        )
3573    }
3574}
3575
3576#[cfg(feature = "std")]
3577impl std::error::Error for SecretVecLimitError {}
3578
3579/// Heap-allocated secret bytes constrained to a public maximum length.
3580///
3581/// This additive wrapper is intended for protocol and configuration trust
3582/// boundaries where unbounded dynamic secret allocation is unacceptable. With
3583/// the `serde` feature, every deserialization input form rejects more than
3584/// `MAX` bytes. Rejected owned buffers and partially decoded values are cleared
3585/// before they are released.
3586#[cfg(feature = "alloc")]
3587pub struct BoundedSecretVec<const MAX: usize> {
3588    pub(crate) inner: SecretVec,
3589}
3590
3591#[cfg(feature = "alloc")]
3592impl<const MAX: usize> BoundedSecretVec<MAX> {
3593    /// Create an empty bounded secret.
3594    #[must_use]
3595    #[inline]
3596    pub const fn empty() -> Self {
3597        Self {
3598            inner: SecretVec::empty(),
3599        }
3600    }
3601
3602    /// Copy a slice into bounded secret storage.
3603    #[inline]
3604    pub fn from_slice(bytes: &[u8]) -> Result<Self, SecretVecLimitError> {
3605        Self::validate_len(bytes.len())?;
3606        Ok(Self {
3607            inner: SecretVec::from_slice(bytes),
3608        })
3609    }
3610
3611    /// Take ownership of a vector after validating its length.
3612    ///
3613    /// An oversized input allocation is volatile-cleared before the error is
3614    /// returned.
3615    #[inline]
3616    pub fn from_vec(mut bytes: Vec<u8>) -> Result<Self, SecretVecLimitError> {
3617        if let Err(error) = Self::validate_len(bytes.len()) {
3618            sanitize_vec_capacity(&mut bytes);
3619            return Err(error);
3620        }
3621        Ok(Self {
3622            inner: SecretVec::from_vec(bytes),
3623        })
3624    }
3625
3626    /// Convert an existing secret vector after validating its length.
3627    ///
3628    /// An oversized input is cleared before the error is returned.
3629    #[inline]
3630    pub fn from_secret_vec(mut secret: SecretVec) -> Result<Self, SecretVecLimitError> {
3631        if let Err(error) = Self::validate_len(secret.len()) {
3632            secret.clear_secret();
3633            return Err(error);
3634        }
3635        Ok(Self { inner: secret })
3636    }
3637
3638    /// Maximum accepted length.
3639    #[must_use]
3640    #[inline]
3641    pub const fn max_len() -> usize {
3642        MAX
3643    }
3644
3645    /// Number of initialized secret bytes.
3646    #[must_use]
3647    #[inline]
3648    pub fn len(&self) -> usize {
3649        self.inner.len()
3650    }
3651
3652    /// Returns true when no bytes are held.
3653    #[must_use]
3654    #[inline]
3655    pub fn is_empty(&self) -> bool {
3656        self.inner.is_empty()
3657    }
3658
3659    /// Run a closure with read-only access to the secret bytes.
3660    #[inline]
3661    pub fn with_secret<R>(&self, inspect: impl FnOnce(&[u8]) -> R) -> R {
3662        self.inner.with_secret(inspect)
3663    }
3664
3665    /// Run a closure with mutable access to the initialized secret bytes.
3666    #[inline]
3667    pub fn with_secret_mut<R>(&mut self, edit: impl FnOnce(&mut [u8]) -> R) -> R {
3668        self.inner.with_secret_mut(edit)
3669    }
3670
3671    /// Append bytes without permitting the configured limit to be exceeded.
3672    #[inline]
3673    pub fn extend_from_slice(&mut self, bytes: &[u8]) -> Result<(), SecretVecLimitError> {
3674        let actual = self.len().saturating_add(bytes.len());
3675        Self::validate_len(actual)?;
3676        self.inner.extend_from_slice(bytes);
3677        Ok(())
3678    }
3679
3680    /// Replace the current value after validating the replacement length.
3681    #[inline]
3682    pub fn replace_from_slice(&mut self, bytes: &[u8]) -> Result<(), SecretVecLimitError> {
3683        Self::validate_len(bytes.len())?;
3684        self.inner.replace_from_slice(bytes);
3685        Ok(())
3686    }
3687
3688    /// Clear this value immediately with volatile writes.
3689    #[inline(never)]
3690    pub fn clear_secret(&mut self) {
3691        self.inner.clear_secret();
3692    }
3693
3694    /// Return the bounded value as an ordinary clear-on-drop secret vector.
3695    #[must_use]
3696    #[inline]
3697    pub fn into_secret_vec(self) -> SecretVec {
3698        self.inner
3699    }
3700
3701    #[inline]
3702    fn validate_len(actual: usize) -> Result<(), SecretVecLimitError> {
3703        if actual > MAX {
3704            Err(SecretVecLimitError {
3705                maximum: MAX,
3706                actual,
3707            })
3708        } else {
3709            Ok(())
3710        }
3711    }
3712}
3713
3714#[cfg(feature = "alloc")]
3715impl<const MAX: usize> Default for BoundedSecretVec<MAX> {
3716    #[inline]
3717    fn default() -> Self {
3718        Self::empty()
3719    }
3720}
3721
3722#[cfg(feature = "alloc")]
3723impl<const MAX: usize> From<BoundedSecretVec<MAX>> for SecretVec {
3724    #[inline]
3725    fn from(secret: BoundedSecretVec<MAX>) -> Self {
3726        secret.into_secret_vec()
3727    }
3728}
3729
3730#[cfg(feature = "alloc")]
3731impl<const MAX: usize> SecureSanitize for BoundedSecretVec<MAX> {
3732    #[inline]
3733    fn secure_sanitize(&mut self) {
3734        self.clear_secret();
3735    }
3736}
3737
3738#[cfg(feature = "alloc")]
3739impl<const MAX: usize> fmt::Debug for BoundedSecretVec<MAX> {
3740    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3741        formatter
3742            .debug_struct("BoundedSecretVec")
3743            .field("len", &self.len())
3744            .field("max_len", &MAX)
3745            .field("contents", &"<redacted>")
3746            .finish()
3747    }
3748}
3749
3750#[cfg(feature = "alloc")]
3751impl<const MAX: usize> ct::ConstantTimeEq for BoundedSecretVec<MAX> {
3752    #[inline]
3753    fn ct_eq(&self, other: &Self) -> ct::Choice {
3754        self.inner.ct_eq(&other.inner)
3755    }
3756}
3757
3758/// Heap-allocated secret UTF-8 text with clear-on-drop behavior.
3759///
3760/// This type is available with the `alloc` feature. Use it for bearer tokens,
3761/// passphrases, and textual secrets that must cross APIs as UTF-8. Clearing
3762/// uses volatile writes over the full allocation capacity before the internal
3763/// byte vector length is set to zero.
3764#[cfg(feature = "alloc")]
3765pub struct SecretString {
3766    pub(crate) inner: Vec<u8>,
3767}
3768
3769/// Default maximum accepted by serde deserialization into [`SecretString`].
3770///
3771/// The limit is measured in UTF-8 bytes, not Unicode scalar values. Use
3772/// [`BoundedSecretString<MAX>`] when a protocol requires a different maximum.
3773#[cfg(feature = "alloc")]
3774pub const DEFAULT_SECRET_STRING_SERDE_MAX_LEN: usize = 1024 * 1024;
3775
3776#[cfg(feature = "alloc")]
3777impl SecretString {
3778    /// Wrap a string using volatile clearing on drop.
3779    #[must_use]
3780    #[inline]
3781    pub fn new(inner: String) -> Self {
3782        Self {
3783            inner: inner.into_bytes(),
3784        }
3785    }
3786
3787    /// Wrap an existing string using volatile clearing on drop.
3788    ///
3789    /// This is an explicit ownership-taking alias for [`SecretString::new`].
3790    /// The string allocation is not copied; its full capacity will be
3791    /// volatile-cleared when this `SecretString` is cleared or dropped.
3792    #[must_use]
3793    #[inline]
3794    pub fn from_string(text: String) -> Self {
3795        Self::new(text)
3796    }
3797
3798    /// Convert secret bytes into UTF-8 text without reallocating.
3799    ///
3800    /// UTF-8 is validated before the byte allocation is transferred. Invalid
3801    /// input is volatile-cleared before [`core::str::Utf8Error`] is returned; the rejected
3802    /// secret bytes are not returned to the caller.
3803    #[inline]
3804    pub fn from_secret_vec(mut secret: SecretVec) -> Result<Self, core::str::Utf8Error> {
3805        if let Err(error) = core::str::from_utf8(secret.inner.as_slice()) {
3806            secret.clear_secret();
3807            return Err(error);
3808        }
3809
3810        Ok(Self {
3811            inner: core::mem::take(&mut secret.inner),
3812        })
3813    }
3814
3815    /// Create an empty secret string.
3816    #[must_use]
3817    #[inline]
3818    pub const fn empty() -> Self {
3819        Self { inner: Vec::new() }
3820    }
3821
3822    /// Create an empty secret string with at least the requested byte capacity.
3823    ///
3824    /// `capacity` must be trusted and bounded. Allocation failure may abort;
3825    /// use [`SecretString::try_with_capacity`] when it must be reported.
3826    #[must_use]
3827    #[inline]
3828    pub fn with_capacity(capacity: usize) -> Self {
3829        Self {
3830            inner: Vec::with_capacity(capacity),
3831        }
3832    }
3833
3834    /// Create an empty secret string using fallible byte allocation.
3835    ///
3836    /// Unlike [`SecretString::with_capacity`], this reports capacity overflow
3837    /// or allocation failure instead of panicking or invoking the allocation
3838    /// error handler.
3839    #[inline]
3840    pub fn try_with_capacity(capacity: usize) -> Result<Self, SecretAllocationError> {
3841        let mut inner = Vec::new();
3842        inner
3843            .try_reserve_exact(capacity)
3844            .map_err(SecretAllocationError::Allocation)?;
3845        Ok(Self { inner })
3846    }
3847
3848    /// Create a secret string by copying from a string slice.
3849    ///
3850    /// The public byte length must be trusted and bounded. Use
3851    /// [`SecretString::try_from_secret_str_bounded`] at untrusted boundaries.
3852    #[must_use]
3853    #[inline]
3854    pub fn from_secret_str(text: &str) -> Self {
3855        Self {
3856            inner: Vec::from(text.as_bytes()),
3857        }
3858    }
3859
3860    /// Copy UTF-8 text after enforcing a public byte-length ceiling and using
3861    /// fallible allocation.
3862    ///
3863    /// Length validation happens before allocation. The borrowed source is not
3864    /// cleared by this method.
3865    #[inline]
3866    pub fn try_from_secret_str_bounded(
3867        text: &str,
3868        maximum_bytes: usize,
3869    ) -> Result<Self, SecretAllocationError> {
3870        if text.len() > maximum_bytes {
3871            return Err(SecretAllocationError::TooLong {
3872                maximum: maximum_bytes,
3873                actual: text.len(),
3874            });
3875        }
3876
3877        let mut secret = Self::try_with_capacity(text.len())?;
3878        secret.inner.extend_from_slice(text.as_bytes());
3879        Ok(secret)
3880    }
3881
3882    /// Create a secret string by generating UTF-8 scalar values directly.
3883    ///
3884    /// `char_count` is the number of generated `char` values, not the final
3885    /// byte length. Each generated character is encoded into the secret heap
3886    /// allocation and the small stack encoding buffer is immediately cleared.
3887    /// `char_count` must be trusted and bounded; capacity overflow panics and
3888    /// allocation failure may abort.
3889    #[must_use]
3890    #[inline]
3891    pub fn from_chars(char_count: usize, mut make_char: impl FnMut(usize) -> char) -> Self {
3892        let capacity = char_count
3893            .checked_mul(MAX_UTF8_CHAR_BYTES)
3894            .expect("secret UTF-8 capacity calculation overflowed");
3895        let mut secret = Self::with_capacity(capacity);
3896        let mut index = 0;
3897        while index < char_count {
3898            secret.push_secret_char(make_char(index));
3899            index += 1;
3900        }
3901        secret
3902    }
3903
3904    /// Create a secret string by fallibly generating UTF-8 scalar values
3905    /// directly.
3906    ///
3907    /// If `make_char` returns an error, any text generated before the error is
3908    /// cleared before the error is returned. This method reports both build
3909    /// failure through `SecretGenerateError::Build` and generator failure
3910    /// through `SecretGenerateError::Generate`. It does not enforce an
3911    /// application maximum; use [`SecretString::try_from_chars_bounded`] when
3912    /// needed.
3913    #[inline]
3914    pub fn try_from_chars<E>(
3915        char_count: usize,
3916        mut make_char: impl FnMut(usize) -> Result<char, E>,
3917    ) -> Result<Self, SecretGenerateError<E>> {
3918        let capacity =
3919            char_count
3920                .checked_mul(MAX_UTF8_CHAR_BYTES)
3921                .ok_or(SecretGenerateError::Build(
3922                    SecretAllocationError::CapacityOverflow,
3923                ))?;
3924        let mut secret = Self::try_with_capacity(capacity).map_err(SecretGenerateError::Build)?;
3925        let mut index = 0;
3926        while index < char_count {
3927            let character = make_char(index).map_err(SecretGenerateError::Generate)?;
3928            secret.push_secret_char(character);
3929            index += 1;
3930        }
3931        Ok(secret)
3932    }
3933
3934    /// Create secret UTF-8 text with a caller-enforced byte-capacity ceiling.
3935    ///
3936    /// The worst-case UTF-8 byte capacity is calculated with checked arithmetic
3937    /// and compared with `maximum_bytes` before allocation or generator
3938    /// execution.
3939    #[inline]
3940    pub fn try_from_chars_bounded<E>(
3941        char_count: usize,
3942        maximum_bytes: usize,
3943        make_char: impl FnMut(usize) -> Result<char, E>,
3944    ) -> Result<Self, SecretGenerateError<E>> {
3945        let capacity =
3946            char_count
3947                .checked_mul(MAX_UTF8_CHAR_BYTES)
3948                .ok_or(SecretGenerateError::Build(
3949                    SecretAllocationError::CapacityOverflow,
3950                ))?;
3951        if capacity > maximum_bytes {
3952            return Err(SecretGenerateError::Build(SecretAllocationError::TooLong {
3953                maximum: maximum_bytes,
3954                actual: capacity,
3955            }));
3956        }
3957        Self::try_from_chars(char_count, make_char)
3958    }
3959
3960    /// Number of bytes currently held.
3961    #[must_use]
3962    #[inline]
3963    pub fn len(&self) -> usize {
3964        self.inner.len()
3965    }
3966
3967    /// Returns true when no text is held.
3968    #[must_use]
3969    #[inline]
3970    pub fn is_empty(&self) -> bool {
3971        self.inner.is_empty()
3972    }
3973
3974    /// Current allocation capacity in bytes.
3975    #[must_use]
3976    #[inline]
3977    pub fn capacity(&self) -> usize {
3978        self.inner.capacity()
3979    }
3980
3981    /// Run a closure with read-only access to the secret text.
3982    ///
3983    /// The result is fallible because the text is stored internally as bytes to
3984    /// keep clearing safe without `String::as_mut_vec`.
3985    #[inline]
3986    pub fn try_with_secret<R>(
3987        &self,
3988        inspect: impl FnOnce(&str) -> R,
3989    ) -> Result<R, core::str::Utf8Error> {
3990        core::str::from_utf8(self.inner.as_slice()).map(inspect)
3991    }
3992
3993    /// Run a closure with mutable access to the secret text.
3994    ///
3995    /// The result is fallible because the text is stored internally as bytes to
3996    /// keep clearing safe without `String::as_mut_vec`. The closure receives
3997    /// `&mut str`, so safe Rust cannot invalidate UTF-8.
3998    #[inline]
3999    pub fn try_with_secret_mut<R>(
4000        &mut self,
4001        edit: impl FnOnce(&mut str) -> R,
4002    ) -> Result<R, core::str::Utf8Error> {
4003        core::str::from_utf8_mut(self.inner.as_mut_slice()).map(edit)
4004    }
4005
4006    /// Run a closure with read-only access to the secret bytes.
4007    #[inline]
4008    pub fn with_secret_bytes<R>(&self, inspect: impl FnOnce(&[u8]) -> R) -> R {
4009        inspect(self.inner.as_slice())
4010    }
4011
4012    /// Append text to the secret string.
4013    ///
4014    /// If capacity must grow, the previous allocation is wiped before it is
4015    /// dropped. Prefer constructing with enough capacity in callers that append
4016    /// repeatedly.
4017    #[inline]
4018    pub fn push_str(&mut self, text: &str) {
4019        self.grow_for(text.len());
4020        self.inner.extend_from_slice(text.as_bytes());
4021    }
4022
4023    /// Replace all text with a new string slice.
4024    ///
4025    /// If capacity must grow, the old allocation is wiped before it is dropped
4026    /// and the old secret bytes are not copied into the replacement allocation.
4027    #[inline]
4028    pub fn replace_from_secret_str(&mut self, text: &str) {
4029        if text.len() > self.inner.capacity() {
4030            let new_capacity = next_secret_capacity(self.inner.capacity(), text.len());
4031            let mut replacement = Vec::with_capacity(new_capacity);
4032            replacement.extend_from_slice(text.as_bytes());
4033            self.clear_secret();
4034            self.inner = replacement;
4035            return;
4036        }
4037
4038        self.clear_secret();
4039        self.inner.extend_from_slice(text.as_bytes());
4040    }
4041
4042    /// Replace all text by taking ownership of an existing string.
4043    ///
4044    /// The old allocation is cleared before the provided string allocation
4045    /// becomes the secret storage. The provided string is not copied; its full
4046    /// capacity will be volatile-cleared when this `SecretString` is later
4047    /// cleared or dropped.
4048    #[inline]
4049    pub fn replace_from_string(&mut self, text: String) {
4050        let replacement = text.into_bytes();
4051        self.clear_secret();
4052        self.inner = replacement;
4053    }
4054
4055    /// Replace all text with generated UTF-8 scalar values.
4056    ///
4057    /// The replacement text is generated into a fresh clear-on-drop allocation
4058    /// before the old value is cleared and replaced. If `make_char` panics, the
4059    /// old value remains unchanged and partial generated text is cleared during
4060    /// unwinding.
4061    #[inline]
4062    pub fn replace_from_chars(&mut self, char_count: usize, make_char: impl FnMut(usize) -> char) {
4063        let mut replacement = Self::from_chars(char_count, make_char);
4064        self.clear_secret();
4065        core::mem::swap(&mut self.inner, &mut replacement.inner);
4066    }
4067
4068    /// Replace all text with fallibly generated UTF-8 scalar values.
4069    ///
4070    /// The replacement text is generated into a fresh clear-on-drop allocation
4071    /// before the old value is cleared and replaced. If `make_char` returns an
4072    /// error, the old value remains unchanged and partial generated text is
4073    /// cleared before the error is returned.
4074    #[inline]
4075    pub fn try_replace_from_chars<E>(
4076        &mut self,
4077        char_count: usize,
4078        make_char: impl FnMut(usize) -> Result<char, E>,
4079    ) -> Result<(), SecretGenerateError<E>> {
4080        let mut replacement = Self::try_from_chars(char_count, make_char)?;
4081        self.clear_secret();
4082        core::mem::swap(&mut self.inner, &mut replacement.inner);
4083        Ok(())
4084    }
4085
4086    /// Clear this value immediately with volatile writes.
4087    #[inline(never)]
4088    pub fn clear_secret(&mut self) {
4089        sanitize_vec_capacity(&mut self.inner);
4090    }
4091
4092    /// Clear this value immediately with an explicit three-pass volatile
4093    /// pattern over the full allocation capacity.
4094    ///
4095    /// Available with the `multi-pass-clear` feature. This is intended for
4096    /// policy or audit compatibility; for volatile RAM, the default
4097    /// [`SecretString::clear_secret`] remains the normal security boundary.
4098    #[cfg(feature = "multi-pass-clear")]
4099    #[inline(never)]
4100    pub fn clear_secret_multi_pass(&mut self) {
4101        sanitize_vec_capacity_multi_pass(&mut self.inner);
4102    }
4103
4104    /// Clear this value immediately with volatile writes, then flush the cache
4105    /// lines covering the heap allocation.
4106    #[cfg(feature = "cache-flush")]
4107    #[inline(never)]
4108    pub fn clear_secret_and_flush(
4109        &mut self,
4110    ) -> Result<crate::cache_flush::CacheFlushReport, crate::cache_flush::CacheFlushError> {
4111        crate::cache_flush::cache_flush_sanitize_vec(&mut self.inner)
4112    }
4113
4114    /// Compare against UTF-8 text without early exit for equal-length inputs.
4115    ///
4116    /// Length mismatch returns immediately because the provided string length
4117    /// is treated as public metadata.
4118    ///
4119    /// The portable fallback is intended to avoid data-dependent early exit, but
4120    /// it is not a formal hardware-level constant-time guarantee. On x86_64,
4121    /// enable `asm-compare` for a stronger compiler boundary. Use a dedicated
4122    /// constant-time comparison crate if your protocol requires externally
4123    /// audited timing guarantees.
4124    #[must_use]
4125    #[inline]
4126    pub fn constant_time_eq(&self, other: &str) -> bool {
4127        constant_time_eq_slices(self.inner.as_slice(), other.as_bytes())
4128    }
4129
4130    /// Consume the wrapper after first clearing the wrapped string.
4131    #[inline]
4132    pub fn into_cleared(mut self) {
4133        self.clear_secret();
4134    }
4135
4136    /// Convert this UTF-8 text into secret bytes without reallocating.
4137    #[must_use]
4138    #[inline]
4139    pub fn into_secret_vec(mut self) -> SecretVec {
4140        SecretVec::from_vec(core::mem::take(&mut self.inner))
4141    }
4142
4143    fn grow_for(&mut self, additional: usize) {
4144        let required = self.inner.len().saturating_add(additional);
4145        if required <= self.inner.capacity() {
4146            return;
4147        }
4148
4149        let new_capacity = next_secret_capacity(self.inner.capacity(), required);
4150        let mut replacement = Vec::with_capacity(new_capacity);
4151        replacement.extend_from_slice(self.inner.as_slice());
4152        self.clear_secret();
4153        self.inner = replacement;
4154    }
4155
4156    fn push_secret_char(&mut self, character: char) {
4157        let mut encoded = [0; 4];
4158        let text = character.encode_utf8(&mut encoded);
4159        self.inner.extend_from_slice(text.as_bytes());
4160        wipe::bytes(&mut encoded);
4161    }
4162}
4163
4164#[cfg(feature = "alloc")]
4165impl Drop for SecretString {
4166    #[inline]
4167    fn drop(&mut self) {
4168        self.clear_secret();
4169    }
4170}
4171
4172#[cfg(feature = "alloc")]
4173impl Default for SecretString {
4174    #[inline]
4175    fn default() -> Self {
4176        Self::empty()
4177    }
4178}
4179
4180#[cfg(feature = "alloc")]
4181impl SecureSanitize for SecretString {
4182    #[inline]
4183    fn secure_sanitize(&mut self) {
4184        self.clear_secret();
4185    }
4186}
4187
4188#[cfg(feature = "alloc")]
4189impl fmt::Debug for SecretString {
4190    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4191        formatter
4192            .debug_struct("SecretString")
4193            .field("len", &self.inner.len())
4194            .field("contents", &"<redacted>")
4195            .finish()
4196    }
4197}
4198
4199#[cfg(feature = "alloc")]
4200impl ct::ConstantTimeEq for SecretString {
4201    #[inline]
4202    fn ct_eq(&self, other: &Self) -> ct::Choice {
4203        ct::eq_public_len(self.inner.as_slice(), other.inner.as_slice())
4204    }
4205}
4206
4207#[cfg(feature = "alloc")]
4208impl ct::ConstantTimeEq<str> for SecretString {
4209    #[inline]
4210    fn ct_eq(&self, other: &str) -> ct::Choice {
4211        ct::eq_public_len(self.inner.as_slice(), other.as_bytes())
4212    }
4213}
4214
4215#[cfg(feature = "alloc")]
4216impl TryFrom<SecretVec> for SecretString {
4217    type Error = core::str::Utf8Error;
4218
4219    #[inline]
4220    fn try_from(secret: SecretVec) -> Result<Self, Self::Error> {
4221        Self::from_secret_vec(secret)
4222    }
4223}
4224
4225#[cfg(feature = "alloc")]
4226impl From<SecretString> for SecretVec {
4227    #[inline]
4228    fn from(secret: SecretString) -> Self {
4229        secret.into_secret_vec()
4230    }
4231}
4232
4233/// Error returned when secret UTF-8 text exceeds its declared public limit.
4234#[cfg(feature = "alloc")]
4235#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4236pub struct SecretStringLimitError {
4237    /// Maximum accepted UTF-8 byte length.
4238    pub maximum: usize,
4239    /// UTF-8 byte length that was rejected.
4240    pub actual: usize,
4241}
4242
4243#[cfg(feature = "alloc")]
4244impl fmt::Display for SecretStringLimitError {
4245    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4246        write!(
4247            formatter,
4248            "secret text length exceeds limit: maximum {} UTF-8 bytes, got {} bytes",
4249            self.maximum, self.actual
4250        )
4251    }
4252}
4253
4254#[cfg(feature = "std")]
4255impl std::error::Error for SecretStringLimitError {}
4256
4257/// Heap-allocated secret UTF-8 text constrained to a public byte limit.
4258///
4259/// The limit is measured after UTF-8 encoding. This type is intended for
4260/// configuration and protocol boundaries where unbounded textual secret
4261/// allocation is unacceptable. Rejected owned strings and secret containers
4262/// are volatile-cleared before the error is returned.
4263#[cfg(feature = "alloc")]
4264pub struct BoundedSecretString<const MAX: usize> {
4265    pub(crate) inner: SecretString,
4266}
4267
4268#[cfg(feature = "alloc")]
4269impl<const MAX: usize> BoundedSecretString<MAX> {
4270    /// Create an empty bounded secret string.
4271    #[must_use]
4272    #[inline]
4273    pub const fn empty() -> Self {
4274        Self {
4275            inner: SecretString::empty(),
4276        }
4277    }
4278
4279    /// Copy UTF-8 text into bounded secret storage.
4280    #[inline]
4281    pub fn from_secret_str(text: &str) -> Result<Self, SecretStringLimitError> {
4282        Self::validate_len(text.len())?;
4283        Ok(Self {
4284            inner: SecretString::from_secret_str(text),
4285        })
4286    }
4287
4288    /// Take ownership of a string after validating its UTF-8 byte length.
4289    ///
4290    /// An oversized input allocation is volatile-cleared before the error is
4291    /// returned.
4292    #[inline]
4293    pub fn from_string(mut text: String) -> Result<Self, SecretStringLimitError> {
4294        if let Err(error) = Self::validate_len(text.len()) {
4295            text.secure_sanitize();
4296            return Err(error);
4297        }
4298        Ok(Self {
4299            inner: SecretString::from_string(text),
4300        })
4301    }
4302
4303    /// Convert an existing secret string after validating its byte length.
4304    ///
4305    /// An oversized input is cleared before the error is returned.
4306    #[inline]
4307    pub fn from_secret_string(mut secret: SecretString) -> Result<Self, SecretStringLimitError> {
4308        if let Err(error) = Self::validate_len(secret.len()) {
4309            secret.clear_secret();
4310            return Err(error);
4311        }
4312        Ok(Self { inner: secret })
4313    }
4314
4315    /// Convert secret bytes without reallocating after UTF-8 and length checks.
4316    ///
4317    /// Invalid UTF-8 is cleared by [`SecretString::from_secret_vec`]. Valid but
4318    /// oversized text is cleared before the limit error is returned.
4319    #[inline]
4320    pub fn from_secret_vec(secret: SecretVec) -> Result<Self, BoundedSecretStringError> {
4321        let text = SecretString::from_secret_vec(secret).map_err(BoundedSecretStringError::Utf8)?;
4322        Self::from_secret_string(text).map_err(BoundedSecretStringError::Limit)
4323    }
4324
4325    /// Maximum accepted UTF-8 byte length.
4326    #[must_use]
4327    #[inline]
4328    pub const fn max_len() -> usize {
4329        MAX
4330    }
4331
4332    /// Number of initialized UTF-8 bytes.
4333    #[must_use]
4334    #[inline]
4335    pub fn len(&self) -> usize {
4336        self.inner.len()
4337    }
4338
4339    /// Returns true when no text is held.
4340    #[must_use]
4341    #[inline]
4342    pub fn is_empty(&self) -> bool {
4343        self.inner.is_empty()
4344    }
4345
4346    /// Current allocation capacity in bytes.
4347    #[must_use]
4348    #[inline]
4349    pub fn capacity(&self) -> usize {
4350        self.inner.capacity()
4351    }
4352
4353    /// Run a closure with read-only access to the secret text.
4354    #[inline]
4355    pub fn try_with_secret<R>(
4356        &self,
4357        inspect: impl FnOnce(&str) -> R,
4358    ) -> Result<R, core::str::Utf8Error> {
4359        self.inner.try_with_secret(inspect)
4360    }
4361
4362    /// Run a closure with mutable access to the secret text.
4363    #[inline]
4364    pub fn try_with_secret_mut<R>(
4365        &mut self,
4366        edit: impl FnOnce(&mut str) -> R,
4367    ) -> Result<R, core::str::Utf8Error> {
4368        self.inner.try_with_secret_mut(edit)
4369    }
4370
4371    /// Append text without permitting the configured byte limit to be exceeded.
4372    #[inline]
4373    pub fn push_str(&mut self, text: &str) -> Result<(), SecretStringLimitError> {
4374        Self::validate_len(self.len().saturating_add(text.len()))?;
4375        self.inner.push_str(text);
4376        Ok(())
4377    }
4378
4379    /// Replace the current value after validating the replacement byte length.
4380    #[inline]
4381    pub fn replace_from_secret_str(&mut self, text: &str) -> Result<(), SecretStringLimitError> {
4382        Self::validate_len(text.len())?;
4383        self.inner.replace_from_secret_str(text);
4384        Ok(())
4385    }
4386
4387    /// Replace the current value by taking ownership of a bounded string.
4388    ///
4389    /// Oversized input is cleared before the error is returned. On success the
4390    /// provided allocation becomes the secret storage without copying.
4391    #[inline]
4392    pub fn replace_from_string(&mut self, text: String) -> Result<(), SecretStringLimitError> {
4393        let mut replacement = Self::from_string(text)?;
4394        self.clear_secret();
4395        core::mem::swap(&mut self.inner, &mut replacement.inner);
4396        Ok(())
4397    }
4398
4399    /// Clear this value immediately with volatile writes.
4400    #[inline(never)]
4401    pub fn clear_secret(&mut self) {
4402        self.inner.clear_secret();
4403    }
4404
4405    /// Compare against UTF-8 text without early exit for equal-length inputs.
4406    #[must_use]
4407    #[inline]
4408    pub fn constant_time_eq(&self, other: &str) -> bool {
4409        self.inner.constant_time_eq(other)
4410    }
4411
4412    /// Return the bounded value as an ordinary clear-on-drop secret string.
4413    #[must_use]
4414    #[inline]
4415    pub fn into_secret_string(self) -> SecretString {
4416        self.inner
4417    }
4418
4419    /// Return the bounded value as secret bytes without reallocating.
4420    #[must_use]
4421    #[inline]
4422    pub fn into_secret_vec(self) -> SecretVec {
4423        self.inner.into_secret_vec()
4424    }
4425
4426    #[inline]
4427    fn validate_len(actual: usize) -> Result<(), SecretStringLimitError> {
4428        if actual > MAX {
4429            Err(SecretStringLimitError {
4430                maximum: MAX,
4431                actual,
4432            })
4433        } else {
4434            Ok(())
4435        }
4436    }
4437}
4438
4439/// Error returned while converting bounded secret bytes into UTF-8 text.
4440#[cfg(feature = "alloc")]
4441#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4442pub enum BoundedSecretStringError {
4443    /// The secret bytes were not valid UTF-8.
4444    Utf8(core::str::Utf8Error),
4445    /// The valid UTF-8 text exceeded the declared public limit.
4446    Limit(SecretStringLimitError),
4447}
4448
4449#[cfg(feature = "alloc")]
4450impl fmt::Display for BoundedSecretStringError {
4451    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4452        match self {
4453            Self::Utf8(error) => error.fmt(formatter),
4454            Self::Limit(error) => error.fmt(formatter),
4455        }
4456    }
4457}
4458
4459#[cfg(feature = "std")]
4460impl std::error::Error for BoundedSecretStringError {
4461    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
4462        match self {
4463            Self::Utf8(error) => Some(error),
4464            Self::Limit(error) => Some(error),
4465        }
4466    }
4467}
4468
4469#[cfg(feature = "alloc")]
4470impl<const MAX: usize> Default for BoundedSecretString<MAX> {
4471    #[inline]
4472    fn default() -> Self {
4473        Self::empty()
4474    }
4475}
4476
4477#[cfg(feature = "alloc")]
4478impl<const MAX: usize> SecureSanitize for BoundedSecretString<MAX> {
4479    #[inline]
4480    fn secure_sanitize(&mut self) {
4481        self.clear_secret();
4482    }
4483}
4484
4485#[cfg(feature = "alloc")]
4486impl<const MAX: usize> fmt::Debug for BoundedSecretString<MAX> {
4487    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4488        formatter
4489            .debug_struct("BoundedSecretString")
4490            .field("len", &self.len())
4491            .field("max_len", &MAX)
4492            .field("contents", &"<redacted>")
4493            .finish()
4494    }
4495}
4496
4497#[cfg(feature = "alloc")]
4498impl<const MAX: usize> ct::ConstantTimeEq for BoundedSecretString<MAX> {
4499    #[inline]
4500    fn ct_eq(&self, other: &Self) -> ct::Choice {
4501        self.inner.ct_eq(&other.inner)
4502    }
4503}
4504
4505#[cfg(feature = "alloc")]
4506impl<const MAX: usize> ct::ConstantTimeEq<str> for BoundedSecretString<MAX> {
4507    #[inline]
4508    fn ct_eq(&self, other: &str) -> ct::Choice {
4509        self.inner.ct_eq(other)
4510    }
4511}
4512
4513#[cfg(feature = "alloc")]
4514impl<const MAX: usize> From<BoundedSecretString<MAX>> for SecretString {
4515    #[inline]
4516    fn from(secret: BoundedSecretString<MAX>) -> Self {
4517        secret.into_secret_string()
4518    }
4519}
4520
4521#[cfg(feature = "alloc")]
4522impl<const MAX: usize> TryFrom<SecretString> for BoundedSecretString<MAX> {
4523    type Error = SecretStringLimitError;
4524
4525    #[inline]
4526    fn try_from(secret: SecretString) -> Result<Self, Self::Error> {
4527        Self::from_secret_string(secret)
4528    }
4529}
4530
4531#[cfg(feature = "alloc")]
4532impl<const MAX: usize> TryFrom<SecretVec> for BoundedSecretString<MAX> {
4533    type Error = BoundedSecretStringError;
4534
4535    #[inline]
4536    fn try_from(secret: SecretVec) -> Result<Self, Self::Error> {
4537        Self::from_secret_vec(secret)
4538    }
4539}
4540
4541/// Clear-on-drop wrapper for non-byte secret types.
4542///
4543/// This is useful for structs that implement [`SecureSanitize`] by clearing
4544/// their sensitive fields. Like [`SecretBytes`], this wrapper intentionally does
4545/// not implement `Clone`, `Copy`, or secret-printing `Debug`.
4546///
4547/// # Clearing Strength
4548///
4549/// When `T = [u8; N]`, this wrapper clears through [`SecureSanitize`] for byte
4550/// arrays, which uses the same volatile byte clearing primitive as the rest of
4551/// the crate. For fixed-size byte secrets, still prefer [`SecretBytes<N>`],
4552/// which avoids implementing `Clone`, `Copy`, `Deref`, `AsRef<[u8]>`, or
4553/// secret-printing `Debug`.
4554///
4555/// Scalar values such as `u64`, arrays of sanitizable values, `Option<T>`, and
4556/// `Result<T, E>` implement [`SecureSanitize`] directly. With `alloc`, `Box<T>`,
4557/// `Vec<T>`, and `String` are supported as well. Construction, drop clearing,
4558/// and [`Secret::into_cleared`] remain available for all of them.
4559///
4560/// For byte vectors, prefer [`SecretVec`] over `Secret<Vec<u8>>`. `Vec<T>` is
4561/// supported for generic sanitizable containers and clears the raw allocation
4562/// capacity after dropping live elements, but generic exposure is intentionally
4563/// unavailable because `Vec<T>` does not implement the storage-stability
4564/// contracts. [`SecretVec`] provides reviewed scoped access and rotation that
4565/// clears old allocations before release.
4566pub struct Secret<T: SecureSanitize> {
4567    inner: T,
4568}
4569
4570impl<T: SecureSanitize> Secret<T> {
4571    /// Wrap a sanitizable value.
4572    #[must_use]
4573    #[inline]
4574    pub const fn new(inner: T) -> Self {
4575        Self { inner }
4576    }
4577
4578    /// Consume the wrapper after first clearing the wrapped value.
4579    #[inline]
4580    pub fn into_cleared(mut self) {
4581        self.inner.secure_sanitize();
4582    }
4583}
4584
4585impl<T: StableSharedSecretStorage> Secret<T> {
4586    /// Run a closure with shared access to storage certified as shared-stable.
4587    ///
4588    /// This method is unavailable for types such as `Vec<T>`, `String`, and
4589    /// interior-mutable reallocating containers. Use a dedicated secret
4590    /// container or implement [`StableSharedSecretStorage`] after reviewing
4591    /// the type's complete safe shared API.
4592    ///
4593    /// The returned value cannot borrow the wrapped secret:
4594    ///
4595    /// ```compile_fail
4596    /// use sanitization::Secret;
4597    ///
4598    /// let secret = Secret::new([1_u8, 2, 3, 4]);
4599    /// let escaped = secret.with_secret(|bytes| bytes);
4600    /// let _ = escaped;
4601    /// ```
4602    #[inline]
4603    pub fn with_secret<R>(&self, inspect: impl FnOnce(&T) -> R) -> R {
4604        inspect(&self.inner)
4605    }
4606}
4607
4608impl<T: StableMutableSecretStorage> Secret<T> {
4609    /// Run a closure with mutable access to storage certified as mutable-stable.
4610    ///
4611    /// This method is unavailable for generic growable or reallocating
4612    /// containers. Prefer [`SecretVec`], [`SecretString`], their bounded
4613    /// variants, or a reviewed fixed-storage type carrying
4614    /// [`StableMutableSecretStorage`].
4615    #[inline]
4616    pub fn with_secret_mut<R>(&mut self, edit: impl FnOnce(&mut T) -> R) -> R {
4617        edit(&mut self.inner)
4618    }
4619}
4620
4621impl<T: SecureSanitize> SecureSanitize for Secret<T> {
4622    #[inline]
4623    fn secure_sanitize(&mut self) {
4624        self.inner.secure_sanitize();
4625    }
4626}
4627
4628impl<T: StableSharedSecretStorage> StableSharedSecretStorage for Secret<T> {}
4629impl<T: StableMutableSecretStorage> StableMutableSecretStorage for Secret<T> {}
4630
4631impl<T: SecureSanitize> Drop for Secret<T> {
4632    #[inline]
4633    fn drop(&mut self) {
4634        self.secure_sanitize();
4635    }
4636}
4637
4638impl<T: SecureSanitize + Default> Default for Secret<T> {
4639    #[inline]
4640    fn default() -> Self {
4641        Self::new(T::default())
4642    }
4643}
4644
4645impl<T: SecureSanitize> fmt::Debug for Secret<T> {
4646    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4647        formatter
4648            .debug_struct("Secret")
4649            .field("contents", &"<redacted>")
4650            .finish()
4651    }
4652}
4653
4654/// Clear-on-drop secret gated by an application-controlled storage allow-list.
4655///
4656/// Unlike [`Secret<T>`], construction and exposure require a policy type that
4657/// implements [`SecretStoragePolicy<T>`] for the exact wrapped type. This lets
4658/// a high-assurance application centralize accepted storage types and prevents
4659/// a dependency's unrelated storage-marker implementation from automatically
4660/// entering that accepted set.
4661///
4662/// The policy is defense in depth. Shared and mutable access still require
4663/// [`StableSharedSecretStorage`] and [`StableMutableSecretStorage`]
4664/// respectively. An incorrect policy or storage-contract implementation can
4665/// invalidate the clearing guarantee, but cannot be relied on for Rust memory
4666/// safety.
4667///
4668/// There is intentionally no field-only derive for storage stability. A proc
4669/// macro cannot inspect later inherent methods, trait implementations,
4670/// interior mutation, returned guards, callbacks, or deferred cleanup.
4671///
4672/// An unapproved type cannot be constructed under a policy:
4673///
4674/// ```compile_fail
4675/// use sanitization::{
4676///     define_secret_storage_policy, AllowlistedSecret, SecretBytes,
4677/// };
4678///
4679/// define_secret_storage_policy! {
4680///     DeploymentStoragePolicy {
4681///         SecretBytes<32> => "reviewed fixed key storage",
4682///     }
4683/// }
4684///
4685/// let _ = AllowlistedSecret::<SecretBytes<16>, DeploymentStoragePolicy>::new(
4686///     SecretBytes::from_array([0; 16]),
4687/// );
4688/// ```
4689pub struct AllowlistedSecret<T: SecureSanitize, P> {
4690    inner: T,
4691    policy: PhantomData<fn() -> P>,
4692}
4693
4694impl<T, P> AllowlistedSecret<T, P>
4695where
4696    T: SecureSanitize,
4697    P: SecretStoragePolicy<T>,
4698{
4699    /// Wrap a value approved by `P`.
4700    #[must_use]
4701    #[inline]
4702    pub const fn new(inner: T) -> Self {
4703        Self {
4704            inner,
4705            policy: PhantomData,
4706        }
4707    }
4708
4709    /// Return the policy's review rationale for this exact storage type.
4710    #[must_use]
4711    #[inline]
4712    pub const fn policy_rationale() -> &'static str {
4713        P::RATIONALE
4714    }
4715
4716    /// Consume the wrapper after first clearing the wrapped value.
4717    #[inline]
4718    pub fn into_cleared(mut self) {
4719        self.inner.secure_sanitize();
4720    }
4721}
4722
4723impl<T, P> AllowlistedSecret<T, P>
4724where
4725    T: StableSharedSecretStorage,
4726    P: SecretStoragePolicy<T>,
4727{
4728    /// Run a closure with policy-approved shared-stable storage.
4729    #[inline]
4730    pub fn with_secret<R>(&self, inspect: impl FnOnce(&T) -> R) -> R {
4731        inspect(&self.inner)
4732    }
4733}
4734
4735impl<T, P> AllowlistedSecret<T, P>
4736where
4737    T: StableMutableSecretStorage,
4738    P: SecretStoragePolicy<T>,
4739{
4740    /// Run a closure with policy-approved mutable-stable storage.
4741    #[inline]
4742    pub fn with_secret_mut<R>(&mut self, edit: impl FnOnce(&mut T) -> R) -> R {
4743        edit(&mut self.inner)
4744    }
4745}
4746
4747impl<T: SecureSanitize, P> SecureSanitize for AllowlistedSecret<T, P> {
4748    #[inline]
4749    fn secure_sanitize(&mut self) {
4750        self.inner.secure_sanitize();
4751    }
4752}
4753
4754impl<T, P> StableSharedSecretStorage for AllowlistedSecret<T, P>
4755where
4756    T: StableSharedSecretStorage,
4757    P: SecretStoragePolicy<T>,
4758{
4759}
4760
4761impl<T, P> StableMutableSecretStorage for AllowlistedSecret<T, P>
4762where
4763    T: StableMutableSecretStorage,
4764    P: SecretStoragePolicy<T>,
4765{
4766}
4767
4768impl<T: SecureSanitize, P> Drop for AllowlistedSecret<T, P> {
4769    #[inline]
4770    fn drop(&mut self) {
4771        self.secure_sanitize();
4772    }
4773}
4774
4775impl<T, P> Default for AllowlistedSecret<T, P>
4776where
4777    T: SecureSanitize + Default,
4778    P: SecretStoragePolicy<T>,
4779{
4780    #[inline]
4781    fn default() -> Self {
4782        Self::new(T::default())
4783    }
4784}
4785
4786impl<T: SecureSanitize, P> fmt::Debug for AllowlistedSecret<T, P> {
4787    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4788        formatter
4789            .debug_struct("AllowlistedSecret")
4790            .field("contents", &"<redacted>")
4791            .finish()
4792    }
4793}
4794
4795#[allow(unsafe_code)]
4796mod consume_once {
4797    use super::{fmt, SecureSanitize, StableMutableSecretStorage, StableSharedSecretStorage};
4798    use core::{
4799        cell::UnsafeCell,
4800        sync::atomic::{AtomicBool, Ordering},
4801    };
4802
4803    /// Error returned after a [`ConsumeOnceSecret`] has already been claimed.
4804    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
4805    pub struct AlreadyConsumedError;
4806
4807    impl fmt::Display for AlreadyConsumedError {
4808        fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4809            formatter.write_str("consume-once secret already claimed")
4810        }
4811    }
4812
4813    #[cfg(feature = "std")]
4814    impl std::error::Error for AlreadyConsumedError {}
4815
4816    /// Clear-on-drop wrapper that permits one scoped secret exposure.
4817    ///
4818    /// `ConsumeOnceSecret<T>` uses an atomic claim flag, so exactly one caller
4819    /// may enter [`ConsumeOnceSecret::consume`], including when multiple shared
4820    /// references race. The winning closure receives `&T`; ownership of `T` is
4821    /// not moved out through this API. A cleanup guard clears the wrapped value
4822    /// after that closure returns or unwinds, even when another owner keeps the
4823    /// wrapper alive. `Drop` clears a value that is never consumed.
4824    ///
4825    /// The successful closure can still deliberately copy or export data it
4826    /// reads. Rust moves and compiler-generated register copies remain outside
4827    /// the memory-sanitization guarantee.
4828    pub struct ConsumeOnceSecret<T: SecureSanitize> {
4829        inner: UnsafeCell<T>,
4830        claimed: AtomicBool,
4831    }
4832
4833    struct ClearOnExit<'a, T: SecureSanitize> {
4834        owner: &'a ConsumeOnceSecret<T>,
4835    }
4836
4837    impl<T: SecureSanitize> Drop for ClearOnExit<'_, T> {
4838        #[inline]
4839        fn drop(&mut self) {
4840            self.owner.clear_inner();
4841        }
4842    }
4843
4844    // SAFETY: Moving the wrapper to another thread transfers ownership of the
4845    // inner value and atomic flag. Access to the inner value is still mediated
4846    // by the claim flag.
4847    unsafe impl<T: SecureSanitize + Send> Send for ConsumeOnceSecret<T> {}
4848
4849    // SAFETY: Shared references may race to consume the value, but the atomic
4850    // swap permits exactly one successful accessor. That accessor has exclusive
4851    // logical access until its cleanup guard clears the inner value before
4852    // returning or while unwinding.
4853    unsafe impl<T: SecureSanitize + Send> Sync for ConsumeOnceSecret<T> {}
4854
4855    impl<T: SecureSanitize> ConsumeOnceSecret<T> {
4856        /// Wrap a sanitizable value for one-time consumption.
4857        #[must_use]
4858        #[inline]
4859        pub const fn new(inner: T) -> Self {
4860            Self {
4861                inner: UnsafeCell::new(inner),
4862                claimed: AtomicBool::new(false),
4863            }
4864        }
4865
4866        /// Consume the wrapper after first clearing the wrapped value.
4867        #[inline]
4868        pub fn into_cleared(mut self) {
4869            self.claimed.store(true, Ordering::Release);
4870            self.inner.get_mut().secure_sanitize();
4871        }
4872
4873        /// Returns true after an accessor claims the value, after manual
4874        /// sanitization, or after [`ConsumeOnceSecret::into_cleared`].
4875        ///
4876        /// A `true` result means later access is rejected. It does not
4877        /// distinguish an accessor that is still running from one whose cleanup
4878        /// guard has already cleared the value.
4879        #[must_use]
4880        #[inline]
4881        pub fn is_claimed(&self) -> bool {
4882            self.claimed.load(Ordering::Acquire)
4883        }
4884
4885        #[inline]
4886        fn claim(&self) -> Result<ClearOnExit<'_, T>, AlreadyConsumedError> {
4887            if self.claimed.swap(true, Ordering::AcqRel) {
4888                Err(AlreadyConsumedError)
4889            } else {
4890                Ok(ClearOnExit { owner: self })
4891            }
4892        }
4893
4894        #[inline]
4895        fn clear_inner(&self) {
4896            // SAFETY: `clear_inner` is called only by the unique successful
4897            // claimant's cleanup guard. The closure frame and its inner borrow
4898            // have ended before the guard runs, including during unwinding.
4899            unsafe { (&mut *self.inner.get()).secure_sanitize() };
4900        }
4901    }
4902
4903    impl<T: StableSharedSecretStorage> ConsumeOnceSecret<T> {
4904        /// Run a closure with shared access exactly once, then clear the
4905        /// wrapped value.
4906        ///
4907        /// The first caller atomically claims the value. Every later caller
4908        /// receives [`AlreadyConsumedError`]. The closure's return value may
4909        /// report success or failure; either way, a private cleanup guard clears
4910        /// the wrapped value before this method returns. The same guard runs
4911        /// during panic unwinding.
4912        ///
4913        /// Requiring [`StableSharedSecretStorage`] prevents safe methods reached
4914        /// through `&T` from silently releasing uncleared secret storage.
4915        /// Caller code can still deliberately copy, log, or export bytes.
4916        /// Process abort prevents the cleanup guard from running.
4917        ///
4918        /// ```compile_fail
4919        /// use sanitization::{ConsumeOnceSecret, SecureSanitize};
4920        ///
4921        /// struct Unreviewed(Vec<u8>);
4922        ///
4923        /// impl SecureSanitize for Unreviewed {
4924        ///     fn secure_sanitize(&mut self) {
4925        ///         self.0.secure_sanitize();
4926        ///     }
4927        /// }
4928        ///
4929        /// let secret = ConsumeOnceSecret::new(Unreviewed(vec![1, 2, 3]));
4930        /// // Rejected until `Unreviewed` explicitly satisfies the shared
4931        /// // storage-stability contract.
4932        /// let _ = secret.consume(|value| value.0.len());
4933        /// ```
4934        #[inline]
4935        pub fn consume<R>(&self, inspect: impl FnOnce(&T) -> R) -> Result<R, AlreadyConsumedError> {
4936            let clear_guard = self.claim()?;
4937            // SAFETY: `claim` permits exactly one successful accessor. No other
4938            // safe method can access `inner` after the claim flag is set.
4939            let result = inspect(unsafe { &*self.inner.get() });
4940            drop(clear_guard);
4941            Ok(result)
4942        }
4943    }
4944
4945    impl<T: SecureSanitize> Drop for ConsumeOnceSecret<T> {
4946        #[inline]
4947        fn drop(&mut self) {
4948            self.inner.get_mut().secure_sanitize();
4949        }
4950    }
4951
4952    impl<T: SecureSanitize + Default> Default for ConsumeOnceSecret<T> {
4953        #[inline]
4954        fn default() -> Self {
4955            Self::new(T::default())
4956        }
4957    }
4958
4959    impl<T: SecureSanitize> SecureSanitize for ConsumeOnceSecret<T> {
4960        #[inline]
4961        fn secure_sanitize(&mut self) {
4962            self.claimed.store(true, Ordering::Release);
4963            self.inner.get_mut().secure_sanitize();
4964        }
4965    }
4966
4967    impl<T: StableSharedSecretStorage> StableSharedSecretStorage for ConsumeOnceSecret<T> {}
4968    impl<T: StableMutableSecretStorage> StableMutableSecretStorage for ConsumeOnceSecret<T> {}
4969
4970    impl<T: SecureSanitize> fmt::Debug for ConsumeOnceSecret<T> {
4971        fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4972            formatter
4973                .debug_struct("ConsumeOnceSecret")
4974                .field("contents", &"<redacted>")
4975                .finish()
4976        }
4977    }
4978}
4979
4980pub use consume_once::{AlreadyConsumedError, ConsumeOnceSecret};