secure-gate 0.8.0-rc.6

Secure wrappers for secrets with explicit access and automatic zeroization (requires inner type: Zeroize)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! Heap-allocated wrapper for variable-length secrets.
//!
//! Provides [`Dynamic<T>`], a zero-cost wrapper enforcing explicit access to sensitive data.
//! Treat secrets as radioactive — minimize exposure surface.
//!
//! **Inner type must implement `Zeroize`** for automatic zeroization on drop (including spare capacity).
//! Requires the `alloc` feature.
//!
//! # Examples
//!
//! ```rust
//! # #[cfg(feature = "alloc")]
//! use secure_gate::{Dynamic, RevealSecret};
//!
//! # #[cfg(feature = "alloc")]
//! {
//! let secret: Dynamic<Vec<u8>> = Dynamic::new(vec![1u8, 2, 3, 4]);
//! let sum = secret.with_secret(|s| s.iter().sum::<u8>());
//! assert_eq!(sum, 10);
//! # }
//! ```

#[cfg(feature = "alloc")]
extern crate alloc;
use alloc::boxed::Box;
use zeroize::Zeroize;

#[cfg(any(feature = "encoding-hex", feature = "encoding-base64"))]
use crate::RevealSecret;

// Encoding traits
#[cfg(feature = "encoding-base64")]
use crate::traits::encoding::base64_url::ToBase64Url;
#[cfg(feature = "encoding-hex")]
use crate::traits::encoding::hex::ToHex;

#[cfg(feature = "rand")]
use rand::{rngs::OsRng, TryCryptoRng, TryRngCore};

#[cfg(feature = "encoding-base64")]
use crate::traits::decoding::base64_url::FromBase64UrlStr;
#[cfg(feature = "encoding-bech32")]
use crate::traits::decoding::bech32::FromBech32Str;
#[cfg(feature = "encoding-bech32m")]
use crate::traits::decoding::bech32m::FromBech32mStr;
#[cfg(feature = "encoding-hex")]
use crate::traits::decoding::hex::FromHexStr;

/// Zero-cost heap-allocated wrapper for variable-length secrets.
///
/// Requires `alloc`. **Inner type must implement `Zeroize`** for automatic zeroization on drop
/// (including spare capacity in `Vec`/`String`).
///
/// No `Deref`, `AsRef`, or `Copy` by default — all access requires
/// [`expose_secret()`](crate::RevealSecret::expose_secret) or
/// [`with_secret()`](crate::RevealSecret::with_secret) (scoped, preferred).
/// For the common concrete types, [`Dynamic::<Vec<u8>>::new_with`](Dynamic::new_with) and
/// [`Dynamic::<String>::new_with`](Dynamic::new_with) are the matching scoped constructors —
/// closures that write directly into the wrapper. [`new(value)`](Dynamic::new) remains
/// available as the ergonomic default. `Debug` always prints `[REDACTED]`.
pub struct Dynamic<T: ?Sized + zeroize::Zeroize> {
    inner: Box<T>,
}

impl<T: ?Sized + zeroize::Zeroize> Dynamic<T> {
    /// Wraps `value` in a `Box<T>` and returns a `Dynamic<T>`.
    ///
    /// Accepts any type that implements `Into<Box<T>>` — including owned values,
    /// `Box<T>`, `String`, `Vec<u8>`, `&str` (via the blanket `From<&str>` impl), etc.
    ///
    /// Equivalent to `Dynamic::from(value)` — `#[doc(alias = "from")]` is set so both
    /// names appear in docs.rs search.
    ///
    /// Requires the `alloc` feature (which `Dynamic<T>` itself always requires).
    #[doc(alias = "from")]
    #[inline(always)]
    pub fn new<U>(value: U) -> Self
    where
        U: Into<Box<T>>,
    {
        let inner = value.into();
        Self { inner }
    }
}

