Skip to main content

sanitization_secrecy/
lib.rs

1#![no_std]
2#![deny(unsafe_code)]
3#![deny(unsafe_op_in_unsafe_fn)]
4#![warn(missing_docs, rust_2018_idioms, unused_qualifications)]
5
6//! Compatibility-oriented secret wrappers backed by [`sanitization`].
7//!
8//! This crate provides the familiar `SecretBox`, `SecretSlice`,
9//! `SecretString`, `ExposeSecret`, and `ExposeSecretMut` API shape for projects
10//! migrating from `secrecy` 0.10. It deliberately keeps reference-returning
11//! exposure, cloning, and plaintext serialization out of the hardened
12//! `sanitization` containers.
13//!
14//! The compatibility wrapper provides redacted formatting and sanitizes its
15//! currently boxed value on drop. It does not provide memory locking, guard
16//! pages, storage-history recovery, or the scoped-exposure guarantees of the
17//! native `sanitization` container families.
18//!
19//! Reference exposure requires the core storage-stability contracts under
20//! every feature combination. The `hazmat-unrestricted-exposure` feature adds
21//! a visibly distinct [`UnrestrictedSecretBox`] for legacy types that cannot
22//! satisfy those contracts; it never broadens [`SecretBox`].
23
24extern crate alloc;
25
26use alloc::{boxed::Box, string::String, vec::Vec};
27use core::{
28    any, fmt,
29    mem::{size_of, MaybeUninit},
30};
31use sanitization::{ct, SecureSanitize};
32
33#[cfg(feature = "serde")]
34use serde::{de, ser, Deserialize, Serialize};
35
36/// The `zeroize` API used by `secrecy` callers, available through the default
37/// `zeroize-interop` compatibility feature.
38#[cfg(feature = "zeroize-interop")]
39pub use zeroize;
40
41/// A boxed secret value with explicit reference exposure and clearing on drop.
42///
43/// This compatibility type intentionally exposes references through
44/// [`ExposeSecret`] and [`ExposeSecretMut`], with stable-storage bounds by
45/// default. Prefer native `sanitization` containers when scoped closure
46/// exposure, memory locking, canaries, or guard pages are required.
47pub struct SecretBox<S: SecureSanitize + ?Sized> {
48    inner_secret: Box<S>,
49}
50
51impl<S: SecureSanitize + ?Sized> SecretBox<S> {
52    /// Wrap an already boxed secret without copying it.
53    #[must_use]
54    #[inline]
55    pub const fn new(boxed_secret: Box<S>) -> Self {
56        Self {
57            inner_secret: boxed_secret,
58        }
59    }
60
61    /// Sanitize the currently boxed value while retaining its allocation.
62    #[inline]
63    pub fn clear_secret(&mut self) {
64        self.inner_secret.secure_sanitize();
65    }
66
67    /// Consume this wrapper after sanitizing its value.
68    #[inline]
69    pub fn into_cleared(self) {
70        drop(self);
71    }
72}
73
74impl<S: sanitization::StableMutableSecretStorage + Default> SecretBox<S> {
75    /// Allocate a default value and initialize it directly through a mutable
76    /// reference.
77    ///
78    /// If `initialize` panics, the partially initialized boxed value is
79    /// sanitized during unwinding.
80    #[must_use]
81    #[inline]
82    pub fn init_with_mut(initialize: impl FnOnce(&mut S)) -> Self {
83        let mut secret = Self::default();
84        initialize(secret.expose_secret_mut());
85        secret
86    }
87
88    /// Fallible in-place initialization of the final boxed value.
89    ///
90    /// Returning an error or unwinding sanitizes the partially initialized
91    /// value before its allocation is released. Allocation failure can still
92    /// abort and is not represented by `E`.
93    #[inline]
94    pub fn try_init_with_mut<E>(
95        initialize: impl FnOnce(&mut S) -> Result<(), E>,
96    ) -> Result<Self, E> {
97        let mut secret = Self::default();
98        initialize(secret.expose_secret_mut())?;
99        Ok(secret)
100    }
101}
102
103impl<S: CloneableSecret> SecretBox<S> {
104    /// Construct a value, clone it into its final allocation, and sanitize the
105    /// temporary value.
106    ///
107    /// Prefer [`SecretBox::new`] or [`SecretBox::init_with_mut`] because this
108    /// operation necessarily creates a temporary copy. The temporary is also
109    /// sanitized if cloning panics and Rust unwinds. Cleanup is not guaranteed
110    /// after an abort, including an allocation failure handled by aborting.
111    /// `CloneableSecret` requires custom clone implementations to sanitize
112    /// secret-bearing partial destination state if cloning unwinds; this
113    /// wrapper cannot recover state discarded inside arbitrary `Clone` code.
114    #[must_use]
115    #[inline]
116    pub fn init_with(construct: impl FnOnce() -> S) -> Self {
117        let temporary = TemporarySecret::new(construct());
118        Self::new(Box::new(temporary.value().clone()))
119    }
120
121    /// Fallible form of [`SecretBox::init_with`].
122    ///
123    /// Generator errors are returned directly. A successfully generated
124    /// temporary is sanitized on success and during panic unwinding. Allocation
125    /// failure and a panic from `S::clone` are not represented by `E`.
126    ///
127    /// `CloneableSecret` is an explicit security contract: if `S::clone`
128    /// unwinds after constructing secret-bearing destination state, that
129    /// partial state must sanitize itself during ordinary destruction. This
130    /// wrapper can sanitize the complete source temporary, but Rust does not
131    /// expose an arbitrary clone's discarded partial destination to it.
132    #[inline]
133    pub fn try_init_with<E>(construct: impl FnOnce() -> Result<S, E>) -> Result<Self, E> {
134        let temporary = TemporarySecret::new(construct()?);
135        Ok(Self::new(Box::new(temporary.value().clone())))
136    }
137}
138
139impl<S: SecureSanitize + ?Sized> From<Box<S>> for SecretBox<S> {
140    #[inline]
141    fn from(source: Box<S>) -> Self {
142        Self::new(source)
143    }
144}
145
146impl<S: SecureSanitize + Default> Default for SecretBox<S> {
147    #[inline]
148    fn default() -> Self {
149        Self::new(Box::<S>::default())
150    }
151}
152
153impl<S: SecureSanitize + ?Sized> SecureSanitize for SecretBox<S> {
154    #[inline]
155    fn secure_sanitize(&mut self) {
156        self.clear_secret();
157    }
158}
159
160#[cfg(feature = "zeroize-interop")]
161impl<S: SecureSanitize + ?Sized> zeroize::Zeroize for SecretBox<S> {
162    #[inline]
163    fn zeroize(&mut self) {
164        self.clear_secret();
165    }
166}
167
168#[cfg(feature = "zeroize-interop")]
169impl<S: SecureSanitize + ?Sized> zeroize::ZeroizeOnDrop for SecretBox<S> {}
170
171impl<S: SecureSanitize + ?Sized> Drop for SecretBox<S> {
172    #[inline]
173    fn drop(&mut self) {
174        self.clear_secret();
175    }
176}
177
178impl<S: SecureSanitize + ?Sized> fmt::Debug for SecretBox<S> {
179    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
180        write!(
181            formatter,
182            "SecretBox<{}>([REDACTED])",
183            any::type_name::<S>()
184        )
185    }
186}
187
188impl<S: SecureSanitize + ct::ConstantTimeEq + ?Sized> SecretBox<S> {
189    /// Compare two wrapped values without secret-dependent early exit.
190    ///
191    /// For dynamically sized values, length is public. The returned choice
192    /// must be explicitly declassified before it can control normal program
193    /// flow. Prefer this method over comparing exposed references with `==`.
194    #[must_use]
195    #[inline]
196    pub fn ct_eq(&self, other: &Self) -> ct::Choice {
197        ct::ConstantTimeEq::ct_eq(self.inner_secret.as_ref(), other.inner_secret.as_ref())
198    }
199}
200
201impl<S: CloneableSecret> Clone for SecretBox<S> {
202    #[inline]
203    fn clone(&self) -> Self {
204        Self::new(self.inner_secret.clone())
205    }
206}
207
208impl<S: sanitization::StableSharedSecretStorage + ?Sized> ExposeSecret<S> for SecretBox<S> {
209    #[inline]
210    fn expose_secret(&self) -> &S {
211        self.inner_secret.as_ref()
212    }
213}
214
215impl<S: sanitization::StableMutableSecretStorage + ?Sized> ExposeSecretMut<S> for SecretBox<S> {
216    #[inline]
217    fn expose_secret_mut(&mut self) -> &mut S {
218        self.inner_secret.as_mut()
219    }
220}
221
222/// Explicit reduced-assurance wrapper for legacy unrestricted exposure.
223///
224/// This type is available only with `hazmat-unrestricted-exposure`. Unlike
225/// [`SecretBox`], it does not require storage-stability attestations before
226/// returning references or invoking mutable initialization callbacks. Safe
227/// methods reached through those references can therefore replace or release
228/// secret-bearing storage without clearing historical allocations first.
229///
230/// Cargo feature unification can make this type available transitively, but it
231/// cannot change any method or trait implementation on [`SecretBox`]. A caller
232/// must name and construct `UnrestrictedSecretBox` explicitly.
233#[cfg(feature = "hazmat-unrestricted-exposure")]
234pub struct UnrestrictedSecretBox<S: SecureSanitize + ?Sized> {
235    inner: SecretBox<S>,
236}
237
238#[cfg(feature = "hazmat-unrestricted-exposure")]
239impl<S: SecureSanitize + ?Sized> UnrestrictedSecretBox<S> {
240    /// Wrap an already boxed secret without copying it.
241    #[must_use]
242    #[inline]
243    pub const fn new(boxed_secret: Box<S>) -> Self {
244        Self {
245            inner: SecretBox::new(boxed_secret),
246        }
247    }
248
249    /// Sanitize the currently boxed value while retaining its allocation.
250    #[inline]
251    pub fn clear_secret(&mut self) {
252        self.inner.clear_secret();
253    }
254
255    /// Convert to the storage-gated wrapper without copying the secret.
256    #[must_use]
257    #[inline]
258    pub fn into_restricted(self) -> SecretBox<S> {
259        self.inner
260    }
261
262    /// Consume this wrapper after sanitizing its value.
263    #[inline]
264    pub fn into_cleared(self) {
265        drop(self);
266    }
267}
268
269#[cfg(feature = "hazmat-unrestricted-exposure")]
270impl<S: SecureSanitize + Default> UnrestrictedSecretBox<S> {
271    /// Allocate a default value and initialize it through an unrestricted
272    /// mutable reference.
273    ///
274    /// If the callback reallocates or replaces owned storage, this wrapper
275    /// cannot recover and sanitize the released allocation.
276    #[must_use]
277    #[inline]
278    pub fn init_with_mut(initialize: impl FnOnce(&mut S)) -> Self {
279        let mut secret = Self::default();
280        initialize(secret.inner.inner_secret.as_mut());
281        secret
282    }
283
284    /// Fallible unrestricted initialization of the final boxed value.
285    ///
286    /// Returning an error or unwinding sanitizes the currently owned value,
287    /// but cannot recover storage released by the callback.
288    #[inline]
289    pub fn try_init_with_mut<E>(
290        initialize: impl FnOnce(&mut S) -> Result<(), E>,
291    ) -> Result<Self, E> {
292        let mut secret = Self::default();
293        initialize(secret.inner.inner_secret.as_mut())?;
294        Ok(secret)
295    }
296}
297
298#[cfg(feature = "hazmat-unrestricted-exposure")]
299impl<S: SecureSanitize + ?Sized> From<Box<S>> for UnrestrictedSecretBox<S> {
300    #[inline]
301    fn from(source: Box<S>) -> Self {
302        Self::new(source)
303    }
304}
305
306#[cfg(feature = "hazmat-unrestricted-exposure")]
307impl<S: SecureSanitize + Default> Default for UnrestrictedSecretBox<S> {
308    #[inline]
309    fn default() -> Self {
310        Self {
311            inner: SecretBox::default(),
312        }
313    }
314}
315
316#[cfg(feature = "hazmat-unrestricted-exposure")]
317impl<S: SecureSanitize + ?Sized> SecureSanitize for UnrestrictedSecretBox<S> {
318    #[inline]
319    fn secure_sanitize(&mut self) {
320        self.clear_secret();
321    }
322}
323
324#[cfg(all(feature = "hazmat-unrestricted-exposure", feature = "zeroize-interop"))]
325impl<S: SecureSanitize + ?Sized> zeroize::Zeroize for UnrestrictedSecretBox<S> {
326    #[inline]
327    fn zeroize(&mut self) {
328        self.clear_secret();
329    }
330}
331
332#[cfg(all(feature = "hazmat-unrestricted-exposure", feature = "zeroize-interop"))]
333impl<S: SecureSanitize + ?Sized> zeroize::ZeroizeOnDrop for UnrestrictedSecretBox<S> {}
334
335#[cfg(feature = "hazmat-unrestricted-exposure")]
336impl<S: SecureSanitize + ?Sized> fmt::Debug for UnrestrictedSecretBox<S> {
337    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
338        write!(
339            formatter,
340            "UnrestrictedSecretBox<{}>([REDACTED])",
341            any::type_name::<S>()
342        )
343    }
344}
345
346#[cfg(feature = "hazmat-unrestricted-exposure")]
347impl<S: SecureSanitize + ct::ConstantTimeEq + ?Sized> UnrestrictedSecretBox<S> {
348    /// Compare two wrapped values without secret-dependent early exit.
349    #[must_use]
350    #[inline]
351    pub fn ct_eq(&self, other: &Self) -> ct::Choice {
352        self.inner.ct_eq(&other.inner)
353    }
354}
355
356#[cfg(feature = "hazmat-unrestricted-exposure")]
357impl<S: CloneableSecret> Clone for UnrestrictedSecretBox<S> {
358    #[inline]
359    fn clone(&self) -> Self {
360        Self {
361            inner: self.inner.clone(),
362        }
363    }
364}
365
366#[cfg(feature = "hazmat-unrestricted-exposure")]
367impl<S: SecureSanitize + ?Sized> ExposeSecret<S> for UnrestrictedSecretBox<S> {
368    #[inline]
369    fn expose_secret(&self) -> &S {
370        self.inner.inner_secret.as_ref()
371    }
372}
373
374#[cfg(feature = "hazmat-unrestricted-exposure")]
375impl<S: SecureSanitize + ?Sized> ExposeSecretMut<S> for UnrestrictedSecretBox<S> {
376    #[inline]
377    fn expose_secret_mut(&mut self) -> &mut S {
378        self.inner.inner_secret.as_mut()
379    }
380}
381
382/// A boxed secret slice.
383pub type SecretSlice<S> = SecretBox<[S]>;
384
385/// Error returned when a no-copy vector transfer would discard capacity.
386#[derive(Clone, Copy, Debug, Eq, PartialEq)]
387pub struct SecretSliceCapacityError {
388    /// Number of initialized elements.
389    pub length: usize,
390    /// Number of elements in the source allocation.
391    pub capacity: usize,
392}
393
394impl fmt::Display for SecretSliceCapacityError {
395    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
396        write!(
397            formatter,
398            "secret slice source has length {} but capacity {}; no-copy boxing would discard secret-bearing capacity",
399            self.length, self.capacity
400        )
401    }
402}
403
404impl<S: SecureSanitize> SecretSlice<S> {
405    /// Transfer a vector without copying when its allocation is already exact.
406    ///
407    /// A non-zero-sized vector with excess capacity is sanitized and rejected
408    /// before `into_boxed_slice` can release that allocation. Do not call
409    /// `shrink_to_fit` on secret-bearing input to satisfy this precondition;
410    /// construct it with exact capacity or use the cloning [`From<Vec<S>>`]
411    /// implementation when `S` implements [`CloneableSecret`].
412    #[inline]
413    pub fn try_from_vec_exact(mut source: Vec<S>) -> Result<Self, SecretSliceCapacityError> {
414        let length = source.len();
415        let capacity = source.capacity();
416        if size_of::<S>() != 0 && capacity != length {
417            source.secure_sanitize();
418            return Err(SecretSliceCapacityError { length, capacity });
419        }
420
421        Ok(Self::new(source.into_boxed_slice()))
422    }
423}
424
425impl SecretSlice<u8> {
426    /// Allocate a zero-filled byte slice and initialize its final boxed storage.
427    ///
428    /// `length` must be trusted and bounded. Allocation failure may abort.
429    #[must_use]
430    #[inline]
431    pub fn init_with_len(length: usize, initialize: impl FnOnce(&mut [u8])) -> Self {
432        let mut secret = Self::new(alloc::vec![0_u8; length].into_boxed_slice());
433        initialize(secret.expose_secret_mut());
434        secret
435    }
436
437    /// Fallible allocation and initialization of a runtime-length byte slice.
438    ///
439    /// A returned error or unwind sanitizes the final boxed byte allocation.
440    /// Allocation refusal and initializer failure remain distinguishable. This
441    /// method does not enforce an application limit; use
442    /// [`SecretSlice::try_init_with_len_bounded`] at untrusted length
443    /// boundaries.
444    #[inline]
445    pub fn try_init_with_len<E>(
446        length: usize,
447        initialize: impl FnOnce(&mut [u8]) -> Result<(), E>,
448    ) -> Result<Self, SecretSliceInitError<E>> {
449        let mut secret =
450            try_allocate_exact_zeroed_slice(length).map_err(SecretSliceInitError::Build)?;
451        initialize(secret.expose_secret_mut()).map_err(SecretSliceInitError::Initialize)?;
452        Ok(secret)
453    }
454
455    /// Fallibly allocate and initialize a byte slice under a compile-time
456    /// public length ceiling.
457    ///
458    /// Oversized lengths are rejected before allocation and before
459    /// `initialize` runs. Allocation refusal, a non-exact allocator capacity,
460    /// and initializer failure remain distinct typed outcomes.
461    #[inline]
462    pub fn try_init_with_len_bounded<const MAX: usize, E>(
463        length: usize,
464        initialize: impl FnOnce(&mut [u8]) -> Result<(), E>,
465    ) -> Result<Self, SecretSliceInitError<E>> {
466        if length > MAX {
467            return Err(SecretSliceInitError::Build(
468                SecretSliceAllocationError::TooLong {
469                    maximum: MAX,
470                    actual: length,
471                },
472            ));
473        }
474
475        Self::try_init_with_len(length, initialize)
476    }
477}
478
479/// Error returned while allocating final storage for a runtime-length secret
480/// slice.
481#[derive(Debug)]
482pub enum SecretSliceAllocationError {
483    /// The requested public length exceeded the compile-time maximum.
484    TooLong {
485        /// Maximum accepted byte length.
486        maximum: usize,
487        /// Rejected requested byte length.
488        actual: usize,
489    },
490    /// The allocator could not reserve the requested byte length.
491    Allocation(alloc::collections::TryReserveError),
492    /// The allocator exposed more logical capacity than requested.
493    ///
494    /// The allocation is released before it receives secret input.
495    NonExactCapacity {
496        /// Requested byte length.
497        requested: usize,
498        /// Capacity returned by the allocator.
499        actual: usize,
500    },
501}
502
503impl fmt::Display for SecretSliceAllocationError {
504    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
505        match self {
506            Self::TooLong { maximum, actual } => write!(
507                formatter,
508                "secret byte length exceeds limit: maximum {maximum} bytes, got {actual} bytes"
509            ),
510            Self::Allocation(error) => write!(formatter, "secret allocation failed: {error}"),
511            Self::NonExactCapacity { requested, actual } => write!(
512                formatter,
513                "secret allocator returned capacity {actual} for requested length {requested}"
514            ),
515        }
516    }
517}
518
519impl core::error::Error for SecretSliceAllocationError {
520    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
521        match self {
522            Self::Allocation(error) => Some(error),
523            Self::TooLong { .. } | Self::NonExactCapacity { .. } => None,
524        }
525    }
526}
527
528/// Error returned by fallible runtime-length secret-slice initialization.
529#[derive(Debug)]
530pub enum SecretSliceInitError<E> {
531    /// Public-length validation or allocation failed before initialization.
532    Build(SecretSliceAllocationError),
533    /// The caller's initializer returned an error.
534    Initialize(E),
535}
536
537impl<E> From<SecretSliceAllocationError> for SecretSliceInitError<E> {
538    #[inline]
539    fn from(error: SecretSliceAllocationError) -> Self {
540        Self::Build(error)
541    }
542}
543
544impl<E: fmt::Display> fmt::Display for SecretSliceInitError<E> {
545    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
546        match self {
547            Self::Build(error) => error.fmt(formatter),
548            Self::Initialize(error) => {
549                write!(formatter, "secret slice initialization failed: {error}")
550            }
551        }
552    }
553}
554
555impl<E> core::error::Error for SecretSliceInitError<E>
556where
557    E: core::error::Error + 'static,
558{
559    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
560        match self {
561            Self::Build(error) => Some(error),
562            Self::Initialize(error) => Some(error),
563        }
564    }
565}
566
567fn try_allocate_exact_zeroed_slice(
568    length: usize,
569) -> Result<SecretSlice<u8>, SecretSliceAllocationError> {
570    let mut bytes = Vec::new();
571    bytes
572        .try_reserve_exact(length)
573        .map_err(SecretSliceAllocationError::Allocation)?;
574
575    if bytes.capacity() != length {
576        return Err(SecretSliceAllocationError::NonExactCapacity {
577            requested: length,
578            actual: bytes.capacity(),
579        });
580    }
581
582    bytes.resize(length, 0);
583    Ok(SecretSlice::new(bytes.into_boxed_slice()))
584}
585
586impl<S: CloneableSecret> From<Vec<S>> for SecretSlice<S> {
587    /// Clone into guarded destination storage, then sanitize the source vector.
588    ///
589    /// This intentionally copies the live elements so the source allocation,
590    /// including excess capacity, can be cleared before release. Completed
591    /// destination elements are also sanitized if a later clone panics.
592    #[inline]
593    fn from(source: Vec<S>) -> Self {
594        let source = TemporarySecret::new(source);
595        Self::new(clone_slice_into_box(source.value()))
596    }
597}
598
599impl<S: CloneableSecret> Clone for SecretSlice<S> {
600    #[inline]
601    fn clone(&self) -> Self {
602        Self::new(clone_slice_into_box(self.inner_secret.as_ref()))
603    }
604}
605
606impl<S: SecureSanitize> Default for SecretSlice<S> {
607    #[inline]
608    fn default() -> Self {
609        Self::new(Vec::new().into_boxed_slice())
610    }
611}
612
613/// A boxed UTF-8 secret string.
614pub type SecretString = SecretBox<str>;
615
616/// Byte-limit and exact-allocation errors for boxed UTF-8 text.
617pub type SecretStringBuildError = SecretSliceAllocationError;
618
619/// Error ingesting owned bytes as bounded secret text. Never retains input bytes.
620#[derive(Debug)]
621pub enum SecretStringUtf8Error {
622    /// The byte limit or destination allocation policy was not satisfied.
623    Build(SecretStringBuildError),
624    /// The input was within the limit but was not valid UTF-8.
625    InvalidUtf8,
626}
627
628impl fmt::Display for SecretStringUtf8Error {
629    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
630        match self {
631            Self::Build(error) => error.fmt(formatter),
632            Self::InvalidUtf8 => formatter.write_str("secret input is not valid UTF-8"),
633        }
634    }
635}
636
637impl core::error::Error for SecretStringUtf8Error {
638    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
639        match self {
640            Self::Build(error) => Some(error),
641            Self::InvalidUtf8 => None,
642        }
643    }
644}
645
646impl SecretString {
647    /// Copy owned UTF-8 bytes into final boxed text without an intermediate string.
648    ///
649    /// Checks the public byte limit before validation or allocation. The source
650    /// vector's entire capacity is wiped on success, error, or unwind.
651    /// UTF-8 validation is not a data-oblivious operation.
652    pub fn try_from_utf8_bounded<const MAX: usize>(
653        source: Vec<u8>,
654    ) -> Result<Self, SecretStringUtf8Error> {
655        let source = TemporarySecret::new(source);
656        let bytes = source.value().as_slice();
657        if bytes.len() > MAX {
658            return Err(SecretStringUtf8Error::Build(
659                SecretStringBuildError::TooLong {
660                    maximum: MAX,
661                    actual: bytes.len(),
662                },
663            ));
664        }
665        let text = core::str::from_utf8(bytes).map_err(|_| SecretStringUtf8Error::InvalidUtf8)?;
666        Self::try_from_str_bounded::<MAX>(text).map_err(SecretStringUtf8Error::Build)
667    }
668
669    /// Copy owned UTF-8 text into final boxed storage under a public byte limit.
670    ///
671    /// The source allocation, including spare capacity, is sanitized on success,
672    /// on any returned error, and during unwinding. The limit applies to the
673    /// source length in bytes. Excess length is rejected before reserving the box.
674    ///
675    /// ```
676    /// use sanitization_secrecy::{ExposeSecret, SecretString};
677    ///
678    /// let token = SecretString::try_from_string_bounded::<64>(String::from("token"))?;
679    /// assert_eq!(token.expose_secret(), "token");
680    /// # Ok::<(), sanitization_secrecy::SecretStringBuildError>(())
681    /// ```
682    pub fn try_from_string_bounded<const MAX: usize>(
683        source: String,
684    ) -> Result<Self, SecretStringBuildError> {
685        let source = TemporarySecret::new(source);
686        Self::try_from_str_bounded::<MAX>(source.value())
687    }
688
689    /// Fallibly copy borrowed UTF-8 text into a box of at most `MAX` bytes.
690    /// The caller retains responsibility for the borrowed source.
691    pub fn try_from_str_bounded<const MAX: usize>(
692        source: &str,
693    ) -> Result<Self, SecretStringBuildError> {
694        let len = source.len();
695        if len > MAX {
696            return Err(SecretStringBuildError::TooLong {
697                maximum: MAX,
698                actual: len,
699            });
700        }
701        let mut text = String::new();
702        text.try_reserve_exact(len)
703            .map_err(SecretStringBuildError::Allocation)?;
704        // Boxing can shrink excess capacity. Reject it while the buffer is empty.
705        if text.capacity() != len {
706            return Err(SecretStringBuildError::NonExactCapacity {
707                requested: len,
708                actual: text.capacity(),
709            });
710        }
711        text.push_str(source);
712        Ok(Self::new(text.into_boxed_str()))
713    }
714}
715
716impl From<String> for SecretString {
717    /// Copy into final boxed string storage and sanitize the source allocation.
718    ///
719    /// Copying is intentional: it permits the complete source capacity to be
720    /// cleared before release instead of asking `String::into_boxed_str` to
721    /// discard excess capacity without sanitizing it.
722    #[inline]
723    fn from(source: String) -> Self {
724        let source = TemporarySecret::new(source);
725        Self::new(Box::<str>::from(source.value().as_str()))
726    }
727}
728
729impl From<&str> for SecretString {
730    /// Copy a borrowed string into compatibility storage.
731    ///
732    /// The source remains outside this wrapper's ownership and clearing
733    /// guarantee.
734    #[inline]
735    fn from(source: &str) -> Self {
736        Self::new(Box::<str>::from(source))
737    }
738}
739
740/// Compatibility exception: `SecretString` is always cloneable to match
741/// `secrecy` 0.10. Other generic `SecretBox<S>` values require
742/// [`CloneableSecret`].
743impl Clone for SecretString {
744    #[inline]
745    fn clone(&self) -> Self {
746        Self::new(self.inner_secret.clone())
747    }
748}
749
750impl Default for SecretString {
751    #[inline]
752    fn default() -> Self {
753        String::new().into()
754    }
755}
756
757/// Marker for secret values whose owners explicitly permit duplication.
758///
759/// Types do not become cloneable merely by implementing [`SecureSanitize`]:
760/// `SecretString` is the intentional compatibility exception and remains
761/// unconditionally cloneable to match `secrecy` 0.10.
762///
763/// ```compile_fail
764/// use sanitization::SecureSanitize;
765/// use sanitization_secrecy::SecretBox;
766///
767/// #[derive(Clone)]
768/// struct RequiresOptIn(u8);
769/// impl SecureSanitize for RequiresOptIn {
770///     fn secure_sanitize(&mut self) {
771///         self.0.secure_sanitize();
772///     }
773/// }
774///
775/// let secret = SecretBox::new(Box::new(RequiresOptIn(7)));
776/// let duplicate = secret.clone();
777/// # let _ = duplicate;
778/// ```
779///
780/// Implementors are responsible for ensuring that partially cloned owned
781/// state is sanitized if their `Clone` implementation unwinds. The wrapper can
782/// guard completed slice elements, but it cannot inspect partial state inside
783/// an arbitrary `S::clone()` implementation.
784///
785/// This crate implements the marker for reviewed integer primitives, `String`,
786/// and arrays whose elements are those integer primitives. A custom `Copy`
787/// implementation does not authorize its array automatically because `Copy`
788/// does not prevent a separate manually implemented `Clone` from panicking.
789pub trait CloneableSecret: Clone + SecureSanitize {}
790
791macro_rules! impl_cloneable_secret {
792    ($($type:ty),+ $(,)?) => {
793        $(impl CloneableSecret for $type {})+
794    };
795}
796
797impl_cloneable_secret!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize,);
798
799impl CloneableSecret for String {}
800
801macro_rules! impl_cloneable_secret_arrays {
802    ($($type:ty),+ $(,)?) => {
803        $(impl<const N: usize> CloneableSecret for [$type; N] {})+
804    };
805}
806
807impl_cloneable_secret_arrays!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize,);
808
809/// Expose a shared reference to an inner secret.
810///
811/// The returned reference can remain live for the full borrow of `self`. By
812/// default, `SecretBox` implements this trait only for
813/// [`sanitization::StableSharedSecretStorage`]. The
814/// `hazmat-unrestricted-exposure` feature adds [`UnrestrictedSecretBox`]
815/// rather than weakening this implementation.
816pub trait ExposeSecret<S: ?Sized> {
817    /// Borrow the secret value.
818    fn expose_secret(&self) -> &S;
819}
820
821/// Expose a mutable reference to an inner secret.
822///
823/// `SecretBox` implements this trait only for
824/// [`sanitization::StableMutableSecretStorage`]. The
825/// `hazmat-unrestricted-exposure` feature adds [`UnrestrictedSecretBox`]
826/// rather than weakening this implementation.
827pub trait ExposeSecretMut<S: ?Sized> {
828    /// Mutably borrow the secret value.
829    fn expose_secret_mut(&mut self) -> &mut S;
830}
831
832/// Marker for secret values whose owners explicitly permit plaintext Serde
833/// serialization.
834///
835/// Implementing this trait is an exfiltration decision. Serialized output and
836/// serializer-owned intermediate buffers are outside this crate's clearing
837/// guarantees.
838///
839/// Serialization is unavailable without an explicit implementation:
840///
841/// ```compile_fail
842/// use sanitization_secrecy::SecretBox;
843///
844/// let secret = SecretBox::new(Box::new(String::from("token")));
845/// let encoded = serde_json::to_string(&secret).unwrap();
846/// # let _ = encoded;
847/// ```
848#[cfg(feature = "serde")]
849pub trait SerializableSecret: Serialize {}
850
851#[cfg(feature = "serde-compat-unbounded")]
852impl<'de, T> Deserialize<'de> for SecretBox<T>
853where
854    T: CloneableSecret + de::DeserializeOwned + Sized,
855{
856    #[inline]
857    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
858    where
859        D: de::Deserializer<'de>,
860    {
861        Self::try_init_with(|| T::deserialize(deserializer))
862    }
863}
864
865#[cfg(all(
866    feature = "serde-compat-unbounded",
867    feature = "hazmat-unrestricted-exposure"
868))]
869impl<'de, T> Deserialize<'de> for UnrestrictedSecretBox<T>
870where
871    T: CloneableSecret + de::DeserializeOwned + Sized,
872{
873    #[inline]
874    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
875    where
876        D: de::Deserializer<'de>,
877    {
878        SecretBox::deserialize(deserializer).map(|inner| Self { inner })
879    }
880}
881
882#[cfg(feature = "serde")]
883impl<'de> Deserialize<'de> for SecretString {
884    /// Deserialize with the core crate's default 1 MiB UTF-8 byte ceiling.
885    ///
886    /// This limit is checked when the deserializer invokes the visitor. Enforce
887    /// a separate transport or parser limit because parser-owned buffers may
888    /// already exist by then. Use `sanitization::BoundedSecretString` when the
889    /// storage type must enforce a smaller permanent maximum.
890    #[inline]
891    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
892    where
893        D: de::Deserializer<'de>,
894    {
895        de::DeserializeSeed::deserialize(
896            SecretStringSeed::<{ sanitization::DEFAULT_SECRET_STRING_SERDE_MAX_LEN }>::new(),
897            deserializer,
898        )
899    }
900}
901
902#[cfg(feature = "serde")]
903/// Deserialize a boxed secret string with an application-selected UTF-8 byte limit.
904/// The limit applies when the visitor receives text, not to parser-owned buffers.
905///
906/// ```
907/// use sanitization_secrecy::{ExposeSecret, SecretStringSeed};
908/// use serde::de::DeserializeSeed;
909///
910/// let mut input = serde_json::Deserializer::from_str(r#""token""#);
911/// let token = SecretStringSeed::<64>::new().deserialize(&mut input)?;
912/// assert_eq!(token.expose_secret(), "token");
913/// # Ok::<(), serde_json::Error>(())
914/// ```
915#[derive(Default)]
916pub struct SecretStringSeed<const MAX: usize>;
917
918#[cfg(feature = "serde")]
919impl<const MAX: usize> SecretStringSeed<MAX> {
920    /// Select a public maximum size of `MAX` bytes.
921    pub const fn new() -> Self {
922        Self
923    }
924}
925
926#[cfg(feature = "serde")]
927impl<'de, const MAX: usize> de::DeserializeSeed<'de> for SecretStringSeed<MAX> {
928    type Value = SecretString;
929
930    fn deserialize<D: de::Deserializer<'de>>(
931        self,
932        deserializer: D,
933    ) -> Result<Self::Value, D::Error> {
934        deserializer.deserialize_string(SecretStringVisitor::<MAX>)
935    }
936}
937
938#[cfg(feature = "serde")]
939struct SecretStringVisitor<const MAX: usize>;
940
941#[cfg(feature = "serde")]
942impl<'de, const MAX: usize> de::Visitor<'de> for SecretStringVisitor<MAX> {
943    type Value = SecretString;
944
945    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
946        write!(
947            formatter,
948            "secret text with a UTF-8 byte length of at most {MAX}"
949        )
950    }
951
952    fn visit_str<E>(self, text: &str) -> Result<Self::Value, E>
953    where
954        E: de::Error,
955    {
956        SecretString::try_from_str_bounded::<MAX>(text).map_err(|error| self.build_error(error))
957    }
958
959    fn visit_string<E>(self, text: String) -> Result<Self::Value, E>
960    where
961        E: de::Error,
962    {
963        SecretString::try_from_string_bounded::<MAX>(text).map_err(|error| self.build_error(error))
964    }
965}
966
967#[cfg(feature = "serde")]
968impl<const MAX: usize> SecretStringVisitor<MAX> {
969    fn build_error<E: de::Error>(&self, error: SecretStringBuildError) -> E {
970        match error {
971            SecretStringBuildError::TooLong { actual, .. } => E::invalid_length(actual, self),
972            other => E::custom(other),
973        }
974    }
975}
976
977#[cfg(feature = "serde")]
978impl<T> Serialize for SecretBox<T>
979where
980    T: sanitization::StableSharedSecretStorage + SerializableSecret + Serialize + Sized,
981{
982    #[inline]
983    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
984    where
985        S: ser::Serializer,
986    {
987        self.expose_secret().serialize(serializer)
988    }
989}
990
991#[cfg(all(feature = "serde", feature = "hazmat-unrestricted-exposure"))]
992impl<T> Serialize for UnrestrictedSecretBox<T>
993where
994    T: SecureSanitize + SerializableSecret + Serialize + Sized,
995{
996    #[inline]
997    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
998    where
999        S: ser::Serializer,
1000    {
1001        self.inner.inner_secret.as_ref().serialize(serializer)
1002    }
1003}
1004
1005struct TemporarySecret<T: SecureSanitize>(T);
1006
1007impl<T: SecureSanitize> TemporarySecret<T> {
1008    #[inline]
1009    const fn new(value: T) -> Self {
1010        Self(value)
1011    }
1012
1013    #[inline]
1014    const fn value(&self) -> &T {
1015        &self.0
1016    }
1017}
1018
1019fn clone_slice_into_box<S: CloneableSecret>(source: &[S]) -> Box<[S]> {
1020    let mut pending = PendingCloneSlice::new(source.len());
1021    for item in source {
1022        pending.push(item.clone());
1023    }
1024    pending.into_box()
1025}
1026
1027struct PendingCloneSlice<S: SecureSanitize> {
1028    storage: Option<Box<[MaybeUninit<S>]>>,
1029    initialized: usize,
1030}
1031
1032impl<S: SecureSanitize> PendingCloneSlice<S> {
1033    fn new(length: usize) -> Self {
1034        Self {
1035            storage: Some(Box::<[S]>::new_uninit_slice(length)),
1036            initialized: 0,
1037        }
1038    }
1039
1040    fn push(&mut self, value: S) {
1041        let storage = self.storage.as_mut().expect("pending clone storage");
1042        storage[self.initialized].write(value);
1043        self.initialized += 1;
1044    }
1045
1046    #[allow(unsafe_code)]
1047    fn into_box(mut self) -> Box<[S]> {
1048        let expected = self.storage.as_ref().expect("pending clone storage").len();
1049        assert_eq!(
1050            self.initialized, expected,
1051            "pending clone slice is not fully initialized"
1052        );
1053        let storage = self.storage.take().expect("pending clone storage");
1054        // SAFETY: the mandatory check above proves that `push` initialized
1055        // every slot in the consecutive prefix before the guard was disarmed.
1056        unsafe { storage.assume_init() }
1057    }
1058}
1059
1060impl<S: SecureSanitize> Drop for PendingCloneSlice<S> {
1061    #[allow(unsafe_code)]
1062    fn drop(&mut self) {
1063        let Some(storage) = self.storage.as_mut() else {
1064            return;
1065        };
1066
1067        for slot in &mut storage[..self.initialized] {
1068            // SAFETY: only the consecutive prefix counted by `initialized`
1069            // has been written. Each value is sanitized before its destructor
1070            // runs, and `MaybeUninit` prevents a second automatic drop.
1071            unsafe {
1072                slot.assume_init_mut().secure_sanitize();
1073                slot.assume_init_drop();
1074            }
1075        }
1076    }
1077}
1078
1079impl<T: SecureSanitize> Drop for TemporarySecret<T> {
1080    #[inline]
1081    fn drop(&mut self) {
1082        self.0.secure_sanitize();
1083    }
1084}
1085
1086#[cfg(test)]
1087extern crate std;
1088
1089#[cfg(test)]
1090mod tests {
1091    use super::*;
1092    use alloc::vec;
1093    use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
1094    use std::{
1095        format, panic,
1096        sync::{Arc, Mutex},
1097    };
1098
1099    static DEFAULT_VALUE_CLEARED: AtomicBool = AtomicBool::new(false);
1100    static DEFAULT_VALUE_TEST_LOCK: Mutex<()> = Mutex::new(());
1101
1102    #[cfg(feature = "serde")]
1103    impl SerializableSecret for [u8; 4] {}
1104
1105    #[cfg(all(feature = "serde", feature = "hazmat-unrestricted-exposure"))]
1106    impl SerializableSecret for String {}
1107
1108    #[test]
1109    fn string_and_slice_round_trip() {
1110        let mut source = String::with_capacity(64);
1111        source.push_str("token");
1112        let mut text = SecretString::from(source);
1113        assert_eq!(text.expose_secret(), "token");
1114        text.expose_secret_mut().make_ascii_uppercase();
1115        assert_eq!(text.expose_secret(), "TOKEN");
1116        text.clear_secret();
1117        assert_eq!(text.expose_secret().as_bytes(), &[0; 5]);
1118
1119        let bytes = SecretSlice::from(vec![1_u8, 2, 3]);
1120        assert_eq!(bytes.expose_secret(), &[1, 2, 3]);
1121    }
1122
1123    #[cfg(feature = "hazmat-unrestricted-exposure")]
1124    #[test]
1125    fn hazmat_newtype_provides_explicit_unrestricted_string_exposure() {
1126        let mut secret =
1127            UnrestrictedSecretBox::<String>::init_with_mut(|text| text.push_str("token"));
1128        secret.expose_secret_mut().push_str("-rotated");
1129        assert_eq!(secret.expose_secret(), "token-rotated");
1130
1131        let restricted = secret.into_restricted();
1132        assert_eq!(restricted.inner_secret.as_ref(), "token-rotated");
1133    }
1134
1135    #[test]
1136    fn exact_vector_transfer_rejects_and_sanitizes_excess_capacity() {
1137        struct NonCloneable {
1138            cleared: Arc<AtomicBool>,
1139            byte: u8,
1140        }
1141
1142        impl SecureSanitize for NonCloneable {
1143            fn secure_sanitize(&mut self) {
1144                self.byte = 0;
1145                self.cleared.store(true, Ordering::SeqCst);
1146            }
1147        }
1148
1149        let cleared = Arc::new(AtomicBool::new(false));
1150        let mut source = Vec::with_capacity(8);
1151        source.push(NonCloneable {
1152            cleared: Arc::clone(&cleared),
1153            byte: 23,
1154        });
1155
1156        let error = SecretSlice::try_from_vec_exact(source).unwrap_err();
1157        assert_eq!(error.length, 1);
1158        assert_eq!(error.capacity, 8);
1159        assert!(cleared.load(Ordering::SeqCst));
1160    }
1161
1162    #[test]
1163    fn exact_vector_transfer_preserves_live_elements() {
1164        let mut source = Vec::with_capacity(4);
1165        source.extend_from_slice(&[3_u8, 5, 7, 11]);
1166        assert_eq!(source.len(), source.capacity());
1167
1168        let secret = SecretSlice::try_from_vec_exact(source).unwrap();
1169        assert_eq!(secret.expose_secret(), &[3, 5, 7, 11]);
1170    }
1171
1172    #[test]
1173    fn vector_conversion_clears_source_with_excess_capacity() {
1174        let cleared = Arc::new(AtomicBool::new(false));
1175        let mut source = Vec::with_capacity(8);
1176        source.push(TrackedSecret {
1177            cleared: Arc::clone(&cleared),
1178            byte: 31,
1179        });
1180
1181        let secret = SecretSlice::from(source);
1182        assert!(cleared.load(Ordering::SeqCst));
1183        assert_eq!(secret.expose_secret()[0].byte, 31);
1184    }
1185
1186    #[test]
1187    fn debug_is_redacted() {
1188        let secret = SecretString::from("do-not-print");
1189        let rendered = format!("{secret:?}");
1190        assert!(rendered.contains("REDACTED"));
1191        assert!(!rendered.contains("do-not-print"));
1192    }
1193
1194    #[test]
1195    fn init_with_mut_writes_final_allocation() {
1196        let secret = SecretBox::<[u8; 4]>::init_with_mut(|bytes| {
1197            bytes.copy_from_slice(b"test");
1198        });
1199        assert_eq!(secret.expose_secret(), b"test");
1200    }
1201
1202    #[test]
1203    fn runtime_slice_initializer_uses_final_length_and_propagates_errors() {
1204        let secret = SecretSlice::<u8>::init_with_len(5, |bytes| {
1205            assert_eq!(bytes.len(), 5);
1206            bytes.copy_from_slice(b"token");
1207        });
1208        assert_eq!(secret.expose_secret(), b"token");
1209
1210        let result = SecretSlice::<u8>::try_init_with_len(4, |bytes| {
1211            bytes[0] = 17;
1212            Err::<(), _>("injected initialization failure")
1213        });
1214        assert!(matches!(
1215            result,
1216            Err(SecretSliceInitError::Initialize(
1217                "injected initialization failure"
1218            ))
1219        ));
1220    }
1221
1222    #[test]
1223    fn bounded_runtime_slice_rejects_length_before_initialization() {
1224        let initializer_called = AtomicBool::new(false);
1225        let result = SecretSlice::<u8>::try_init_with_len_bounded::<4, &str>(5, |_| {
1226            initializer_called.store(true, Ordering::SeqCst);
1227            Ok(())
1228        });
1229
1230        assert!(matches!(
1231            result,
1232            Err(SecretSliceInitError::Build(
1233                SecretSliceAllocationError::TooLong {
1234                    maximum: 4,
1235                    actual: 5
1236                }
1237            ))
1238        ));
1239        assert!(!initializer_called.load(Ordering::SeqCst));
1240    }
1241
1242    #[test]
1243    fn runtime_slice_reports_capacity_overflow_as_allocation_failure() {
1244        let result = SecretSlice::<u8>::try_init_with_len(usize::MAX, |_| Ok::<(), &str>(()));
1245        assert!(matches!(
1246            result,
1247            Err(SecretSliceInitError::Build(
1248                SecretSliceAllocationError::Allocation(_)
1249            ))
1250        ));
1251    }
1252
1253    #[test]
1254    fn reviewed_primitive_arrays_are_cloneable_secrets() {
1255        fn assert_cloneable<T: CloneableSecret>() {}
1256
1257        assert_cloneable::<[u8; 32]>();
1258        assert_cloneable::<[i128; 2]>();
1259    }
1260
1261    #[derive(Clone)]
1262    struct TrackedSecret {
1263        cleared: Arc<AtomicBool>,
1264        byte: u8,
1265    }
1266
1267    impl SecureSanitize for TrackedSecret {
1268        fn secure_sanitize(&mut self) {
1269            self.byte = 0;
1270            self.cleared.store(true, Ordering::SeqCst);
1271        }
1272    }
1273
1274    // STORAGE CONTRACT: all secret bytes are inline; shared and mutable
1275    // operations in this test type neither replace nor release storage.
1276    impl sanitization::StableSharedSecretStorage for TrackedSecret {}
1277    impl sanitization::StableMutableSecretStorage for TrackedSecret {}
1278
1279    impl CloneableSecret for TrackedSecret {}
1280
1281    #[derive(Default)]
1282    struct DefaultTrackedSecret(u8);
1283
1284    impl SecureSanitize for DefaultTrackedSecret {
1285        fn secure_sanitize(&mut self) {
1286            self.0 = 0;
1287            DEFAULT_VALUE_CLEARED.store(true, Ordering::SeqCst);
1288        }
1289    }
1290
1291    // STORAGE CONTRACT: the only storage is one inline byte.
1292    impl sanitization::StableSharedSecretStorage for DefaultTrackedSecret {}
1293    impl sanitization::StableMutableSecretStorage for DefaultTrackedSecret {}
1294
1295    #[test]
1296    fn drop_sanitizes_boxed_value() {
1297        let cleared = Arc::new(AtomicBool::new(false));
1298        let secret = SecretBox::new(Box::new(TrackedSecret {
1299            cleared: Arc::clone(&cleared),
1300            byte: 42,
1301        }));
1302
1303        drop(secret);
1304        assert!(cleared.load(Ordering::SeqCst));
1305    }
1306
1307    #[test]
1308    fn cloned_secret_is_independent() {
1309        let source = SecretBox::new(Box::new(7_u32));
1310        let mut duplicate = source.clone();
1311        *duplicate.expose_secret_mut() = 9;
1312
1313        assert_eq!(*source.expose_secret(), 7);
1314        assert_eq!(*duplicate.expose_secret(), 9);
1315    }
1316
1317    #[test]
1318    fn custom_clone_marker_is_the_positive_opt_in() {
1319        let cleared = Arc::new(AtomicBool::new(false));
1320        let source = SecretBox::new(Box::new(TrackedSecret { cleared, byte: 19 }));
1321        let duplicate = source.clone();
1322        assert_eq!(duplicate.expose_secret().byte, 19);
1323    }
1324
1325    #[test]
1326    fn completed_slice_clones_are_sanitized_when_a_later_clone_panics() {
1327        struct PanicCloneElement {
1328            byte: u8,
1329            clone_attempts: Arc<AtomicUsize>,
1330            leaked_on_drop: Arc<AtomicBool>,
1331            cloned: bool,
1332        }
1333
1334        impl Clone for PanicCloneElement {
1335            fn clone(&self) -> Self {
1336                if self.clone_attempts.fetch_add(1, Ordering::SeqCst) == 1 {
1337                    panic!("injected element clone panic");
1338                }
1339                Self {
1340                    byte: self.byte,
1341                    clone_attempts: Arc::clone(&self.clone_attempts),
1342                    leaked_on_drop: Arc::clone(&self.leaked_on_drop),
1343                    cloned: true,
1344                }
1345            }
1346        }
1347
1348        impl SecureSanitize for PanicCloneElement {
1349            fn secure_sanitize(&mut self) {
1350                self.byte = 0;
1351            }
1352        }
1353
1354        impl CloneableSecret for PanicCloneElement {}
1355
1356        impl Drop for PanicCloneElement {
1357            fn drop(&mut self) {
1358                if self.cloned && self.byte != 0 {
1359                    self.leaked_on_drop.store(true, Ordering::SeqCst);
1360                }
1361            }
1362        }
1363
1364        let clone_attempts = Arc::new(AtomicUsize::new(0));
1365        let leaked_on_drop = Arc::new(AtomicBool::new(false));
1366        let source = SecretBox::new(
1367            vec![
1368                PanicCloneElement {
1369                    byte: 11,
1370                    clone_attempts: Arc::clone(&clone_attempts),
1371                    leaked_on_drop: Arc::clone(&leaked_on_drop),
1372                    cloned: false,
1373                },
1374                PanicCloneElement {
1375                    byte: 13,
1376                    clone_attempts,
1377                    leaked_on_drop: Arc::clone(&leaked_on_drop),
1378                    cloned: false,
1379                },
1380            ]
1381            .into_boxed_slice(),
1382        );
1383
1384        let result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
1385            let _ = source.clone();
1386        }));
1387        assert!(result.is_err());
1388        assert!(!leaked_on_drop.load(Ordering::SeqCst));
1389    }
1390
1391    #[test]
1392    fn incomplete_pending_clone_keeps_cleanup_guard_armed() {
1393        let cleared = Arc::new(AtomicBool::new(false));
1394        let mut pending = PendingCloneSlice::new(2);
1395        pending.push(TrackedSecret {
1396            cleared: Arc::clone(&cleared),
1397            byte: 47,
1398        });
1399
1400        let result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
1401            let _ = pending.into_box();
1402        }));
1403
1404        assert!(result.is_err());
1405        assert!(cleared.load(Ordering::SeqCst));
1406    }
1407
1408    #[test]
1409    fn compatibility_comparison_uses_explicit_declassification() {
1410        let left = SecretString::from("same-token");
1411        let equal = SecretString::from("same-token");
1412        let different = SecretString::from("other-token");
1413
1414        assert!(left
1415            .ct_eq(&equal)
1416            .declassify("authentication token equality is intentionally public"));
1417        assert!(!left
1418            .ct_eq(&different)
1419            .declassify("authentication token inequality is intentionally public"));
1420    }
1421
1422    #[test]
1423    fn init_temporary_is_sanitized_on_success() {
1424        let cleared = Arc::new(AtomicBool::new(false));
1425        let secret = SecretBox::init_with(|| TrackedSecret {
1426            cleared: Arc::clone(&cleared),
1427            byte: 42,
1428        });
1429
1430        assert!(cleared.load(Ordering::SeqCst));
1431        assert_eq!(secret.expose_secret().byte, 42);
1432    }
1433
1434    #[test]
1435    fn init_temporary_is_sanitized_when_clone_panics() {
1436        #[derive(Default)]
1437        struct PanicClone {
1438            cleared: Arc<AtomicBool>,
1439        }
1440
1441        impl Clone for PanicClone {
1442            fn clone(&self) -> Self {
1443                panic!("injected clone panic")
1444            }
1445        }
1446
1447        impl SecureSanitize for PanicClone {
1448            fn secure_sanitize(&mut self) {
1449                self.cleared.store(true, Ordering::SeqCst);
1450            }
1451        }
1452
1453        impl CloneableSecret for PanicClone {}
1454
1455        let cleared = Arc::new(AtomicBool::new(false));
1456        let result = panic::catch_unwind({
1457            let cleared = Arc::clone(&cleared);
1458            move || {
1459                let _ = SecretBox::init_with(|| PanicClone { cleared });
1460            }
1461        });
1462
1463        assert!(result.is_err());
1464        assert!(cleared.load(Ordering::SeqCst));
1465    }
1466
1467    #[test]
1468    fn init_with_mut_sanitizes_partial_value_during_unwind() {
1469        let _test_guard = DEFAULT_VALUE_TEST_LOCK
1470            .lock()
1471            .expect("default-value cleanup test lock");
1472        DEFAULT_VALUE_CLEARED.store(false, Ordering::SeqCst);
1473        let result = panic::catch_unwind(|| {
1474            let _ = SecretBox::<DefaultTrackedSecret>::init_with_mut(|secret| {
1475                secret.0 = 42;
1476                panic!("injected initializer panic");
1477            });
1478        });
1479
1480        assert!(result.is_err());
1481        assert!(DEFAULT_VALUE_CLEARED.load(Ordering::SeqCst));
1482    }
1483
1484    #[test]
1485    fn try_init_with_mut_sanitizes_partial_value_on_error() {
1486        let _test_guard = DEFAULT_VALUE_TEST_LOCK
1487            .lock()
1488            .expect("default-value cleanup test lock");
1489        DEFAULT_VALUE_CLEARED.store(false, Ordering::SeqCst);
1490        let result = SecretBox::<DefaultTrackedSecret>::try_init_with_mut(|secret| {
1491            secret.0 = 29;
1492            Err::<(), _>("injected initialization failure")
1493        });
1494
1495        assert_eq!(result.unwrap_err(), "injected initialization failure");
1496        assert!(DEFAULT_VALUE_CLEARED.load(Ordering::SeqCst));
1497    }
1498
1499    #[test]
1500    fn into_cleared_sanitizes_exactly_once() {
1501        struct CountedClear(Arc<AtomicUsize>);
1502
1503        impl SecureSanitize for CountedClear {
1504            fn secure_sanitize(&mut self) {
1505                self.0.fetch_add(1, Ordering::SeqCst);
1506            }
1507        }
1508
1509        let clear_count = Arc::new(AtomicUsize::new(0));
1510        SecretBox::new(Box::new(CountedClear(Arc::clone(&clear_count)))).into_cleared();
1511        assert_eq!(clear_count.load(Ordering::SeqCst), 1);
1512    }
1513
1514    #[test]
1515    fn fallible_constructor_preserves_generator_error() {
1516        let result = SecretBox::<[u8; 4]>::try_init_with(|| Err::<[u8; 4], _>("failure"));
1517        assert_eq!(result.unwrap_err(), "failure");
1518    }
1519
1520    #[cfg(feature = "serde")]
1521    #[test]
1522    fn serde_plaintext_requires_explicit_marker() {
1523        let secret = SecretBox::new(Box::new([1_u8, 2, 3, 4]));
1524        assert_eq!(secret.expose_secret(), &[1, 2, 3, 4]);
1525        assert_eq!(serde_json::to_string(&secret).unwrap(), "[1,2,3,4]");
1526    }
1527
1528    #[cfg(feature = "serde")]
1529    #[test]
1530    #[cfg_attr(
1531        miri,
1532        ignore = "large JSON boundary fixture is covered natively; small byte limits are tested under Miri"
1533    )]
1534    fn serde_secret_string_enforces_default_input_ceiling() {
1535        let accepted_json = format!(
1536            "\"{}\"",
1537            "a".repeat(sanitization::DEFAULT_SECRET_STRING_SERDE_MAX_LEN)
1538        );
1539        let accepted: SecretString = serde_json::from_str(&accepted_json).unwrap();
1540        assert_eq!(
1541            accepted.expose_secret().len(),
1542            sanitization::DEFAULT_SECRET_STRING_SERDE_MAX_LEN
1543        );
1544
1545        let rejected_json = format!(
1546            "\"{}\"",
1547            "b".repeat(sanitization::DEFAULT_SECRET_STRING_SERDE_MAX_LEN + 1)
1548        );
1549        assert!(serde_json::from_str::<SecretString>(&rejected_json).is_err());
1550        use serde::de::Visitor;
1551        let oversized = "b".repeat(sanitization::DEFAULT_SECRET_STRING_SERDE_MAX_LEN + 1);
1552        let error = SecretStringVisitor::<{ sanitization::DEFAULT_SECRET_STRING_SERDE_MAX_LEN }>
1553            .visit_string::<de::value::Error>(oversized)
1554            .unwrap_err();
1555        assert!(format!("{error}").contains("invalid length"));
1556    }
1557
1558    #[test]
1559    fn bounded_utf8_checks_length_before_validity() {
1560        let text = "\u{e9}";
1561        assert_eq!(
1562            SecretString::try_from_utf8_bounded::<2>(text.as_bytes().to_vec())
1563                .unwrap()
1564                .expose_secret(),
1565            text
1566        );
1567        assert_eq!(
1568            SecretString::try_from_utf8_bounded::<0>(Vec::new())
1569                .unwrap()
1570                .expose_secret(),
1571            ""
1572        );
1573        for bytes in [text.as_bytes().to_vec(), alloc::vec![0xff; 2]] {
1574            assert!(matches!(
1575                SecretString::try_from_utf8_bounded::<1>(bytes),
1576                Err(SecretStringUtf8Error::Build(
1577                    SecretStringBuildError::TooLong {
1578                        maximum: 1,
1579                        actual: 2
1580                    }
1581                ))
1582            ));
1583        }
1584        assert!(matches!(
1585            SecretString::try_from_utf8_bounded::<1>(alloc::vec![0xff]),
1586            Err(SecretStringUtf8Error::InvalidUtf8)
1587        ));
1588    }
1589
1590    #[cfg(feature = "serde")]
1591    #[test]
1592    fn seed_limits_owned_and_borrowed_text_in_bytes() {
1593        use serde::de::{
1594            value::{BorrowedStrDeserializer, Error, StringDeserializer},
1595            DeserializeSeed,
1596        };
1597        let text = "\u{e9}";
1598        let borrowed = || BorrowedStrDeserializer::<Error>::new(text);
1599        let owned = || StringDeserializer::<Error>::new(text.into());
1600        assert_eq!(
1601            SecretStringSeed::<2>::new()
1602                .deserialize(borrowed())
1603                .unwrap()
1604                .expose_secret(),
1605            text
1606        );
1607        assert_eq!(
1608            SecretStringSeed::<2>::new()
1609                .deserialize(owned())
1610                .unwrap()
1611                .expose_secret(),
1612            text
1613        );
1614        for error in [
1615            SecretStringSeed::<1>::new()
1616                .deserialize(borrowed())
1617                .unwrap_err(),
1618            SecretStringSeed::<1>::new()
1619                .deserialize(owned())
1620                .unwrap_err(),
1621        ] {
1622            assert!(format!("{error}").contains("UTF-8 byte length of at most 1"));
1623            assert!(!format!("{error}").contains(text));
1624        }
1625    }
1626
1627    #[test]
1628    fn bounded_string_constructors_measure_utf8_bytes() {
1629        let two_bytes = "\u{e9}";
1630        assert_eq!(
1631            SecretString::try_from_string_bounded::<2>(two_bytes.into())
1632                .unwrap()
1633                .expose_secret(),
1634            two_bytes
1635        );
1636        assert!(matches!(
1637            SecretString::try_from_str_bounded::<1>(two_bytes),
1638            Err(SecretStringBuildError::TooLong {
1639                actual: 2,
1640                maximum: 1
1641            })
1642        ));
1643        assert_eq!(
1644            SecretString::try_from_str_bounded::<0>("")
1645                .unwrap()
1646                .expose_secret(),
1647            ""
1648        );
1649    }
1650
1651    #[cfg(feature = "serde")]
1652    #[test]
1653    fn serde_owned_string_preserves_text() {
1654        use serde::de::Visitor;
1655        let secret = SecretStringVisitor::<5>
1656            .visit_string::<de::value::Error>("token".into())
1657            .unwrap();
1658        assert_eq!(secret.expose_secret(), "token");
1659    }
1660
1661    #[cfg(feature = "serde-compat-unbounded")]
1662    #[test]
1663    fn generic_serde_deserialization_requires_unbounded_compatibility_opt_in() {
1664        let secret: SecretBox<String> = serde_json::from_str("\"token\"").unwrap();
1665        assert_eq!(secret.inner_secret.as_ref(), "token");
1666    }
1667
1668    #[cfg(all(
1669        feature = "serde-compat-unbounded",
1670        feature = "hazmat-unrestricted-exposure"
1671    ))]
1672    #[test]
1673    fn unrestricted_newtype_serde_requires_both_explicit_features() {
1674        let secret: UnrestrictedSecretBox<String> = serde_json::from_str("\"token\"").unwrap();
1675        assert_eq!(secret.expose_secret(), "token");
1676        assert_eq!(serde_json::to_string(&secret).unwrap(), "\"token\"");
1677    }
1678}