Skip to main content

secure_gate/
lib.rs

1// no_std by default; the `std` feature opts back into the standard library.
2// Verified in CI by cross-building for a bare-metal target.
3#![cfg_attr(not(feature = "std"), no_std)]
4// Forbid unsafe code unconditionally
5#![forbid(unsafe_code)]
6#![warn(missing_docs)]
7
8//! Secure wrappers for secrets with **explicit access** and **mandatory zeroization** — a
9//! `no_std`-compatible, zero-overhead library with audit-friendly access patterns.
10//!
11//! Secrets are **automatically zeroized on drop** (the inner type must implement
12//! [`Zeroize`](zeroize::Zeroize)). While a secret is held in [`Fixed`] or [`Dynamic`],
13//! there is no `Deref` and no `AsRef`: callers reach the inner secret only via
14//! [`RevealSecret`] / [`RevealSecretMut`], and `Debug` on a wrapper always prints
15//! `[REDACTED]`. [`SlotWriter`], which borrows a wrapper's storage rather than holding it,
16//! prints its cursor instead — position, remaining, length — and never the bytes.
17//! Access has two shapes: **borrow** it, or **take** it.
18//! [`with_secret()`](RevealSecret::with_secret) and
19//! [`expose_secret()`](RevealSecret::expose_secret) lend you a reference while the
20//! wrapper keeps ownership and keeps wiping. [`into_inner()`](RevealSecret::into_inner)
21//! transfers ownership: you get the plain value and the protection ends with the call.
22//!
23//! Those two shapes are what the **3-tier access model** in `SECURITY.md` counts in
24//! threes: `with_secret` (Tier 1) and `expose_secret` (Tier 2) are both the borrow
25//! shape, differing only in how tightly the lifetime is pinned, and `into_inner`
26//! (Tier 3) is the take. Two shapes, three volumes — the tiers say how loudly you
27//! have to announce which one you picked, not how many protections there are.
28//!
29//! Extraction is a hand-off, not a third layer of protection. Encoding output is the
30//! one case that keeps a wrapper — [`EncodedSecret`] **does** implement `Deref`, because
31//! its job is to keep an encoded *copy* of the secret wiped until it drops. Ordinary
32//! copies you make of the derefed value (`.to_string()`) are not tracked. See
33//! [Where accident-prevention ends](#where-accident-prevention-ends).
34//!
35//! # Which type should I use?
36//!
37//! | Type | Allocation | Use case | Feature |
38//! |------|-----------|----------|----------|
39//! | [`Fixed<T>`] | Stack | Keys, nonces, tokens — compile-time-known size | Always available |
40//! | [`Dynamic<T>`] | Heap | Passwords, API keys, ciphertexts — variable length | `alloc` (default) |
41//!
42//! Both types share the same [`RevealSecret`] / [`RevealSecretMut`] access API.
43//!
44//! # Quick start
45//!
46//! ```rust
47//! use secure_gate::{Fixed, RevealSecret};
48//!
49//! // Wrap a 32-byte key
50//! let key = Fixed::new([0x42u8; 32]);
51//!
52//! // Tier 1 — scoped access (preferred): secret ref cannot escape the closure
53//! let first = key.with_secret(|bytes| bytes[0]);
54//! assert_eq!(first, 0x42);
55//!
56//! // Tier 2 — direct reference (escape hatch for FFI / third-party APIs)
57//! assert_eq!(key.expose_secret().len(), 32);
58//!
59//! // Debug is always redacted
60//! assert_eq!(format!("{:?}", key), "[REDACTED]");
61//! // key is zeroized when dropped
62//! ```
63//!
64//! ```rust
65//! # #[cfg(feature = "alloc")]
66//! # {
67//! use secure_gate::{Dynamic, RevealSecret};
68//!
69//! let password: Dynamic<String> = Dynamic::new(String::from("hunter2"));
70//! let len = password.with_secret(|s: &String| s.len());
71//! assert_eq!(len, 7);
72//! # }
73//! ```
74//!
75//! ```rust
76//! use secure_gate::{fixed_newtype, RevealSecret};
77//!
78//! fixed_newtype!(pub Aes256Key, 32);
79//!
80//! let key = Aes256Key::new([0xABu8; 32]);
81//! key.with_secret(|b| assert_eq!(b.len(), 32));
82//! ```
83//!
84//! # Module structure
85//!
86//! ```text
87//! secure_gate (lib.rs)
88//! ├── Fixed<T>              ← always available, stack-allocated
89//! ├── Dynamic<T>            ← requires `alloc`, heap-allocated
90//! ├── traits/
91//! │   ├── RevealSecret      ← immutable access (always available)
92//! │   ├── RevealSecretMut   ← mutable access (always available)
93//! │   ├── revealed_secrets/
94//! │   │   └── EncodedSecret     ← zeroizing encoded string wrapper (alloc)
95//! │   ├── ConstantTimeEq    ← ct-eq feature
96//! │   ├── CloneableSecret   ← cloneable feature
97//! │   ├── SerializableSecret← serde-serialize feature
98//! │   ├── encoding/         ← ToHex, ToBase32, ToBase64Url, ToBech32, ToBech32m
99//! │   └── decoding/         ← FromHexStr, FromBase32Str, FromBase64UrlStr, FromBech32Str, FromBech32mStr
100//! ├── macros/               ← fixed_newtype!, dynamic_newtype!
101//! └── error                 ← FromSliceError, HexError, Base32Error, Base64Error, Bech32Error
102//! ```
103//!
104//! All public items are re-exported at the crate root. Use `secure_gate::Fixed`,
105//! not `secure_gate::fixed::Fixed`.
106//!
107//! # Type taxonomy
108//!
109//! | Category | Types | `Deref` to secret? | Purpose |
110//! |----------|-------|-------------------|----------|
111//! | **Secret wrappers** | [`Fixed<T>`], [`Dynamic<T>`] | No — use [`RevealSecret`] | Hold live secrets; `Debug` → `[REDACTED]` |
112//! | **Output wrapper** | [`EncodedSecret`] | Yes — yields `&str`; copies you make are yours, the buffer stays the wrapper's | Holds encoded output, wiped on drop |
113//! | **Borrowed slot cursor** | [`SlotWriter`] | No — it writes, it does not read out | Appends into a slot a sized `new_with` handed out; `Debug` → cursor state only, never bytes |
114//! | **Opt-in markers** | [`CloneableSecret`], [`SerializableSecret`] | — (no methods) | Implement on inner type `T` to unlock gated impls |
115//!
116//! `CloneableSecret` and `SerializableSecret` are implemented on the **inner type `T`**,
117//! not on `Fixed<T>` or `Dynamic<T>` directly. [`EncodedSecret`] is not a secret
118//! wrapper and does not interact with these markers.
119//!
120//! # Where accident-prevention ends
121//!
122//! This crate carries two separate obligations, and they end in different places.
123//!
124//! **Accidents must not compile.** This applies while the secret is held in
125//! [`Fixed`]/[`Dynamic`], and it ends at the named extraction. `into_inner` and
126//! `EncodedSecret::into_inner` are the exits that transfer ownership: you typed a
127//! name, the call site is grep-able, and the wrapper is consumed. `expose_secret` is
128//! a named *borrow* — the wrapper still owns the secret and still wipes it — but it
129//! hands out a reference with no lifetime bound to a call site, so it is audited
130//! alongside them.
131//!
132//! **Documented behavior must be accurate.** This never ends, and it is why the
133//! taxonomy table above says `Deref: Yes` for the output wrapper.
134//!
135//! What [`EncodedSecret`] still guarantees: the `String` it owns is zeroized on drop,
136//! and its `Debug` prints `[REDACTED]`. What it does not guarantee: copies you make
137//! through `Deref` are ordinary values. `str::to_string()` and `.to_owned()` both
138//! produce untracked plaintext. That is what extraction is for — the crate is not
139//! trying to follow the bytes into your TLS stack. `into_inner` gives up even the first
140//! guarantee, by design: it is the named end of protection.
141//!
142//! Two consequences worth knowing:
143//!
144//! - `format!("{:?}", &*encoded)` prints the encoded secret. Redaction lives on the
145//!   wrapper, not on `str`; dereferencing first opts out of it.
146//! - [`EncodedSecret::into_zeroizing`] returns a `Zeroizing<String>`, whose `Debug` is
147//!   **not** redacted. It is a deliberate hand-off to a foreign type, not an equivalent
148//!   wrapper.
149//!
150//! # Import paths
151//!
152//! ```rust
153//! // ✅ Correct — always import from the crate root
154//! use secure_gate::{Fixed, RevealSecret};
155//!
156//! // ❌ Wrong — these internal paths compile but are not the public API
157//! // use secure_gate::traits::reveal_secret::RevealSecret;
158//! // use secure_gate::traits::encoding::hex::ToHex;
159//! ```
160//!
161//! # Method resolution: wrapper methods vs trait methods
162//!
163//! Encoding methods exist at **two levels** — both produce identical results:
164//!
165//! | Call style | Example | Appears in audit sweep? |
166//! |-----------|---------|------------------------|
167//! | **Wrapper trait impl** (ergonomic) | `key.to_hex()` (needs `use secure_gate::ToHex`) | No — grep for `to_hex` directly |
168//! | **Trait via scoped access** (audit-friendly) | `key.with_secret(\|b\| b.to_hex())` | Yes — `with_secret` is grep-able |
169//!
170//! Both levels are impls of the **same** trait ([`ToHex`], [`ToBase32`], [`ToBase64Url`],
171//! [`ToBech32`], [`ToBech32m`]): a blanket impl covers the raw bytes inside
172//! `with_secret`, and per-wrapper impls on `Fixed<[u8; N]>` / `Dynamic<Vec<u8>>`
173//! delegate through `with_secret` internally. One trait also means one bound:
174//! `fn fingerprint<S: ToHex>(s: &S)` accepts wrappers and forwarding newtypes
175//! alike.
176//!
177//! # Feature flags
178//!
179//! | Feature | Default | Description |
180//! |---------|---------|-------------|
181//! | `alloc` | **yes** | Heap types ([`Dynamic<T>`]), `Vec`/`String` zeroization |
182//! | `std` | no | Full `std` support (implies `alloc`) |
183//! | | | **Cryptographic** |
184//! | `ct-eq` | no | [`ConstantTimeEq`] via `subtle` — timing-safe comparison |
185//! | `rand` | no | `from_random()` / `from_rng()` — `no_std` for [`Fixed`] |
186//! | | | **Serialization** |
187//! | `serde-serialize` | no | Serde `Serialize` (requires [`SerializableSecret`] marker) |
188//! | `serde-deserialize` | no | Serde `Deserialize` with 1 MiB default limit |
189//! | `serde` | no | Both directions |
190//! | | | **Encoding** |
191//! | `encoding-hex` | no | [`ToHex`] / [`FromHexStr`] via `base16ct` (constant-time) |
192//! | `encoding-base32` | no | [`ToBase32`] / [`FromBase32Str`] via `base32ct` (constant-time) |
193//! | `encoding-base64` | no | [`ToBase64Url`] / [`FromBase64UrlStr`] via `base64ct` (constant-time) |
194//! | `encoding-bech32` | no | [`ToBech32`] / [`FromBech32Str`] (BIP-173) **and** [`ToBech32m`] / [`FromBech32mStr`] (BIP-350); `_sized::<N>` for a caller-chosen code length |
195//! | `encoding` | no | All encoding features |
196//! | | | **Meta** |
197//! | `cloneable` | no | [`CloneableSecret`] opt-in cloning |
198//! | `full` | no | Everything except `std` |
199//!
200//! # What's available without `alloc`?
201//!
202//! With `default-features = false`:
203//! - [`Fixed<T>`], [`RevealSecret`], [`RevealSecretMut`]
204//! - [`Fixed::try_from_hex`](Fixed::try_from_hex), [`Fixed::try_from_base32`](Fixed::try_from_base32),
205//!   [`Fixed::try_from_base64url`](Fixed::try_from_base64url),
206//!   [`Fixed::try_from_bech32`](Fixed::try_from_bech32), [`Fixed::try_from_bech32m`](Fixed::try_from_bech32m)
207//!   (no-alloc stack-based decoding)
208//! - [`fixed_newtype!`] (distinct nominal types — two keys of the same size that
209//!   the compiler keeps apart); a plain `type` alias over [`Fixed<T>`] needs nothing
210//!   at all
211//! - [`FromSliceError`]
212//!
213//! **Not** available without `alloc`: [`Dynamic<T>`], [`EncodedSecret`],
214//! encoding traits ([`ToHex`], etc.), decoding traits ([`FromHexStr`], etc.),
215//! [`dynamic_newtype!`], serde support.
216//!
217//! # `no_std`
218//!
219//! `no_std` compatible (`#![no_std]` unless the `std` feature is enabled — verified in CI
220//! by cross-building for `thumbv7em-none-eabihf`). [`Fixed<T>`] works without `alloc`.
221//! Enable `alloc` (default) for [`Dynamic<T>`]. For pure stack / embedded builds, use
222//! `default-features = false`. MSRV: **1.70** (Rust edition 2021 — the MSRV 1.70 line, same API as `main`).
223//!
224//! One caveat: the `rand` feature compiles without `std` or `alloc`, but
225//! [`Fixed::from_random`] relies on `getrandom`, which needs a platform entropy backend.
226//! On bare-metal targets you must configure one (see the `getrandom` crate's
227//! "custom backend" documentation); without it, builds enabling `rand` fail at link
228//! time on such targets. [`Fixed::from_rng`] with a caller-supplied RNG has no such
229//! requirement.
230//!
231//! # Security
232//!
233//! This crate has **not** undergone an independent security audit. No unsafe code —
234//! enforced with `#![forbid(unsafe_code)]`. Prefer scoped access ([`RevealSecret::with_secret`])
235//! over direct references. Encoders return [`EncodedSecret`], which stays wiped until it
236//! drops; `EncodedSecret::into_inner` is the named call that ends that. See
237//! [SECURITY.md](https://github.com/Slurp9187/secure-gate/blob/release/0.8/SECURITY.md)
238//! for the full threat model.
239//!
240//! # Inherent Rust Limitations
241//!
242//! Three universal limits apply to any in-memory secret library in Rust (and in
243//! C, C++, and Go) — `secure-gate` documents them honestly rather than
244//! overclaiming:
245//!
246//! - **Stack-move residue**: moving a [`Fixed<T>`] by value leaves the prior stack
247//!   slot uncleared until a later frame overwrites it. Prefer
248//!   [`Fixed::new_with`](Fixed::new_with), pass by reference, or use
249//!   [`Dynamic<T>`] for long-lived secrets.
250//! - **Heap-reallocation residue**: `Vec` / `String` realloc frees the old buffer
251//!   unzeroed. Pre-size, use `Dynamic<[u8; N]>` (boxed array — no realloc surface),
252//!   or install a zero-on-dealloc global allocator such as `zeroizing-alloc` at
253//!   the binary level.
254//! - **Swap / core dumps**: process memory paged to disk or written on crash is
255//!   outside any in-process library's reach. Use OS facilities (`mlock`,
256//!   encrypted swap, disabled core dumps).
257//!
258//! Full discussion in
259//! [SECURITY.md § Inherent Rust Limitations](https://github.com/Slurp9187/secure-gate/blob/release/0.8/SECURITY.md#inherent-rust-limitations).
260//!
261//! See the [README](https://github.com/Slurp9187/secure-gate/blob/release/0.8/README.md) and
262//! [SECURITY.md](https://github.com/Slurp9187/secure-gate/blob/release/0.8/SECURITY.md) for full details.
263
264#[cfg(feature = "alloc")]
265extern crate alloc;
266
267// Documentation-only. Several doc comments link to `std` items that this crate touches
268// through gated impls (`io::Write` on `Dynamic<Vec<u8>>` and on `SlotWriter`, `io::Read`
269// on `DynamicReader`). Those links are correct and resolve on docs.rs, which builds with
270// `all-features`. They do not resolve under `--features=full`, which this branch's rustdoc
271// job builds and which does *not* enable `std`, because without that feature the name
272// `std` is not in scope at all and rustdoc has nothing to point at. This brings it into
273// scope for doc builds only: it is `cfg(doc)`, so it affects no real build, `no_std` or
274// otherwise, and it makes the links resolve in every feature combination rather than only
275// the one docs.rs happens to use.
276#[cfg(doc)]
277extern crate std;
278
279#[cfg(feature = "alloc")]
280mod dynamic;
281
282mod slot_writer;
283
284/// Fixed-size secret wrapper types - always available with zero dependencies.
285/// These provide fundamental secure storage abstractions for fixed-size data.
286mod fixed;
287
288/// Centralized error types - always available.
289mod error;
290
291/// Core traits for wrapper polymorphism - always available.
292pub mod traits;
293
294/// Implementation detail of the `*_newtype!` macros — not a public API.
295///
296/// Generated code needs to name `Zeroize`, `serde` traits, and `alloc` types
297/// without requiring the caller to depend on those crates directly, and
298/// `::alloc::…` paths do not resolve in an ordinary `std` crate. Re-exporting
299/// them here keeps expansions self-contained via `$crate::__private::…`.
300///
301/// Semver-exempt: items here may change or disappear in any release.
302#[doc(hidden)]
303pub mod __private {
304    #[cfg(feature = "alloc")]
305    pub use alloc::{boxed::Box, string::String, vec::Vec};
306    #[cfg(feature = "rand")]
307    pub use rand::{TryCryptoRng, TryRngCore};
308    #[cfg(feature = "serde-deserialize")]
309    pub use serde::{Deserialize, Deserializer};
310    #[cfg(feature = "serde-serialize")]
311    pub use serde::{Serialize, Serializer};
312    pub use zeroize::{Zeroize, ZeroizeOnDrop};
313}
314
315/// Heap-allocated secret wrapper with explicit access and automatic zeroization on drop.
316///
317/// Variable-length secrets (passwords, API keys, ciphertexts). Inner type must implement
318/// `Zeroize`. Secret bytes live on the heap only — never on the stack. Requires `alloc`.
319///
320/// See [`Fixed<T>`] for the stack-allocated alternative.
321///
322/// ```rust
323/// # #[cfg(feature = "alloc")]
324/// # {
325/// use secure_gate::{Dynamic, RevealSecret};
326///
327/// let pw: Dynamic<String> = Dynamic::new(String::from("hunter2"));
328/// assert_eq!(pw.with_secret(|s: &String| s.len()), 7);
329/// assert_eq!(format!("{:?}", pw), "[REDACTED]");
330/// # }
331/// ```
332#[cfg(feature = "alloc")]
333pub use dynamic::Dynamic;
334
335/// Cursor-like reader over [`Dynamic<Vec<u8>>`] — see [`Dynamic::as_reader`].
336#[cfg(feature = "std")]
337pub use dynamic::DynamicReader;
338
339/// Append-shaped writing into the fixed slot handed to a sized `new_with`.
340///
341/// The sized constructors hand out a slot whose length is already decided, which is what
342/// makes growth, and therefore the reallocation hazard, inexpressible. `SlotWriter`
343/// restores the append shape on top of that, so concatenating a wire format does not mean
344/// writing offsets by hand. [`push_slice`](SlotWriter::push_slice) panics on overrun and
345/// leaves the slot untouched; the `std`-gated `std::io::Write` path cannot do that and
346/// stay inside `Write`'s contract, so it truncates and reports the refusal on a later
347/// call. `Debug` shows the cursor — position, remaining, length — and never the bytes.
348pub use slot_writer::SlotWriter;
349
350#[cfg(all(feature = "alloc", feature = "serde-deserialize"))]
351/// Default maximum byte length for `Dynamic<Vec<u8>>` / `Dynamic<String>` deserialization (1 MiB).
352///
353/// The standard `serde::Deserialize` impl for both types rejects payloads exceeding this value.
354/// Pass a custom ceiling to [`Dynamic::deserialize_with_limit`] when a different limit is needed.
355///
356/// **Important:** this limit is enforced *after* the upstream deserializer has fully
357/// materialized the payload. It is a **result-length acceptance bound**, not a
358/// pre-allocation DoS guard. For untrusted input, enforce size limits at the
359/// transport or parser layer upstream.
360pub use dynamic::MAX_DESERIALIZE_BYTES;
361
362/// Stack-allocated secret wrapper with explicit access and automatic zeroization on drop.
363///
364/// Fixed-size secrets (keys, nonces, tokens). Inner type must implement `Zeroize`.
365/// Always available — works without `alloc`. Prefer [`new_with`](Fixed::new_with) over
366/// [`new`](Fixed::new) when minimizing stack residue matters.
367///
368/// See [`Dynamic<T>`] for the heap-allocated alternative.
369///
370/// ```rust
371/// use secure_gate::{Fixed, RevealSecret};
372///
373/// let key = Fixed::new([0xABu8; 32]);
374/// key.with_secret(|b| assert_eq!(b[0], 0xAB));
375/// assert_eq!(format!("{:?}", key), "[REDACTED]");
376/// ```
377pub use fixed::Fixed;
378
379/// Marker trait that opts a secret type into cloning. No methods — gates the `Clone`
380/// impl on [`Fixed`] and [`Dynamic`]. Each clone is independently zeroized on drop,
381/// but increases the in-memory exposure surface. Requires `cloneable` feature.
382///
383/// Implement this on your inner type `T`; `Fixed<T>` and `Dynamic<T>` then gain the
384/// gated `Clone` impl automatically. **This marker is deliberately not implemented by
385/// default** on `Fixed<T>` or `Dynamic<T>` — cloning is an opt-in risk that must be
386/// explicitly enabled. Without the `cloneable` feature this type does not exist at all.
387///
388///
389/// **Coherence note:** Rust's orphan rule prevents downstream crates from implementing
390/// this marker for foreign types such as `String`, `Vec<u8>`, or `[u8; N]` — so
391/// `Dynamic<String>` and `Fixed<[u8; N]>` themselves can never become `Clone`. To opt
392/// a secret into cloning, define a newtype inner type in your crate (deriving
393/// `Zeroize` and `Clone`) and implement the marker on it. This is intentional: it keeps
394/// every cloneable secret type visible in *your* code. See the trait-level docs for a
395/// worked example.
396/// See also [`SerializableSecret`] (the other opt-in marker trait).
397#[cfg(feature = "cloneable")]
398pub use traits::CloneableSecret;
399
400/// Constant-time equality for secrets — prevents timing side-channel attacks.
401///
402/// Provides [`ct_eq()`](ConstantTimeEq::ct_eq) via the `subtle` crate. `==` is
403/// **deliberately not implemented** on [`Fixed`] / [`Dynamic`] — always use `ct_eq`.
404/// Requires `ct-eq` feature.
405///
406/// ```rust
407/// # #[cfg(feature = "ct-eq")]
408/// # {
409/// use secure_gate::{Fixed, ConstantTimeEq};
410///
411/// let a = Fixed::new([1u8; 32]);
412/// let b = Fixed::new([1u8; 32]);
413/// assert!(a.ct_eq(&b));
414/// # }
415/// ```
416#[cfg(feature = "ct-eq")]
417pub use traits::ConstantTimeEq;
418
419/// Explicit immutable access to secret contents (3-tier access model).
420///
421/// - **Tier 1** (preferred): [`with_secret()`](RevealSecret::with_secret) — scoped closure,
422///   borrow cannot escape.
423/// - **Tier 2** (escape hatch): [`expose_secret()`](RevealSecret::expose_secret) — direct
424///   `&T` reference for FFI / third-party APIs.
425/// - **Tier 3** (consumption): [`into_inner()`](RevealSecret::into_inner) — transfers
426///   ownership of the plain value; protection ends with the call.
427///
428/// Length metadata lives in the separate [`SecretLen`] trait. See
429/// [`RevealSecretMut`] for the mutable counterpart.
430// Kept as a separate `use` from `SecretLen` on purpose: rustdoc 1.70 (the 0.8
431// line's MSRV toolchain) ICEs resolving intra-doc links on a grouped
432// `pub use a::{B, C};` re-export, and the two lines share this file.
433pub use traits::RevealSecret;
434
435/// Length metadata for secrets whose inner type has a meaningful length.
436///
437/// [`len()`](SecretLen::len) / [`byte_len()`](SecretLen::byte_len) /
438/// [`is_empty()`](SecretLen::is_empty) do not expose contents, but length itself
439/// can be sensitive for variable-length secrets — see the trait's Security
440/// section. Implemented for `Fixed<[T; N]>`, `Dynamic<String>`, and
441/// `Dynamic<Vec<T>>`; deliberately not for custom inner types.
442pub use traits::SecretLen;
443
444/// Explicit mutable access to secret contents.
445///
446/// Extends [`RevealSecret`]. Prefer [`with_secret_mut()`](RevealSecretMut::with_secret_mut)
447/// (Tier 1) over [`expose_secret_mut()`](RevealSecretMut::expose_secret_mut) (Tier 2).
448/// Implemented by [`Fixed`], [`Dynamic`], and the generated newtypes. [`EncodedSecret`]
449/// implements neither this nor [`RevealSecret`] — it is an output wrapper, not a secret one.
450pub use traits::RevealSecretMut;
451
452/// Placeholder values left behind by [`RevealSecret::into_inner`] (Tier 3 access).
453///
454/// When `into_inner` moves the real secret out of a wrapper, it must leave *something*
455/// behind for the wrapper's `Drop` impl to zeroize. `SentinelValue::sentinel_value()`
456/// produces that inert placeholder (an all-default array, empty `String`, or empty
457/// `Vec`). Implemented for `[T; N]` (any `N`, `T: Default`), `String`, and `Vec<T>`.
458///
459/// Implement this for your own inner types to make `into_inner` available on wrappers
460/// around them. A sentinel must never contain secret material.
461///
462/// Leaving it unimplemented is a deliberate position, not a gap: `into_inner` is then
463/// uncallable for that inner type, so a secret with no safe inert placeholder simply
464/// cannot be extracted by ownership transfer. `with_secret` and `expose_secret` still
465/// work. That is the safe default rather than a missing feature.
466pub use traits::SentinelValue;
467
468/// Asserts that an inner type owns no buffer whose capacity can change.
469///
470/// Required by [`Fixed::new`], which is what makes `SECURITY.md`'s claim that `Fixed<T>`
471/// "has no realloc surface" true rather than aspirational. Before this bound existed,
472/// `Fixed<Vec<u8>>`, `Fixed<String>` and `fixed_newtype!(pub Name, generic Vec<u8>)` all
473/// compiled, and measured, they abandoned an unwiped buffer holding the whole secret on
474/// any capacity change — the same weakness `Dynamic` documents, minus `Dynamic`'s
475/// safe-growth `std::io::Write` path.
476///
477/// Implemented for the primitives, `[T; N]` for any `N`, tuples up to four elements, and
478/// `Option<T>`. Nothing heap-owning is implemented: `Vec<T>`, `String` and `Box<[T]>` are
479/// all absent, because the residue does not need a capacity change — replacing the whole
480/// value abandons the allocation too, measured at 1024 of 1024 bytes through a
481/// `Fixed<Box<[u8]>>`. For a heap-backed secret use [`Dynamic`], which documents the
482/// residue and offers the one safe growth path.
483///
484/// A custom inner type writes `impl FixedStorage for MyKey {}`. Like [`CloneableSecret`],
485/// the compiler checks that you made the claim, not that it is true — see the trait docs
486/// for the test to apply and for why an assertion is the right trade here.
487pub use traits::FixedStorage;
488
489/// Encoded string **output wrapper** for zeroizing encoded output.
490///
491/// This is an **output wrapper** — it exists *only* to keep encoded data zeroized until
492/// it drops. It is **not** a secret wrapper like [`Fixed`]/[`Dynamic`] and does not
493/// accept [`CloneableSecret`] or [`SerializableSecret`] markers.
494///
495/// Returned by every encoding method (`to_hex`, `to_hex_upper`, `to_base32`,
496/// `to_base64url`, `try_to_bech32`, `try_to_bech32m`, and the `_sized::<N>` forms of
497/// the last two — only bech32 and bech32m take a code length).
498/// Wraps `Zeroizing<String>` with `Debug` → `[REDACTED]`. Its one accessor is
499/// `Deref<Target = str>`; there are deliberately no `AsRef` impls, because `Deref`
500/// already opens that door. Deliberately **no** `Display` either: `{}` on this type is
501/// a compile error, so `Debug` redaction cannot mislead a caller into logging the
502/// encoded secret. Write it out with `&*encoded`.
503///
504/// Use [`into_inner()`](EncodedSecret::into_inner) to extract a plain `String`
505/// (ends zeroization) or [`into_zeroizing()`](EncodedSecret::into_zeroizing) to keep
506/// the wiping. `into_zeroizing` is a partial downgrade: zeroize-on-drop survives, the
507/// redacted `Debug` does not, because `zeroize::Zeroizing` derives its own.
508///
509/// Requires `alloc` feature.
510#[cfg(feature = "alloc")]
511pub use traits::EncodedSecret;
512
513/// Marker trait that opts a secret type into Serde serialization. No methods — gates the
514/// `Serialize` impl on [`Fixed`] and [`Dynamic`]. Serialization exposes the full secret;
515/// audit every impl. Requires `serde-serialize` feature.
516///
517/// **`Deserialize` does NOT require this marker** — it is gated separately by the
518/// `serde-deserialize` feature with its own impls on the wrapper types directly. This
519/// marker controls `Serialize` only.
520///
521/// Implement this on your inner type `T`; `Fixed<T>` and `Dynamic<T>` then gain the
522/// gated `Serialize` impl automatically. **This marker is deliberately not implemented
523/// by default** on `Fixed<T>` or `Dynamic<T>` — serialization is an opt-in risk that
524/// must be explicitly enabled. Without the `serde-serialize` feature this type does not
525/// exist at all.
526///
527///
528/// **Coherence note:** Rust's orphan rule prevents downstream crates from implementing
529/// this marker for foreign types such as `String`, `Vec<u8>`, or `[u8; N]` — so
530/// `Fixed<[u8; N]>` and `Dynamic<String>` themselves can never become `Serialize`. To
531/// opt a secret into serialization, define a newtype inner type in your crate (deriving
532/// `Zeroize` and `Serialize`) and implement the marker on it. This is intentional: it
533/// keeps every serializable secret type visible in *your* code. See the trait-level
534/// docs for a worked example.
535/// See also [`CloneableSecret`] (the other opt-in marker trait).
536#[cfg(feature = "serde-serialize")]
537pub use traits::SerializableSecret;
538
539// Newtype macros (`dynamic_newtype!` needs `alloc`)
540mod macros;
541
542/// Decodes Base32 strings (`&str`) to `Vec<u8>`. Blanket impl for `AsRef<str>`.
543/// Requires `encoding-base32` + `alloc`. See [`ToBase32`] for the encoding counterpart.
544#[cfg(all(feature = "encoding-base32", feature = "alloc"))]
545pub use traits::FromBase32Str;
546
547/// Decodes Base64url strings (`&str`) to `Vec<u8>`. Blanket impl for `AsRef<str>`.
548/// Requires `encoding-base64` + `alloc`. See [`ToBase64Url`] for the encoding counterpart.
549#[cfg(all(feature = "encoding-base64", feature = "alloc"))]
550pub use traits::FromBase64UrlStr;
551
552/// Decodes Bech32 (BIP-173) strings to `Vec<u8>` with HRP validation.
553/// Requires `encoding-bech32` + `alloc`. See [`ToBech32`] for the encoding counterpart.
554#[cfg(all(feature = "encoding-bech32", feature = "alloc"))]
555pub use traits::FromBech32Str;
556
557/// Decodes Bech32m (BIP-350) strings to `Vec<u8>` with HRP validation.
558/// Requires `encoding-bech32` + `alloc`. See [`ToBech32m`] for the encoding counterpart.
559#[cfg(all(feature = "encoding-bech32", feature = "alloc"))]
560pub use traits::FromBech32mStr;
561
562/// Decodes hex strings (`&str`) to `Vec<u8>`. Blanket impl for `AsRef<str>`.
563/// Requires `encoding-hex` + `alloc`. See [`ToHex`] for the encoding counterpart.
564#[cfg(all(feature = "encoding-hex", feature = "alloc"))]
565pub use traits::FromHexStr;
566
567/// Encodes byte data as Base32 strings (RFC 4648 §6, uppercase, no padding).
568/// Blanket impl for `AsRef<[u8]> + `[`EncodableBytes`]. Returns [`EncodedSecret`].
569/// Requires `encoding-base32` + `alloc`.
570/// See [`FromBase32Str`] for the decoding counterpart.
571#[cfg(all(feature = "encoding-base32", feature = "alloc"))]
572pub use traits::ToBase32;
573
574/// Encodes byte data as Base64url strings (RFC 4648, URL-safe, no padding).
575/// Blanket impl for `AsRef<[u8]> + `[`EncodableBytes`]. Returns [`EncodedSecret`].
576/// Requires `encoding-base64` + `alloc`.
577/// See [`FromBase64UrlStr`] for the decoding counterpart.
578#[cfg(all(feature = "encoding-base64", feature = "alloc"))]
579pub use traits::ToBase64Url;
580
581/// Encodes byte data as Bech32 (BIP-173) strings. Blanket impl for
582/// `AsRef<[u8]> + `[`EncodableBytes`]; returns `Result<`[`EncodedSecret`]`, _>`.
583/// The plain methods use [`BECH32_CODE_LENGTH`]; `try_to_bech32_sized::<N>` takes the
584/// code length as a parameter. Requires `encoding-bech32` + `alloc`.
585/// See [`FromBech32Str`] for the decoding counterpart.
586#[cfg(all(feature = "encoding-bech32", feature = "alloc"))]
587pub use traits::ToBech32;
588
589/// Encodes byte data as Bech32m (BIP-350) strings. Blanket impl for
590/// `AsRef<[u8]> + `[`EncodableBytes`]; returns `Result<`[`EncodedSecret`]`, _>`.
591/// The plain methods use [`BECH32_CODE_LENGTH`]; `try_to_bech32m_sized::<N>` takes the
592/// code length as a parameter. Requires `encoding-bech32` + `alloc`.
593/// See [`FromBech32mStr`] for the decoding counterpart.
594#[cfg(all(feature = "encoding-bech32", feature = "alloc"))]
595pub use traits::ToBech32m;
596
597/// Opt-in marker for byte-shaped encoding inputs. Every `To*` trait is blanket
598/// implemented for `AsRef<[u8]> + EncodableBytes`; the second bound keeps string-shaped
599/// types out, so an already-encoded value cannot be silently encoded again. Implement it
600/// for your own byte newtype to make it encodable.
601#[cfg(feature = "encoding-bech32")]
602pub use traits::Case;
603
604#[cfg(any(
605    feature = "encoding-hex",
606    feature = "encoding-base32",
607    feature = "encoding-base64",
608    feature = "encoding-bech32",
609))]
610pub use traits::EncodableBytes;
611
612/// Bech32 (BIP-173) checksum with a caller-chosen code length. `N` caps the length of
613/// the whole encoded string and never enters the checksum. Above [`BECH32_CODE_LENGTH`]
614/// the BCH error-detection guarantee no longer holds - see the type docs.
615// Kept as separate `use` statements on purpose: rustdoc 1.70 (this line's MSRV
616// toolchain) ICEs resolving intra-doc links on a grouped `pub use a::{B, C};`
617// re-export — the same bug already worked around for `SecretLen` above.
618#[cfg(feature = "encoding-bech32")]
619pub use traits::Bech32Sized;
620
621/// The BIP-173 checksum at the default code length, used by every non-`_sized` method.
622#[cfg(feature = "encoding-bech32")]
623pub use traits::Bech32Standard;
624
625/// Bech32m (BIP-350) checksum with a caller-chosen code length - the bech32m twin of
626/// [`Bech32Sized`], with the same rules and the same guarantee boundary.
627#[cfg(feature = "encoding-bech32")]
628pub use traits::Bech32mSized;
629
630/// The BIP-350 checksum at the default code length, used by every non-`_sized` method.
631#[cfg(feature = "encoding-bech32")]
632pub use traits::Bech32mStandard;
633
634/// The bech32 BCH code length (1023) used by every non-`_sized` method.
635#[cfg(feature = "encoding-bech32")]
636pub use traits::BECH32_CODE_LENGTH;
637
638/// Sizes an `N` for the `_sized` methods from an HRP length and a payload byte count.
639#[cfg(feature = "encoding-bech32")]
640pub use traits::bech32_code_length;
641
642/// Encodes byte data as hexadecimal strings (constant-time via `base16ct`).
643/// Blanket impl for `AsRef<[u8]> + `[`EncodableBytes`]. Provides `to_hex()` and
644/// `to_hex_upper()`, both returning [`EncodedSecret`].
645/// Requires `encoding-hex` + `alloc`.
646/// See [`FromHexStr`] for the decoding counterpart.
647#[cfg(all(feature = "encoding-hex", feature = "alloc"))]
648pub use traits::ToHex;
649
650/// Marker trait for types that support secure decoding (`AsRef<str>`). No methods —
651/// nothing bounds on it — the `From*Str` blankets are plain `AsRef<str>`. Retained for
652/// backwards compatibility; the 0.9 line removed it.
653#[cfg(any(
654    feature = "encoding-hex",
655    feature = "encoding-base32",
656    feature = "encoding-base64",
657    feature = "encoding-bech32",
658))]
659pub use traits::SecureDecoding;
660
661/// Vestigial marker for byte-shaped types (`AsRef<[u8]>`). No methods, and nothing
662/// bounds on it — the `To*` blankets are gated by [`EncodableBytes`]. Retained for
663/// backwards compatibility; the 0.9 line removed it.
664#[cfg(any(
665    feature = "encoding-hex",
666    feature = "encoding-base32",
667    feature = "encoding-base64",
668    feature = "encoding-bech32",
669))]
670pub use traits::SecureEncoding;
671
672/// Errors from Bech32 (BIP-173) and Bech32m (BIP-350) decoding.
673/// Variant shapes are identical in debug and release builds; no secret material
674/// (payload bytes, HRP strings) is ever carried in an error.
675#[cfg(feature = "encoding-bech32")]
676pub use error::Bech32Error;
677
678/// Errors from Base32 (RFC 4648 §6, uppercase, unpadded) decoding. Variant shapes are
679/// identical in debug and release builds; only numeric length metadata is carried.
680#[cfg(feature = "encoding-base32")]
681pub use error::Base32Error;
682
683/// Errors from Base64url decoding. Variant shapes are identical in debug and
684/// release builds; only numeric length metadata is carried.
685#[cfg(feature = "encoding-base64")]
686pub use error::Base64Error;
687
688/// Errors from hex decoding. Variant shapes are identical in debug and
689/// release builds; only numeric length metadata is carried.
690#[cfg(feature = "encoding-hex")]
691pub use error::HexError;
692
693/// Error returned when a byte slice cannot be converted to `Fixed<[u8; N]>` due to
694/// length mismatch. Produced by `Fixed::try_from(&[u8])`.
695pub use error::FromSliceError;
696
697// The README's examples are compiled and run by `cargo test --doc`, so they cannot
698// silently rot. `cfg(doctest)` is set only while rustdoc *collects doctests* — never
699// while it *builds documentation* — so this item never reaches docs.rs or `cargo doc`
700// output, and the README is not duplicated onto the crate page.
701//
702// Gated on `full` as well: the README documents the fully-featured crate, so its
703// examples use `alloc` and the encoding traits unconditionally. Without this gate the
704// `--no-default-features` doctest job in CI would fail on imports the README does not
705// feature-gate. CI's `--features full` and `--all-features` entries do run them.
706//
707// It must live at the end of the file: an item here would otherwise sit ahead of the
708// `//!` crate docs above, which is not allowed.
709#[cfg(all(doctest, feature = "full"))]
710#[doc = include_str!("../README.md")]
711pub struct ReadmeDoctests;