// From impls
impl<T: ?Sized + zeroize::Zeroize> From<Box<T>> for Dynamic<T> {
    #[inline(always)]
    fn from(boxed: Box<T>) -> Self {
        Self { inner: boxed }
    }
}

impl From<&[u8]> for Dynamic<Vec<u8>> {
    #[inline(always)]
    fn from(slice: &[u8]) -> Self {
        Self::new(slice.to_vec())
    }
}

impl From<&str> for Dynamic<String> {
    #[inline(always)]
    fn from(input: &str) -> Self {
        Self::new(input.to_string())
    }
}

impl<T: 'static + zeroize::Zeroize> From<T> for Dynamic<T> {
    #[inline(always)]
    fn from(value: T) -> Self {
        Self {
            inner: Box::new(value),
        }
    }
}

// Encoding helpers for Dynamic<Vec<u8>>
impl Dynamic<Vec<u8>> {
    /// Encodes the secret bytes as a lowercase hex string.
    ///
    /// Delegates to [`ToHex::to_hex`](crate::ToHex::to_hex) on the inner `Vec<u8>`.
    /// Requires the `encoding-hex` feature.
    #[cfg(feature = "encoding-hex")]
    #[inline]
    pub fn to_hex(&self) -> alloc::string::String {
        self.with_secret(|s: &Vec<u8>| s.to_hex())
    }

    /// Encodes the secret bytes as an uppercase hex string.
    ///
    /// Delegates to [`ToHex::to_hex_upper`](crate::ToHex::to_hex_upper) on the inner `Vec<u8>`.
    /// Requires the `encoding-hex` feature.
    #[cfg(feature = "encoding-hex")]
    #[inline]
    pub fn to_hex_upper(&self) -> alloc::string::String {
        self.with_secret(|s: &Vec<u8>| s.to_hex_upper())
    }

    /// Encodes the secret bytes as an unpadded Base64url string.
    ///
    /// Delegates to [`ToBase64Url::to_base64url`](crate::ToBase64Url::to_base64url) on the inner `Vec<u8>`.
    /// Requires the `encoding-base64` feature.
    #[cfg(feature = "encoding-base64")]
    #[inline]
    pub fn to_base64url(&self) -> alloc::string::String {
        self.with_secret(|s: &Vec<u8>| s.to_base64url())
    }

    /// Transfers `protected` bytes into a freshly boxed `Vec`, keeping
    /// [`zeroize::Zeroizing`] alive across the only allocation that can panic.
    ///
    /// # Panic safety
    ///
    /// `Box::new(Vec::new())` is the sole allocation point — just the 24-byte
    /// `Vec` header, no data buffer. If it panics (OOM), `protected` is still
    /// in scope and `Zeroizing::drop` zeroes the secret bytes during unwind.
    /// After the swap, `protected` holds an empty `Vec` (no-op to zeroize) and
    /// `Dynamic::from(boxed)` is an infallible struct-field assignment.
    ///
    /// Note: `Box::new(*protected)` would be cleaner but does not compile —
    /// `Zeroizing` implements `Deref` (returning `&T`), not a move-out, so
    /// `*protected` yields a reference rather than an owned value (E0507).
    #[cfg(any(
        feature = "encoding-hex",
        feature = "encoding-base64",
        feature = "encoding-bech32",
        feature = "encoding-bech32m",
    ))]
    #[inline(always)]
    fn from_protected_bytes(mut protected: zeroize::Zeroizing<alloc::vec::Vec<u8>>) -> Self {
        // Only fallible allocation; protected stays live across it for panic-safety
        let mut boxed = Box::<alloc::vec::Vec<u8>>::default();
        core::mem::swap(&mut *boxed, &mut *protected);
        Self::from(boxed)
    }

    /// Closure-based constructor for consistent API with [`Fixed::new_with`](crate::Fixed::new_with).
    /// The actual secret data is allocated on the heap; this method exists
    /// for consistent security-first construction idiom across the crate.
    #[inline(always)]
    pub fn new_with<F>(f: F) -> Self
    where
        F: FnOnce(&mut alloc::vec::Vec<u8>),
    {
        let mut v = alloc::vec::Vec::new();
        f(&mut v);
        Self::new(v)
    }
}

impl Dynamic<alloc::string::String> {
    /// Closure-based constructor for consistent API with [`Fixed::new_with`](crate::Fixed::new_with).
    /// The actual secret data is allocated on the heap; this method exists
    /// for consistent security-first construction idiom across the crate.
    #[inline(always)]
    pub fn new_with<F>(f: F) -> Self
    where
        F: FnOnce(&mut alloc::string::String),
    {
        let mut s = alloc::string::String::new();
        f(&mut s);
        Self::new(s)
    }
}

// RevealSecret
impl crate::RevealSecret for Dynamic<String> {
    type Inner = String;

    #[inline(always)]
    fn with_secret<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&String) -> R,
    {
        f(&self.inner)
    }

    #[inline(always)]
    fn expose_secret(&self) -> &String {
        &self.inner
    }

    #[inline(always)]
    fn len(&self) -> usize {
        self.inner.len()
    }

    /// Consumes `self` and returns the inner `String` wrapped in [`crate::InnerSecret`].
    ///
    /// **Allocation note:** allocates one small `Box<String>` sentinel (24 bytes on
    /// 64-bit) before the swap. If that allocation panics (OOM), `self.inner` is
    /// unchanged and `Dynamic::drop` zeroizes the real secret during unwind —
    /// confidentiality is preserved. This is the same OOM-safety pattern used by
    /// `from_protected_bytes` and `deserialize_with_limit`.
    ///
    /// See [`RevealSecret::into_inner`] for full documentation including the
    /// redacted `Debug` behavior.
    #[inline(always)]
    fn into_inner(mut self) -> crate::InnerSecret<String>
    where
        Self: Sized,
        Self::Inner: Sized + Default + zeroize::Zeroize,
    {
        // Take inner and leave an empty-String sentinel. If allocating the default
        // panics (OOM) before the swap, self.inner still holds the real secret and
        // Dynamic::drop zeroizes it on unwind. After `take`, self.inner is an empty
        // `String` in the box — zeroized on Dynamic::drop as a no-op. `*boxed`
        // deref-moves the String out of the Box.
        let boxed = core::mem::take(&mut self.inner);
        crate::InnerSecret::new(*boxed)
    }
}

impl<T: zeroize::Zeroize> crate::RevealSecret for Dynamic<Vec<T>> {
    type Inner = Vec<T>;

    #[inline(always)]
    fn with_secret<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&Vec<T>) -> R,
    {
        f(&self.inner)
    }

    #[inline(always)]
    fn expose_secret(&self) -> &Vec<T> {
        &self.inner
    }

    #[inline(always)]
    fn len(&self) -> usize {
        self.inner.len() * core::mem::size_of::<T>()
    }

    /// Consumes `self` and returns the inner `Vec<T>` wrapped in [`crate::InnerSecret`].
    ///
    /// **Allocation note:** allocates one small `Box<Vec<T>>` sentinel (24 bytes on
    /// 64-bit) before the swap. If that allocation panics (OOM), `self.inner` is
    /// unchanged and `Dynamic::drop` zeroizes the real secret during unwind —
    /// confidentiality is preserved. This is the same OOM-safety pattern used by
    /// `from_protected_bytes` and `deserialize_with_limit`.
    ///
    /// See [`RevealSecret::into_inner`] for full documentation including the
    /// redacted `Debug` behavior.
    #[inline(always)]
    fn into_inner(mut self) -> crate::InnerSecret<Vec<T>>
    where
        Self: Sized,
        Self::Inner: Sized + Default + zeroize::Zeroize,
    {
        // Take inner and leave an empty-Vec sentinel. If allocating the default
        // panics (OOM) before the swap, self.inner still holds the real secret and
        // Dynamic::drop zeroizes it on unwind. After `take`, self.inner is an empty
        // `Vec` in the box — zeroized on Dynamic::drop as a no-op. `*boxed`
        // deref-moves the Vec out of the Box.
        let boxed = core::mem::take(&mut self.inner);
        crate::InnerSecret::new(*boxed)
    }
}

// RevealSecretMut
impl crate::RevealSecretMut for Dynamic<String> {
    #[inline(always)]
    fn with_secret_mut<F, R>(&mut self, f: F) -> R
    where
        F: FnOnce(&mut String) -> R,
    {
        f(&mut self.inner)
    }

    #[inline(always)]
    fn expose_secret_mut(&mut self) -> &mut String {
        &mut self.inner
    }
}

impl<T: zeroize::Zeroize> crate::RevealSecretMut for Dynamic<Vec<T>> {
    #[inline(always)]
    fn with_secret_mut<F, R>(&mut self, f: F) -> R
    where
        F: FnOnce(&mut Vec<T>) -> R,
    {
        f(&mut self.inner)
    }

    #[inline(always)]
    fn expose_secret_mut(&mut self) -> &mut Vec<T> {
        &mut self.inner
    }
}

// Random generation
#[cfg(feature = "rand")]
impl Dynamic<alloc::vec::Vec<u8>> {
    /// Fills a new `Vec<u8>` with `len` cryptographically secure random bytes and wraps it.
    ///
    /// Uses the system RNG ([`OsRng`](rand::rngs::OsRng)) via [`TryRngCore::try_fill_bytes`](rand::TryRngCore::try_fill_bytes).
    /// In `rand` 0.9, `OsRng` is a zero-sized handle to the OS generator (not user-seedable). Requires the `rand`
    /// feature (and `alloc`, which `Dynamic<Vec<u8>>` always needs).
    ///
    /// # Panics
    ///
    /// Panics if the system RNG fails to provide bytes ([`TryRngCore::try_fill_bytes`](rand::TryRngCore::try_fill_bytes)
    /// returns `Err`). This is treated as a fatal environment error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(all(feature = "alloc", feature = "rand"))]
    /// use secure_gate::{Dynamic, RevealSecret};
    ///
    /// # #[cfg(all(feature = "alloc", feature = "rand"))]
    /// # {
    /// let nonce: Dynamic<Vec<u8>> = Dynamic::from_random(24);
    /// assert_eq!(nonce.len(), 24);
    /// # }
    /// ```
    #[inline]
    pub fn from_random(len: usize) -> Self {
        Self::new_with(|v| {
            v.resize(len, 0u8);
            OsRng
                .try_fill_bytes(v)
                .expect("OsRng failure is a program error");
        })
    }

    /// Allocates a `Vec<u8>` of length `len`, fills it from `rng`, and wraps it.
    ///
    /// Accepts any [`TryCryptoRng`](rand::TryCryptoRng) + [`TryRngCore`](rand::TryRngCore).
    /// Pass [`OsRng`](rand::rngs::OsRng) for the same system entropy as [`from_random`](Self::from_random)
    /// with a fallible interface. **Do not use `OsRng` for deterministic tests** — in `rand` 0.9 it is a
    /// unit struct backed by the OS and is **not** seedable; use a seedable PRNG such as
    /// [`StdRng`](rand::rngs::StdRng) with [`SeedableRng`](rand::SeedableRng) instead. Requires the `rand`
    /// feature and `alloc` (implicit — [`Dynamic<T>`](crate::Dynamic) itself requires it).
    ///
    /// # Errors
    ///
    /// Returns `R::Error` if [`try_fill_bytes`](rand::TryRngCore::try_fill_bytes) fails.
    ///
    /// # Examples
    ///
    /// System RNG (same source as `from_random`, `Result`-based):
    ///
    /// ```rust
    /// # #[cfg(all(feature = "alloc", feature = "rand"))]
    /// # {
    /// use rand::rngs::OsRng;
    /// use secure_gate::Dynamic;
    ///
    /// let nonce: Dynamic<Vec<u8>> = Dynamic::from_rng(24, &mut OsRng).expect("rng fill");
    /// # }
    /// ```
    ///
    /// Deterministic fill (tests) with a seedable generator:
    ///
    /// ```rust
    /// # #[cfg(all(feature = "alloc", feature = "rand"))]
    /// # {
    /// use rand::rngs::StdRng;
    /// use rand::SeedableRng;
    /// use secure_gate::Dynamic;
    ///
    /// let mut rng = StdRng::from_seed([9u8; 32]);
    /// let nonce: Dynamic<Vec<u8>> = Dynamic::from_rng(24, &mut rng).expect("rng fill");
    /// # }
    /// ```
    #[inline]
    pub fn from_rng<R: TryRngCore + TryCryptoRng>(len: usize, rng: &mut R) -> Result<Self, R::Error> {
        let mut result = Ok(());
        let this = Self::new_with(|v| {
            v.resize(len, 0u8);
            result = rng.try_fill_bytes(v);
        });
        result.map(|_| this)
    }
}

// Decoding constructors
#[cfg(feature = "encoding-hex")]
impl Dynamic<alloc::vec::Vec<u8>> {
    /// Decodes a lowercase hex string into `Dynamic<Vec<u8>>`.
    ///
    /// The decoded buffer is kept inside a `Zeroizing` wrapper until after the
    /// `Box` allocation completes, guaranteeing zeroization even on OOM panic.
    pub fn try_from_hex(s: &str) -> Result<Self, crate::error::HexError> {
        Ok(Self::from_protected_bytes(zeroize::Zeroizing::new(
            s.try_from_hex()?,
        )))
    }
}

#[cfg(feature = "encoding-base64")]
impl Dynamic<alloc::vec::Vec<u8>> {
    /// Decodes a Base64url (unpadded) string into `Dynamic<Vec<u8>>`.
    ///
    /// The decoded buffer is kept inside a `Zeroizing` wrapper until after the
    /// `Box` allocation completes, guaranteeing zeroization even on OOM panic.
    pub fn try_from_base64url(s: &str) -> Result<Self, crate::error::Base64Error> {
        Ok(Self::from_protected_bytes(zeroize::Zeroizing::new(
            s.try_from_base64url()?,
        )))
    }
}

#[cfg(feature = "encoding-bech32")]
impl Dynamic<alloc::vec::Vec<u8>> {
    /// Decodes a Bech32 (BIP-173) string into `Dynamic<Vec<u8>>`.
    ///
    /// The decoded buffer is kept inside a `Zeroizing` wrapper until after the
    /// `Box` allocation completes, guaranteeing zeroization even on OOM panic.
    ///
    /// # Warning
    ///
    /// The HRP is **not validated** — any HRP will be accepted as long as the checksum
    /// is valid. For security-critical code where cross-protocol confusion must be
    /// prevented, use [`try_from_bech32`](Self::try_from_bech32).
    pub fn try_from_bech32_unchecked(s: &str) -> Result<Self, crate::error::Bech32Error> {
        let (_hrp, bytes) = s.try_from_bech32_unchecked()?;
        Ok(Self::from_protected_bytes(zeroize::Zeroizing::new(bytes)))
    }

    /// Decodes a Bech32 (BIP-173) string into `Dynamic<Vec<u8>>`, validating that the HRP
    /// matches `expected_hrp` (case-insensitive).
    ///
    /// The decoded buffer is kept inside a `Zeroizing` wrapper until after the
    /// `Box` allocation completes, guaranteeing zeroization even on OOM panic.
    ///
    /// Prefer this over [`try_from_bech32_unchecked`](Self::try_from_bech32_unchecked) in
    /// security-critical code to prevent cross-protocol confusion attacks.
    pub fn try_from_bech32(s: &str, expected_hrp: &str) -> Result<Self, crate::error::Bech32Error> {
        Ok(Self::from_protected_bytes(zeroize::Zeroizing::new(
            s.try_from_bech32(expected_hrp)?,
        )))
    }
}

#[cfg(feature = "encoding-bech32m")]
impl Dynamic<alloc::vec::Vec<u8>> {
    /// Decodes a Bech32m (BIP-350) string into `Dynamic<Vec<u8>>`.
    ///
    /// The decoded buffer is kept inside a `Zeroizing` wrapper until after the
    /// `Box` allocation completes, guaranteeing zeroization even on OOM panic.
    ///
    /// # Warning
    ///
    /// The HRP is **not validated** — any HRP will be accepted as long as the checksum
    /// is valid. For security-critical code where cross-protocol confusion must be
    /// prevented, use [`try_from_bech32m`](Self::try_from_bech32m).
    pub fn try_from_bech32m_unchecked(s: &str) -> Result<Self, crate::error::Bech32Error> {
        let (_hrp, bytes) = s.try_from_bech32m_unchecked()?;
        Ok(Self::from_protected_bytes(zeroize::Zeroizing::new(bytes)))
    }

    /// Decodes a Bech32m (BIP-350) string into `Dynamic<Vec<u8>>`, validating that the HRP
    /// matches `expected_hrp` (case-insensitive).
    ///
    /// The decoded buffer is kept inside a `Zeroizing` wrapper until after the
    /// `Box` allocation completes, guaranteeing zeroization even on OOM panic.
    ///
    /// Prefer this over [`try_from_bech32m_unchecked`](Self::try_from_bech32m_unchecked) in
    /// security-critical code to prevent cross-protocol confusion attacks.
    pub fn try_from_bech32m(
        s: &str,
        expected_hrp: &str,
    ) -> Result<Self, crate::error::Bech32Error> {
        Ok(Self::from_protected_bytes(zeroize::Zeroizing::new(
            s.try_from_bech32m(expected_hrp)?,
        )))
    }
}

// ConstantTimeEq
#[cfg(feature = "ct-eq")]
impl<T: ?Sized + zeroize::Zeroize> crate::ConstantTimeEq for Dynamic<T>
where
    T: crate::ConstantTimeEq,
{
    fn ct_eq(&self, other: &Self) -> bool {
        self.inner.ct_eq(&other.inner)
    }
}

// Debug
impl<T: ?Sized + zeroize::Zeroize> core::fmt::Debug for Dynamic<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("[REDACTED]")
    }
}

// Clone
#[cfg(feature = "cloneable")]
impl<T: zeroize::Zeroize + crate::CloneableSecret> Clone for Dynamic<T> {
    fn clone(&self) -> Self {
        Self::new(self.inner.clone())
    }
}

// Serialize
#[cfg(feature = "serde-serialize")]
impl<T: zeroize::Zeroize + crate::SerializableSecret> serde::Serialize for Dynamic<T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.inner.serialize(serializer)
    }
}

// Deserialize

/// Default maximum byte length accepted when deserializing `Dynamic<Vec<u8>>` or
/// `Dynamic<String>` via the standard `serde::Deserialize` impl (1 MiB).
///
/// Pass a custom value to [`Dynamic::deserialize_with_limit`] when a different
/// ceiling is required.
///
/// **Important:** this limit is enforced *after* the upstream deserializer has fully
/// materialized the payload. It is a **result-length acceptance bound**, not a
/// pre-allocation DoS guard. For untrusted input, enforce size limits at the
/// transport or parser layer upstream.
#[cfg(feature = "serde-deserialize")]
pub const MAX_DESERIALIZE_BYTES: usize = 1_048_576;

#[cfg(feature = "serde-deserialize")]
impl Dynamic<alloc::vec::Vec<u8>> {
    /// Deserializes into `Dynamic<Vec<u8>>`, rejecting payloads larger than `limit` bytes.
    ///
    /// The standard [`serde::Deserialize`] impl calls this with [`MAX_DESERIALIZE_BYTES`].
    /// Use this method directly when you need a tighter or looser ceiling.
    ///
    /// The intermediate buffer is kept inside a `Zeroizing` wrapper until after the `Box`
    /// allocation completes, guaranteeing zeroization even on OOM panic. Oversized buffers
    /// are also zeroized before the error is returned.
    ///
    /// **Important:** this limit is enforced *after* the upstream deserializer has fully
    /// materialized the payload. It is a **result-length acceptance bound**, not a
    /// pre-allocation DoS guard. For untrusted input, enforce size limits at the
    /// transport or parser layer upstream.
    pub fn deserialize_with_limit<'de, D>(deserializer: D, limit: usize) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let mut buf: zeroize::Zeroizing<alloc::vec::Vec<u8>> =
            zeroize::Zeroizing::new(serde::Deserialize::deserialize(deserializer)?);
        if buf.len() > limit {
            // buf drops here → Zeroizing zeros the oversized buffer before deallocation
            return Err(serde::de::Error::custom(
                "deserialized secret exceeds maximum size",
            ));
        }
        // Only fallible allocation; protected stays live across it for panic-safety
        let mut boxed = Box::<alloc::vec::Vec<u8>>::default();
        core::mem::swap(&mut *boxed, &mut *buf);
        Ok(Self::from(boxed))
    }
}

#[cfg(feature = "serde-deserialize")]
impl Dynamic<String> {
    /// Deserializes into `Dynamic<String>`, rejecting payloads larger than `limit` bytes.
    ///
    /// The standard [`serde::Deserialize`] impl calls this with [`MAX_DESERIALIZE_BYTES`].
    /// Use this method directly when you need a tighter or looser ceiling.
    ///
    /// The intermediate buffer is kept inside a `Zeroizing` wrapper until after the `Box`
    /// allocation completes, guaranteeing zeroization even on OOM panic. Oversized buffers
    /// are also zeroized before the error is returned.
    ///
    /// **Important:** this limit is enforced *after* the upstream deserializer has fully
    /// materialized the payload. It is a **result-length acceptance bound**, not a
    /// pre-allocation DoS guard. For untrusted input, enforce size limits at the
    /// transport or parser layer upstream.
    pub fn deserialize_with_limit<'de, D>(deserializer: D, limit: usize) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let mut buf: zeroize::Zeroizing<alloc::string::String> =
            zeroize::Zeroizing::new(serde::Deserialize::deserialize(deserializer)?);
        if buf.len() > limit {
            // buf drops here → Zeroizing zeros the oversized buffer before deallocation
            return Err(serde::de::Error::custom(
                "deserialized secret exceeds maximum size",
            ));
        }
        // Only fallible allocation; protected stays live across it for panic-safety
        let mut boxed = Box::<alloc::string::String>::default();
        core::mem::swap(&mut *boxed, &mut *buf);
        Ok(Self::from(boxed))
    }
}

#[cfg(feature = "serde-deserialize")]
impl<'de> serde::Deserialize<'de> for Dynamic<alloc::vec::Vec<u8>> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Self::deserialize_with_limit(deserializer, MAX_DESERIALIZE_BYTES)
    }
}

#[cfg(feature = "serde-deserialize")]
impl<'de> serde::Deserialize<'de> for Dynamic<String> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Self::deserialize_with_limit(deserializer, MAX_DESERIALIZE_BYTES)
    }
}

// Zeroize + Drop (now always present with bound)
impl<T: ?Sized + zeroize::Zeroize> zeroize::Zeroize for Dynamic<T> {
    fn zeroize(&mut self) {
        self.inner.zeroize();
    }
}

impl<T: ?Sized + zeroize::Zeroize> Drop for Dynamic<T> {
    fn drop(&mut self) {
        self.zeroize();
    }
}

impl<T: ?Sized + zeroize::Zeroize> zeroize::ZeroizeOnDrop for Dynamic<T> {}