Skip to main content

auth_framework/storage/
encryption.rs

1use crate::errors::{AuthError, Result};
2use crate::storage::{AuthStorage, SessionData};
3use crate::tokens::AuthToken;
4use aes_gcm::{
5    Aes256Gcm, Key, KeyInit, Nonce,
6    aead::{Aead, Payload},
7};
8use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
9use serde::{Deserialize, Serialize};
10use std::collections::HashMap;
11use std::env;
12use std::fs;
13use std::time::Duration;
14use zeroize::Zeroize;
15
16/// Serializes the tests in this crate's lib-unit-test binary that
17/// EXPLICITLY read or write `AUTH_STORAGE_ENCRYPTION_KEY`/
18/// `AUTH_STORAGE_ENCRYPTION_KEYS_FILE` via this lock, since those are
19/// process-global state shared across all tests running in parallel
20/// threads within one `cargo test --lib` invocation. Acquire this (and
21/// clean up the env var via [`EncryptionEnvGuard`], not a bare
22/// `set_var`/`remove_var` pair) in any new test that touches those
23/// variables.
24///
25/// **Not a guarantee every such test already does** -- some pre-existing
26/// tests elsewhere in this crate build a persistent storage backend
27/// through the real factory (and therefore read these env vars via
28/// [`StorageEncryption::from_env`]) without taking this lock first; that
29/// gap predates this lock and isn't closed by introducing it.
30/// A `tokio::sync::Mutex`, not `std::sync::Mutex`, because several callers
31/// (in `#[tokio::test]` functions) need to hold this guard across `.await`
32/// points -- use `.lock().await` there, or `.blocking_lock()` in a plain
33/// (non-async) `#[test]`.
34#[cfg(test)]
35pub(crate) static TEST_ENCRYPTION_ENV_LOCK: tokio::sync::Mutex<()> =
36    tokio::sync::Mutex::const_new(());
37
38/// RAII guard that sets `AUTH_STORAGE_ENCRYPTION_KEY` for the lifetime of
39/// the guard and removes it on drop -- including on an early return or a
40/// panic (e.g. from an `assert!`/`.unwrap()` failure), unlike a bare
41/// `set_var` at the top of a test and a `remove_var` at the bottom, which
42/// leaks the variable if the test fails before reaching that last line.
43/// Callers should hold [`TEST_ENCRYPTION_ENV_LOCK`] for the guard's entire
44/// lifetime.
45#[cfg(test)]
46pub(crate) struct EncryptionEnvGuard;
47
48#[cfg(test)]
49impl EncryptionEnvGuard {
50    pub(crate) fn set(key: &str) -> Self {
51        // SAFETY: sound against every caller that ALSO takes
52        // `TEST_ENCRYPTION_ENV_LOCK`; NOT sound otherwise (see the
53        // lock's own doc for which pre-existing tests don't).
54        unsafe {
55            std::env::set_var("AUTH_STORAGE_ENCRYPTION_KEY", key);
56            std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE");
57        }
58        Self
59    }
60}
61
62#[cfg(test)]
63impl Drop for EncryptionEnvGuard {
64    fn drop(&mut self) {
65        // SAFETY: see `EncryptionEnvGuard::set` -- the same lock is held
66        // for this guard's entire lifetime, including this drop.
67        unsafe {
68            std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY");
69        }
70    }
71}
72
73/// Current envelope format version. Bumped whenever the envelope's fields
74/// or decryption rules change in a way that needs disambiguating from
75/// older data still on disk.
76///
77/// * `0` -- the original public `EncryptedStorage`: no `key_id`, no AAD.
78/// * `1` -- versioned `key_id`; AAD is the bare storage key, so the
79///   envelope's own metadata (`v`, `key_id`, `algorithm`) is NOT
80///   authenticated.
81/// * `2` -- AAD binds the metadata too (see [`bound_aad`]).
82///
83/// Versions below the current one are *legacy*: readable only behind the
84/// `allow_legacy_v0` policy (the name is historical; it covers every
85/// pre-current format) and upgraded by [`migrate_kv_to_encrypted`].
86const CURRENT_FORMAT_VERSION: u8 = 2;
87
88/// Format version 1, the first versioned-`key_id` format.
89const FORMAT_V1: u8 = 1;
90
91/// The only algorithm identifier this module reads or writes.
92const ALGORITHM: &str = "AES-256-GCM";
93
94/// The one error text every decryption failure returns. The specific
95/// cause (bad base64, wrong nonce length, unknown key id, failed
96/// authentication, ...) is logged, never returned, so the failure itself
97/// is not an oracle for which check tripped.
98const DECRYPT_FAILED: &str = "Decryption failed";
99
100/// Associated data for a format-v2 envelope: the caller's record AAD
101/// (the storage key) AND the envelope's own `v`, `algorithm` and `key_id`,
102/// each length-prefixed so the concatenation is unambiguous. Binding the
103/// metadata means relabelling an envelope's `key_id`, or rewriting `v` to
104/// downgrade it to a format whose AAD ignores metadata, fails
105/// authentication instead of being trusted.
106fn bound_aad(v: u8, algorithm: &str, key_id: &str, record_aad: &[u8]) -> Vec<u8> {
107    let mut out = Vec::with_capacity(48 + algorithm.len() + key_id.len() + record_aad.len());
108    out.extend_from_slice(b"auth-framework/storage-envelope");
109    out.push(v);
110    for part in [algorithm.as_bytes(), key_id.as_bytes(), record_aad] {
111        out.extend_from_slice(&(part.len() as u32).to_be_bytes());
112        out.extend_from_slice(part);
113    }
114    out
115}
116
117fn default_format_version() -> u8 {
118    // Envelopes serialized before this field existed (format version 0,
119    // the original public `EncryptedStorage`: fields `data`/`nonce`/
120    // `algorithm`/`key_derivation`, no `key_id`, no AAD at encryption
121    // time) deserialize with this field absent -- serde DOES call this
122    // function in that case (per `#[serde(default = "...")]`'s actual
123    // behavior), which happens to return the same `0` the bare type
124    // default would. It's spelled out explicitly, rather than relying on
125    // `#[serde(default)]`'s type-default shorthand, so the "absent field
126    // means format version 0" rule is visible at the field's definition
127    // instead of implicit in `u8::default()`.
128    0
129}
130
131/// Encrypted data container with metadata.
132///
133/// `key_id` makes this a versioned envelope: a value encrypted under one key
134/// can still be decrypted after the *current* key rotates, as long as the
135/// old key is still loadable (see [`KeyProvider`]). Writers always use the
136/// current key; readers look up whichever key the envelope names.
137///
138/// `v` and `key_derivation` exist for backward compatibility with the
139/// original, pre-this-redesign public `EncryptedStorage` (format version
140/// 0): that format had no `key_id` and no AAD binding at encryption time.
141/// An envelope with `v == 0` (including any envelope missing the `v` field
142/// entirely, since `#[serde(default)]` fills it with `0`) is decrypted
143/// against every loaded key with an empty AAD, matching the old behavior;
144/// see [`StorageEncryption::decrypt`].
145#[derive(Debug, Clone, Serialize, Deserialize)]
146pub struct EncryptedData {
147    /// Base64 encoded encrypted data
148    pub data: String,
149    /// Base64 encoded nonce/IV (96 bits, randomly generated per encryption)
150    pub nonce: String,
151    /// Algorithm identifier
152    pub algorithm: String,
153    /// Which key (by id) encrypted this value. Empty for format version 0
154    /// (the original `EncryptedStorage`, which had no key-id concept).
155    #[serde(default)]
156    pub key_id: String,
157    /// Envelope format version. `0` (including an absent field, which
158    /// deserializes to `0`) is the original pre-redesign format; `1` is
159    /// the legacy versioned-`key_id` format; `2` is the current format
160    /// (metadata bound into the AAD).
161    #[serde(default = "default_format_version")]
162    pub v: u8,
163    /// Present only for format-version-0 compatibility (the original
164    /// field name was `key_derivation`); current envelopes don't set it.
165    #[serde(default)]
166    pub key_derivation: String,
167}
168
169/// Supplies the encryption key(s) [`StorageEncryption`] uses.
170///
171/// Exists as a seam so the key *source* (env var today) can be swapped for
172/// a KMS or an `age`/`sops`-style file-based secret without touching
173/// [`StorageEncryption`] or [`EncryptedStorage`] at all. See
174/// [`EnvKeyProvider`]'s own docs for the current, deliberately narrow,
175/// implementation and its known limitation.
176pub trait KeyProvider: Send + Sync {
177    /// Load every key this provider knows about, keyed by key id, plus
178    /// which one is current (new writes use this one; any key in the map
179    /// can still be used to decrypt an old envelope that names it).
180    ///
181    /// Returns an error if no usable key can be loaded at all -- callers
182    /// must fail closed on that, never silently fall back to no
183    /// encryption.
184    fn load_keys(&self) -> Result<LoadedKeys>;
185}
186
187/// The result of [`KeyProvider::load_keys`]: every key this provider could
188/// load, and which one is current.
189pub struct LoadedKeys {
190    pub current_key_id: String,
191    /// All loadable keys, including the current one, by key id. A key id
192    /// must not be empty -- [`StorageEncryption::new`] rejects any that
193    /// are, since an empty id can't be told apart from format-version-0
194    /// envelopes (which have no key id at all).
195    pub keys: HashMap<String, [u8; 32]>,
196}
197
198/// Loads encryption keys from environment variables, or from a file if
199/// `AUTH_STORAGE_ENCRYPTION_KEYS_FILE` is set.
200///
201/// **Known limitation (tracked, per CireSnave's ruling on board item 124):**
202/// env vars and files sit on the same host as the data they protect. An
203/// attacker with read access to the process environment or the key file
204/// can decrypt everything this encrypts. This is accepted as a starting
205/// point, not an endpoint -- [`KeyProvider`] exists specifically so a
206/// KMS-backed or `age`/`sops`-backed provider can replace this one later
207/// without any caller-visible change. See `docs/storage-backends.md` for
208/// the same note aimed at operators.
209///
210/// ## Format
211///
212/// - `AUTH_STORAGE_ENCRYPTION_KEY` (required unless the keys file sets
213///   `current`): the current key, base64-encoded, 32 bytes decoded.
214/// - `AUTH_STORAGE_ENCRYPTION_KEY_ID` (optional, defaults to `"1"`): the id
215///   under which `AUTH_STORAGE_ENCRYPTION_KEY` is recorded in new
216///   envelopes.
217/// - `AUTH_STORAGE_ENCRYPTION_KEYS_FILE` (optional): path to a JSON file
218///   `{"current": "<key_id>", "keys": {"<key_id>": "<base64 key>", ...}}`
219///   for rotation -- old keys stay loadable (decrypt-only in practice,
220///   since `current` picks what new writes use) as long as they're listed
221///   here. If set, this takes priority over the two env vars above. On
222///   Unix, a keys file readable by group or other triggers a `tracing::warn!`;
223///   set `AUTH_STORAGE_ENCRYPTION_STRICT_KEY_FILE_PERMISSIONS=1` to make that
224///   a startup error instead. Not checked at all on Windows.
225/// - **The single env var cannot rotate**: it holds one key, so changing it
226///   makes every stored envelope undecryptable. Use the keys file for
227///   anything that will outlive one key; the storage factory warns when the
228///   env-var key protects data that is already encrypted.
229pub struct EnvKeyProvider;
230
231impl KeyProvider for EnvKeyProvider {
232    fn load_keys(&self) -> Result<LoadedKeys> {
233        if let Ok(path) = env::var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE") {
234            return Self::load_from_file(&path);
235        }
236
237        let mut key_data = env::var("AUTH_STORAGE_ENCRYPTION_KEY").map_err(|_| {
238            AuthError::config(
239                "No storage encryption key configured: set AUTH_STORAGE_ENCRYPTION_KEY \
240                 (or AUTH_STORAGE_ENCRYPTION_KEYS_FILE for multi-key rotation). \
241                 Refusing to start rather than silently storing data unencrypted.",
242            )
243        })?;
244        let key_id = env::var("AUTH_STORAGE_ENCRYPTION_KEY_ID").unwrap_or_else(|_| "1".to_string());
245        let key = decode_key(&key_data);
246        key_data.zeroize();
247        let key = key?;
248
249        let mut keys = HashMap::new();
250        keys.insert(key_id.clone(), key);
251        Ok(LoadedKeys {
252            current_key_id: key_id,
253            keys,
254        })
255    }
256}
257
258impl EnvKeyProvider {
259    fn load_from_file(path: &str) -> Result<LoadedKeys> {
260        #[derive(Deserialize)]
261        struct KeysFile {
262            current: String,
263            keys: HashMap<String, String>,
264        }
265
266        check_keys_file_permissions(path, strict_permissions_requested())?;
267
268        let mut contents = fs::read_to_string(path).map_err(|e| {
269            AuthError::config(format!(
270                "Failed to read AUTH_STORAGE_ENCRYPTION_KEYS_FILE '{path}': {e}"
271            ))
272        })?;
273        let parsed: Result<KeysFile> = serde_json::from_str(&contents).map_err(|e| {
274            AuthError::config(format!(
275                "Failed to parse AUTH_STORAGE_ENCRYPTION_KEYS_FILE '{path}': {e}"
276            ))
277        });
278        contents.zeroize();
279        let mut parsed = parsed?;
280
281        if !parsed.keys.contains_key(&parsed.current) {
282            // Zeroize every base64 key string before returning -- this
283            // early return must not be the one exit path that skips it.
284            for encoded in parsed.keys.values_mut() {
285                encoded.zeroize();
286            }
287            return Err(AuthError::config(format!(
288                "AUTH_STORAGE_ENCRYPTION_KEYS_FILE '{path}': current key id '{}' \
289                 is not present in 'keys'",
290                parsed.current
291            )));
292        }
293
294        // Decode every entry, zeroizing its base64 string regardless of
295        // success or failure, before checking for any error -- so a
296        // failure partway through doesn't leave later entries' strings
297        // (never reached by a `?`-propagating loop) un-zeroized, and
298        // doesn't leave already-decoded key bytes from earlier entries
299        // sitting in `keys` when we return Err below. Pre-sized so
300        // `insert` never triggers a reallocation that could leave a
301        // decoded key copy behind in the old, freed backing array.
302        let mut keys = HashMap::with_capacity(parsed.keys.len());
303        let mut first_error = None;
304        for (id, mut encoded) in parsed.keys {
305            match decode_key(&encoded) {
306                Ok(key) => {
307                    keys.insert(id, key);
308                }
309                Err(e) if first_error.is_none() => {
310                    first_error = Some(e);
311                }
312                Err(_) => {}
313            }
314            encoded.zeroize();
315        }
316
317        if let Some(error) = first_error {
318            for key_bytes in keys.values_mut() {
319                key_bytes.zeroize();
320            }
321            return Err(error);
322        }
323
324        Ok(LoadedKeys {
325            current_key_id: parsed.current,
326            keys,
327        })
328    }
329}
330
331/// Environment variable that turns the keys-file permission warning into a
332/// startup error. Accepts `1`, `true` or `yes` (any case).
333const STRICT_KEY_FILE_PERMISSIONS_ENV: &str = "AUTH_STORAGE_ENCRYPTION_STRICT_KEY_FILE_PERMISSIONS";
334
335/// `true` when a file mode lets group or other read (or write) the file.
336/// (Only the Unix permission check calls it outside tests.)
337#[cfg_attr(
338    not(unix),
339    allow(
340        dead_code,
341        reason = "only the Unix permission check calls it outside tests"
342    )
343)]
344fn keys_file_mode_too_open(mode: u32) -> bool {
345    mode & 0o077 != 0
346}
347
348fn strict_permissions_requested() -> bool {
349    env::var(STRICT_KEY_FILE_PERMISSIONS_ENV)
350        .map(|value| {
351            matches!(
352                value.trim().to_ascii_lowercase().as_str(),
353                "1" | "true" | "yes"
354            )
355        })
356        .unwrap_or(false)
357}
358
359/// Checks the keys file's permissions: always warns when it is readable by
360/// group or other (a file-based key readable by others defeats its point),
361/// and fails startup when `strict` is set
362/// (`AUTH_STORAGE_ENCRYPTION_STRICT_KEY_FILE_PERMISSIONS=1`). The default
363/// stays warn-only because permission semantics vary across containers, CI
364/// and Windows; strict mode is the opt-in for deployments that control them.
365/// Unix only: elsewhere there are no group/other mode bits to inspect, so
366/// strict mode logs that it cannot be enforced.
367fn check_keys_file_permissions(path: &str, strict: bool) -> Result<()> {
368    #[cfg(unix)]
369    {
370        use std::os::unix::fs::PermissionsExt;
371        if let Ok(metadata) = fs::metadata(path) {
372            let mode = metadata.permissions().mode();
373            if keys_file_mode_too_open(mode) {
374                if strict {
375                    return Err(AuthError::config(format!(
376                        "AUTH_STORAGE_ENCRYPTION_KEYS_FILE '{path}' has mode {:o}: it is \
377                         accessible to group or other. Restrict it to the owner (chmod 600) \
378                         or unset {STRICT_KEY_FILE_PERMISSIONS_ENV}.",
379                        mode & 0o777
380                    )));
381                }
382                tracing::warn!(
383                    path = path,
384                    mode = format!("{mode:o}"),
385                    "AUTH_STORAGE_ENCRYPTION_KEYS_FILE is readable by group or other -- \
386                     restrict it to the owner only (chmod 600), or set \
387                     {STRICT_KEY_FILE_PERMISSIONS_ENV}=1 to make this fatal."
388                );
389            }
390        }
391    }
392    #[cfg(not(unix))]
393    {
394        let _ = path;
395        if strict {
396            tracing::warn!(
397                "{STRICT_KEY_FILE_PERMISSIONS_ENV} is set but key-file permissions cannot be \
398                 inspected on this platform; it is not enforced."
399            );
400        }
401    }
402    Ok(())
403}
404
405/// `true` when the key comes from the `AUTH_STORAGE_ENCRYPTION_KEY`
406/// environment variable (no keys file). That source holds exactly one key
407/// and so cannot rotate: replacing it makes every stored envelope
408/// undecryptable. Use a keys file (`AUTH_STORAGE_ENCRYPTION_KEYS_FILE`) for
409/// anything that will outlive one key.
410pub(crate) fn env_key_source_in_use() -> bool {
411    env::var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE").is_err()
412        && env::var("AUTH_STORAGE_ENCRYPTION_KEY").is_ok()
413}
414
415/// Looks at up to `limit` KV entries of `storage` and reports whether any is
416/// already an encryption envelope. Bounded in the number of values read; the
417/// key listing itself is whatever the backend returns for the empty prefix.
418pub(crate) async fn stored_envelopes_exist<S: AuthStorage + ?Sized>(
419    storage: &S,
420    limit: usize,
421) -> Result<bool> {
422    for key in storage.list_kv_keys("").await?.into_iter().take(limit) {
423        if let Some(raw) = storage.get_kv(&key).await?
424            && StorageEncryption::looks_like_envelope(&raw)
425        {
426            return Ok(true);
427        }
428    }
429    Ok(false)
430}
431
432/// Produces a safe-to-log identifier for a storage key, for error
433/// messages, tracing, and migration reports -- **never** the raw key
434/// itself. In this crate, some storage keys literally ARE bearer
435/// secrets (e.g. `api_key:{raw_api_key}` in
436/// `auth_modular::user_manager`, `device:{device_code}` in
437/// `api::oauth_advanced`), so logging or printing a key name verbatim
438/// can leak a working credential into logs or a terminal.
439///
440/// Keeps the portion up to (not including) the first `:` (the
441/// namespace, e.g. `api_key`, assumed not secret since every KV
442/// namespace convention in this crate puts a fixed literal there) plus
443/// a short, one-way hash of the *full* key, so an operator with direct
444/// storage access can still correlate a reported identifier back to
445/// the real record (by recomputing the same hash over a candidate key)
446/// without the identifier itself being usable as a credential. A key
447/// with no `:` at all has no such non-secret prefix to keep -- it is
448/// replaced with the literal `key`, never the raw key itself.
449fn safe_log_id(key: &str) -> String {
450    use sha2::{Digest, Sha256};
451    let hash_hex = hex::encode(&Sha256::digest(key.as_bytes())[..8]);
452    match key.split_once(':') {
453        Some((namespace, _)) => format!("{namespace}:{hash_hex}"),
454        None => format!("key:{hash_hex}"),
455    }
456}
457
458fn decode_key(encoded: &str) -> Result<[u8; 32]> {
459    let mut key_bytes = BASE64
460        .decode(encoded)
461        .map_err(|_| AuthError::config("Invalid base64 in storage encryption key"))?;
462    if key_bytes.len() != 32 {
463        key_bytes.zeroize();
464        return Err(AuthError::config(
465            "Storage encryption key must be 32 bytes (256 bits) once base64-decoded",
466        ));
467    }
468    let mut key = [0u8; 32];
469    key.copy_from_slice(&key_bytes);
470    key_bytes.zeroize();
471    Ok(key)
472}
473
474/// Storage encryption manager using AES-256-GCM, with per-record random
475/// nonces and associated data (AAD) binding each ciphertext to the storage
476/// key it was stored under -- so a ciphertext copied from one record to
477/// another fails to decrypt instead of silently "succeeding" with the
478/// wrong value.
479///
480/// **Known limitation (replay of an older value under the same key):** AAD
481/// binds a ciphertext to *which record* it belongs to, not to *when* it was
482/// written. Someone who can both read an old ciphertext for a given key and
483/// write to that same key can replay the old value -- AES-GCM's
484/// authentication only proves "this is a genuine envelope for this record,"
485/// not "this is the most recent one." Mitigating this needs a monotonic
486/// counter or timestamp bound into the AAD, not done here (most KV-layer
487/// values in this crate are replaced wholesale on every write, which bounds
488/// but does not eliminate the exposure).
489///
490/// **Zeroization scope (accurate, not aspirational):** this module
491/// zeroizes raw key material and intermediate plaintext it owns on every
492/// exit path it controls (success, a validation error, or an encryption
493/// failure partway through), as soon as it's done with it -- the
494/// `[u8; 32]` key bytes in [`LoadedKeys`] (after the AES-GCM ciphers are
495/// built, or before any validation error returns, including the
496/// "current key id not found" check), [`decode_key`]'s intermediate
497/// decoded `Vec<u8>`, every base64-encoded key string
498/// [`EnvKeyProvider`] reads (file contents and every per-key entry, even
499/// ones after a failure elsewhere in the same batch, and even when the
500/// file's `current` id isn't present in `keys`), and
501/// [`migrate_kv_to_encrypted`]'s intermediate plaintext/raw buffers,
502/// including when the subsequent re-encrypt or write-back fails. It does
503/// **not** zeroize: any copy the standard library or `aes-gcm` makes
504/// internally that this code doesn't control (notably `aes` 0.8.4's own
505/// key-schedule storage inside the `Aes256Gcm` cipher object, which has
506/// no zeroize support in the version this crate depends on; and
507/// `HashMap` growth can in principle leave a stale decoded-key copy in
508/// an old, freed backing allocation during a resize -- mitigated, not
509/// eliminated, in `EnvKeyProvider::load_from_file`'s multi-key decoding
510/// loop (the one production path that decodes a variable, potentially
511/// large number of keys into a map) by pre-sizing it with
512/// `with_capacity`; `EnvKeyProvider::load_keys`' single-env-var path
513/// only ever inserts exactly one entry, so it can't resize at all), or
514/// a plaintext value a public method (`decrypt`,
515/// `decrypt_from_storage`) hands back to its caller (that's the actual
516/// return value the caller needs -- it isn't leftover residue this module
517/// can clean up on the caller's behalf).
518pub struct StorageEncryption {
519    current_key_id: String,
520    ciphers: HashMap<String, Aes256Gcm>,
521}
522
523impl StorageEncryption {
524    /// Create a new encryption manager, loading keys from the given
525    /// provider. Fails closed: if the provider can't load a usable key,
526    /// this returns `Err` rather than any fallback.
527    pub fn new(provider: &dyn KeyProvider) -> Result<Self> {
528        let mut loaded = provider.load_keys()?;
529
530        // Validate first, but zeroize the raw key bytes on EVERY exit
531        // path (including these early validation failures) -- not just
532        // the success path -- so a rejected key never lingers in memory
533        // any longer than the other branch does.
534        let validation_error = if loaded.current_key_id.is_empty() {
535            Some(AuthError::config(
536                "Key provider's current_key_id must not be empty",
537            ))
538        } else if loaded.keys.keys().any(|id| id.is_empty()) {
539            Some(AuthError::config(
540                "Key provider returned a key with an empty id -- an empty id is reserved \
541                 to mean \"format-version-0 envelope, no key id at all\"",
542            ))
543        } else if !loaded.keys.contains_key(&loaded.current_key_id) {
544            Some(AuthError::config(format!(
545                "Key provider's current_key_id '{}' is not among the keys it loaded",
546                loaded.current_key_id
547            )))
548        } else {
549            None
550        };
551
552        if let Some(error) = validation_error {
553            for key_bytes in loaded.keys.values_mut() {
554                key_bytes.zeroize();
555            }
556            return Err(error);
557        }
558
559        let ciphers = loaded
560            .keys
561            .iter()
562            .map(|(id, key_bytes)| {
563                let key = Key::<Aes256Gcm>::from_slice(key_bytes);
564                (id.clone(), Aes256Gcm::new(key))
565            })
566            .collect();
567        // The cipher objects above have their own internal copies of the
568        // key material; zeroize the raw bytes we held so they don't sit
569        // around in this struct any longer than necessary.
570        for key_bytes in loaded.keys.values_mut() {
571            key_bytes.zeroize();
572        }
573        Ok(Self {
574            current_key_id: loaded.current_key_id,
575            ciphers,
576        })
577    }
578
579    /// Create a new encryption manager from the environment (see
580    /// [`EnvKeyProvider`]). Convenience wrapper over `new(&EnvKeyProvider)`.
581    pub fn from_env() -> Result<Self> {
582        Self::new(&EnvKeyProvider)
583    }
584
585    /// Create new encryption manager for testing with a single random key.
586    #[cfg(test)]
587    pub fn new_random() -> Self {
588        use rand::Rng;
589        let mut key_bytes = [0u8; 32];
590        rand::rng().fill_bytes(&mut key_bytes);
591        let key = Key::<Aes256Gcm>::from_slice(&key_bytes);
592        let mut ciphers = HashMap::new();
593        ciphers.insert("test".to_string(), Aes256Gcm::new(key));
594        key_bytes.zeroize();
595        Self {
596            current_key_id: "test".to_string(),
597            ciphers,
598        }
599    }
600
601    /// Generate a new 256-bit encryption key (base64 encoded), suitable for
602    /// `AUTH_STORAGE_ENCRYPTION_KEY` or a keys-file entry.
603    pub fn generate_key() -> String {
604        use rand::Rng;
605        let mut key_bytes = [0u8; 32];
606        rand::rng().fill_bytes(&mut key_bytes);
607        let encoded = BASE64.encode(key_bytes);
608        key_bytes.zeroize();
609        encoded
610    }
611
612    /// Encrypt raw bytes. `aad` (associated data) is authenticated but not
613    /// encrypted -- callers should pass the storage key the resulting
614    /// envelope will be stored under, binding the ciphertext to that
615    /// specific record.
616    pub fn encrypt(&self, plaintext: &[u8], aad: &[u8]) -> Result<EncryptedData> {
617        use rand::Rng;
618        let cipher = self.ciphers.get(&self.current_key_id).ok_or_else(|| {
619            AuthError::internal("Current encryption key missing from loaded cipher set")
620        })?;
621
622        // 96-bit nonce, freshly random every call. NIST SP 800-38D caps a
623        // randomly generated 96-bit IV at 2^32 invocations under a single
624        // key before the collision probability becomes unacceptable (the
625        // "32-bit random IV construction" guidance) -- not the ~2^64/2
626        // birthday bound a naive calculation might suggest. A given
627        // deployment's key should be rotated well before approaching that
628        // count; this crate does not currently track or enforce it.
629        let mut nonce_bytes = [0u8; 12];
630        rand::rng().fill_bytes(&mut nonce_bytes);
631        let nonce = Nonce::from_slice(&nonce_bytes);
632
633        let bound = bound_aad(CURRENT_FORMAT_VERSION, ALGORITHM, &self.current_key_id, aad);
634        let ciphertext = cipher
635            .encrypt(
636                nonce,
637                Payload {
638                    msg: plaintext,
639                    aad: &bound,
640                },
641            )
642            .map_err(|e| AuthError::internal(format!("Encryption failed: {}", e)))?;
643
644        Ok(EncryptedData {
645            data: BASE64.encode(&ciphertext),
646            nonce: BASE64.encode(nonce_bytes),
647            algorithm: ALGORITHM.to_string(),
648            key_id: self.current_key_id.clone(),
649            v: CURRENT_FORMAT_VERSION,
650            key_derivation: String::new(),
651        })
652    }
653
654    /// Decrypt an envelope. `aad` must match exactly what was passed to
655    /// [`Self::encrypt`] (the storage key the envelope is stored under) --
656    /// a mismatch (e.g. a ciphertext copied to a different record) fails
657    /// decryption rather than succeeding with the wrong plaintext.
658    ///
659    /// A format-version-0 envelope (see [`EncryptedData`]) is decrypted
660    /// with an empty AAD against every loaded key in turn, matching the
661    /// original `EncryptedStorage`'s behavior (no AAD, no key id) --
662    /// AES-GCM's authentication tag makes trying the wrong key safe (it
663    /// just fails), so this cannot silently produce the wrong plaintext.
664    pub fn decrypt(&self, encrypted: &EncryptedData, aad: &[u8]) -> Result<Vec<u8>> {
665        // Every failure below returns the SAME error text (`DECRYPT_FAILED`);
666        // the cause is logged only.
667        let fail = |why: &str| -> AuthError {
668            // `key_id` comes from the (possibly attacker-writable) store:
669            // log it Debug-escaped and bounded.
670            tracing::warn!(
671                key_id = ?encrypted.key_id.chars().take(64).collect::<String>(),
672                v = encrypted.v,
673                "storage envelope decryption failed: {why}"
674            );
675            AuthError::internal(DECRYPT_FAILED)
676        };
677
678        if encrypted.algorithm != ALGORITHM {
679            return Err(fail("unsupported algorithm"));
680        }
681
682        let ciphertext = BASE64
683            .decode(&encrypted.data)
684            .map_err(|_| fail("invalid base64 in data"))?;
685        let nonce_bytes = BASE64
686            .decode(&encrypted.nonce)
687            .map_err(|_| fail("invalid base64 in nonce"))?;
688        if nonce_bytes.len() != 12 {
689            return Err(fail("invalid nonce length"));
690        }
691        let nonce = Nonce::from_slice(&nonce_bytes);
692
693        if encrypted.v == 0 {
694            // Format version 0 (the original EncryptedStorage): no key id,
695            // no AAD. Try every loaded key, in a stable order; the auth tag
696            // rejects wrong ones.
697            for id in self.sorted_key_ids() {
698                if let Some(cipher) = self.ciphers.get(&id)
699                    && let Ok(plaintext) = cipher.decrypt(
700                        nonce,
701                        Payload {
702                            msg: &ciphertext,
703                            aad: b"",
704                        },
705                    )
706                {
707                    return Ok(plaintext);
708                }
709            }
710            return Err(fail("no loaded key opens this format-version-0 envelope"));
711        }
712
713        let cipher = self
714            .ciphers
715            .get(&encrypted.key_id)
716            .ok_or_else(|| fail("no loaded key for this key_id (rotated out?)"))?;
717
718        // v1 authenticated only the bare record AAD; v2 also binds the
719        // envelope's own metadata. Anything else is unknown to this build.
720        let bound;
721        let effective_aad: &[u8] = match encrypted.v {
722            FORMAT_V1 => aad,
723            CURRENT_FORMAT_VERSION => {
724                bound = bound_aad(encrypted.v, &encrypted.algorithm, &encrypted.key_id, aad);
725                &bound
726            }
727            _ => return Err(fail("unsupported envelope version")),
728        };
729
730        cipher
731            .decrypt(
732                nonce,
733                Payload {
734                    msg: &ciphertext,
735                    aad: effective_aad,
736                },
737            )
738            .map_err(|_| fail("authentication failed (wrong key, wrong record, or tampered)"))
739    }
740
741    /// Encrypt raw bytes for storage, serialized as a self-describing
742    /// envelope. `aad` should be the storage key this will be stored
743    /// under. Accepts arbitrary bytes, not just UTF-8 text.
744    pub fn encrypt_for_storage(&self, data: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
745        let encrypted = self.encrypt(data, aad)?;
746        let serialized = serde_json::to_string(&encrypted).map_err(|e| {
747            AuthError::internal(format!("Failed to serialize encrypted data: {}", e))
748        })?;
749        Ok(serialized.into_bytes())
750    }
751
752    /// Decrypt a storage envelope produced by [`Self::encrypt_for_storage`].
753    /// `aad` must be the same storage key passed to that call.
754    pub fn decrypt_from_storage(&self, data: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
755        // A stored value that is not even an envelope fails with the same
756        // text as every other decryption failure; the cause is logged.
757        let parsed = std::str::from_utf8(data)
758            .map_err(|e| e.to_string())
759            .and_then(|s| serde_json::from_str::<EncryptedData>(s).map_err(|e| e.to_string()));
760        let encrypted = parsed.map_err(|why| {
761            tracing::warn!("stored value is not a readable envelope: {why}");
762            AuthError::internal(DECRYPT_FAILED)
763        })?;
764        self.decrypt(&encrypted, aad)
765    }
766
767    /// Parses `data` as one of this module's own serialized envelopes --
768    /// either the current format or the original format-version-0 shape
769    /// (see [`EncryptedData`]) -- without attempting to decrypt it. `None`
770    /// if `data` isn't valid UTF-8 JSON, doesn't name the right algorithm,
771    /// or claims a post-v0 format without a `key_id`.
772    ///
773    /// This is a **shape** check only. A value that parses here but fails
774    /// to decrypt (wrong key, corrupted, or tampered with) is a hard error
775    /// from [`Self::decrypt_from_storage`], never silently treated as
776    /// plaintext.
777    pub fn parse_envelope(data: &[u8]) -> Option<EncryptedData> {
778        let encrypted = std::str::from_utf8(data)
779            .ok()
780            .and_then(|s| serde_json::from_str::<EncryptedData>(s).ok())?;
781        if encrypted.algorithm != ALGORITHM {
782            return None;
783        }
784        // v0 has neither `v` nor `key_id`. Anything claiming a later
785        // format must carry an explicit non-empty `key_id`; without one it
786        // is just plaintext JSON that happens to resemble an envelope.
787        let well_formed = if encrypted.v == 0 {
788            encrypted.key_id.is_empty()
789        } else {
790            !encrypted.key_id.is_empty()
791        };
792        well_formed.then_some(encrypted)
793    }
794
795    /// Key ids in a stable (ascending) order, for deterministic trial
796    /// decryption.
797    fn sorted_key_ids(&self) -> Vec<String> {
798        let mut ids: Vec<String> = self.ciphers.keys().cloned().collect();
799        ids.sort();
800        ids
801    }
802
803    /// Returns `true` if `data` parses as one of this module's own
804    /// serialized envelopes. Used by [`migrate_kv_to_encrypted`] and
805    /// [`EncryptedStorage::get_kv`] to decide whether a stored value
806    /// should be decrypted at all.
807    pub fn looks_like_envelope(data: &[u8]) -> bool {
808        Self::parse_envelope(data).is_some()
809    }
810}
811
812/// Wrapper for storage backends that adds encryption at rest to the
813/// generic key-value (`store_kv`/`get_kv`) layer.
814///
815/// **Coverage note:** this wraps `store_kv`/`get_kv` only. The dedicated
816/// `store_token`/`store_session` methods (and each backend's own typed
817/// columns for them) are NOT touched by this wrapper -- they delegate to
818/// `inner` unchanged. Encrypting those would need changes to the
819/// `AuthStorage` trait itself (their fields are typed, not opaque bytes),
820/// tracked separately. This wrapper covers everything that already goes
821/// through `store_kv` today: API keys, TOTP secrets, OAuth2 client
822/// registries, MFA codes, and most of the other KV-backed subsystems
823/// found in the storage audit (`docs/STORAGE-AUDIT.md`).
824pub struct EncryptedStorage<T> {
825    inner: T,
826    encryption: StorageEncryption,
827    /// See [`Self::get_kv`]'s doc comment for exactly what this controls.
828    allow_plaintext_reads: bool,
829    /// See [`Self::get_kv`]'s doc comment for exactly what this controls.
830    allow_legacy_v0: bool,
831}
832
833impl<T> EncryptedStorage<T> {
834    /// `allow_plaintext_reads` should be `true` only transiently, while
835    /// migrating an existing deployment's plaintext data (see
836    /// [`migrate_kv_to_encrypted`]) -- it is what makes [`Self::get_kv`]
837    /// tolerate a value that isn't a valid envelope instead of erroring.
838    /// Leaving it `true` permanently means anyone who can write to the
839    /// backing store can overwrite an encrypted value with chosen
840    /// plaintext (or corrupt one) and have it accepted silently, which
841    /// defeats the point of encrypting at rest. Pass `false` for normal
842    /// operation.
843    ///
844    /// `allow_legacy_v0` should likewise be `true` only transiently, while
845    /// migrating pre-existing format-version-0 data: a v0 envelope has no
846    /// AAD binding it to its own storage key, so with this `true`, a
847    /// writer who knows one record's v0 envelope can copy it onto a
848    /// different record's key and it still decrypts -- the exact swap the
849    /// current format's AAD exists to prevent. This flag is independent
850    /// of [`migrate_kv_to_encrypted`]'s own, separate
851    /// `accept_legacy_v0` parameter (that one gates whether migration
852    /// actually *rewrites* a v0 envelope; this one gates whether this
853    /// wrapper's `get_kv` will *read* one at all) -- set this one `true`
854    /// if something needs to read v0 data through this wrapper before,
855    /// or without ever, running migration.
856    pub fn new(
857        storage: T,
858        encryption: StorageEncryption,
859        allow_plaintext_reads: bool,
860        allow_legacy_v0: bool,
861    ) -> Self {
862        Self {
863            inner: storage,
864            encryption,
865            allow_plaintext_reads,
866            allow_legacy_v0,
867        }
868    }
869
870    pub fn into_inner(self) -> T {
871        self.inner
872    }
873}
874
875#[async_trait::async_trait]
876impl<T> AuthStorage for EncryptedStorage<T>
877where
878    T: AuthStorage + Send + Sync,
879{
880    // Token/session methods — NOT encrypted by this wrapper. See the
881    // "Coverage note" on `EncryptedStorage` itself.
882    async fn store_token(&self, token: &AuthToken) -> Result<()> {
883        self.inner.store_token(token).await
884    }
885
886    async fn get_token(&self, token_id: &str) -> Result<Option<AuthToken>> {
887        self.inner.get_token(token_id).await
888    }
889
890    async fn get_token_by_access_token(&self, access_token: &str) -> Result<Option<AuthToken>> {
891        self.inner.get_token_by_access_token(access_token).await
892    }
893
894    async fn update_token(&self, token: &AuthToken) -> Result<()> {
895        self.inner.update_token(token).await
896    }
897
898    async fn delete_token(&self, token_id: &str) -> Result<()> {
899        self.inner.delete_token(token_id).await
900    }
901
902    async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
903        self.inner.list_user_tokens(user_id).await
904    }
905
906    async fn store_session(&self, session_id: &str, data: &SessionData) -> Result<()> {
907        self.inner.store_session(session_id, data).await
908    }
909
910    async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
911        self.inner.get_session(session_id).await
912    }
913
914    async fn delete_session(&self, session_id: &str) -> Result<()> {
915        self.inner.delete_session(session_id).await
916    }
917
918    async fn list_user_sessions(&self, user_id: &str) -> Result<Vec<SessionData>> {
919        self.inner.list_user_sessions(user_id).await
920    }
921
922    async fn count_active_sessions(&self) -> Result<u64> {
923        self.inner.count_active_sessions().await
924    }
925
926    // Bulk methods — delegate directly to `inner`'s own overrides (if any)
927    // instead of inheriting the `AuthStorage` trait's one-at-a-time default
928    // loop, so a backend that implements real batching here keeps that
929    // benefit even when wrapped. Token/session bulk methods are unaffected
930    // by encryption (see the coverage note above) either way.
931    async fn store_tokens_bulk(&self, tokens: &[AuthToken]) -> Result<()> {
932        self.inner.store_tokens_bulk(tokens).await
933    }
934
935    async fn delete_tokens_bulk(&self, token_ids: &[String]) -> Result<()> {
936        self.inner.delete_tokens_bulk(token_ids).await
937    }
938
939    async fn store_sessions_bulk(&self, sessions: &[(String, SessionData)]) -> Result<()> {
940        self.inner.store_sessions_bulk(sessions).await
941    }
942
943    async fn delete_sessions_bulk(&self, session_ids: &[String]) -> Result<()> {
944        self.inner.delete_sessions_bulk(session_ids).await
945    }
946
947    // Key-value methods — encrypted, with the storage key itself as AAD so
948    // a ciphertext can't be swapped between records.
949    async fn get_kv_ttl(&self, key: &str) -> Result<Option<Duration>> {
950        // A TTL is storage metadata, not part of the encrypted value.
951        self.inner.get_kv_ttl(key).await
952    }
953
954    async fn store_kv(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> Result<()> {
955        let encrypted_value = self.encryption.encrypt_for_storage(value, key.as_bytes())?;
956        self.inner.store_kv(key, &encrypted_value, ttl).await
957    }
958
959    async fn store_kv_if_absent(
960        &self,
961        key: &str,
962        value: &[u8],
963        ttl: Option<Duration>,
964    ) -> Result<bool> {
965        let encrypted_value = self.encryption.encrypt_for_storage(value, key.as_bytes())?;
966        self.inner
967            .store_kv_if_absent(key, &encrypted_value, ttl)
968            .await
969    }
970
971    /// Reads back a value stored by [`Self::store_kv`], decrypting it.
972    ///
973    /// A value that **parses as one of this module's envelopes**
974    /// ([`StorageEncryption::looks_like_envelope`]) is always decrypted;
975    /// a decryption failure (wrong key, corrupted, tampered) is a hard
976    /// `Err`, never silently returned as-is.
977    ///
978    /// A value that does **not** parse as an envelope at all is ambiguous:
979    /// it could be genuine pre-encryption plaintext, or it could be a
980    /// plaintext value an attacker (or a bug) overwrote the encrypted one
981    /// with. This method only tolerates that ambiguity -- returning the
982    /// raw bytes as-is -- when `allow_plaintext_reads` is `true`. With it
983    /// `false` (the default via the storage factory once migration is
984    /// done), a non-envelope value is also a hard `Err`, so overwriting an
985    /// encrypted record with plaintext cannot silently succeed.
986    async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>> {
987        let Some(raw) = self.inner.get_kv(key).await? else {
988            return Ok(None);
989        };
990
991        if let Some(envelope) = StorageEncryption::parse_envelope(&raw) {
992            if envelope.v < CURRENT_FORMAT_VERSION && !self.allow_legacy_v0 {
993                return Err(AuthError::internal(format!(
994                    "Value for record '{}' uses legacy envelope format version {} (its \
995                     metadata is not bound into the authenticated data), and \
996                     storage_encryption.allow_legacy_v0 is false. Run the migration tool \
997                     (`auth-framework-admin security encrypt-kv --accept-legacy-v0`) to \
998                     upgrade it to the current format, or temporarily set \
999                     storage_encryption.allow_legacy_v0 = true if something else needs to \
1000                     read it first.",
1001                    safe_log_id(key),
1002                    envelope.v
1003                )));
1004            }
1005            let decrypted = self.encryption.decrypt(&envelope, key.as_bytes())?;
1006            return Ok(Some(decrypted));
1007        }
1008
1009        if self.allow_plaintext_reads {
1010            return Ok(Some(raw));
1011        }
1012
1013        Err(AuthError::internal(format!(
1014            "Value for record '{}' is not a valid encrypted envelope, and \
1015             storage_encryption.allow_plaintext_reads is false. If this key genuinely \
1016             predates encryption being enabled, run the migration tool \
1017             (`auth-framework-admin security encrypt-kv`) or temporarily set \
1018             storage_encryption.allow_plaintext_reads = true while migrating.",
1019            safe_log_id(key)
1020        )))
1021    }
1022
1023    fn tracks_kv_ttl(&self) -> bool {
1024        // A TTL is storage metadata, not part of the encrypted value.
1025        self.inner.tracks_kv_ttl()
1026    }
1027
1028    fn encrypts_kv_at_rest(&self) -> bool {
1029        true
1030    }
1031
1032    async fn delete_kv(&self, key: &str) -> Result<()> {
1033        self.inner.delete_kv(key).await
1034    }
1035
1036    // Key NAMES are never encrypted (only values) -- pass through
1037    // unchanged so RBAC role reload, maintenance/backup, and analytics
1038    // (all of which call this) keep working once this wrapper is in the
1039    // default path. Without this override, the AuthStorage trait's
1040    // default implementation would fail (it used to return an empty Vec).
1041    async fn list_kv_keys(&self, prefix: &str) -> Result<Vec<String>> {
1042        self.inner.list_kv_keys(prefix).await
1043    }
1044
1045    async fn cleanup_expired(&self) -> Result<()> {
1046        self.inner.cleanup_expired().await
1047    }
1048}
1049
1050/// Outcome of [`migrate_kv_to_encrypted`].
1051///
1052/// `#[non_exhaustive]`: this is a read-only outcome type, not something
1053/// a caller builds -- only this crate's own tests construct one (with
1054/// `..Default::default()`, which only compiles from *inside* the
1055/// crate), so a later field addition here can never be a breaking
1056/// change for an external caller.
1057#[derive(Debug, Clone, Default, PartialEq, Eq)]
1058#[non_exhaustive]
1059pub struct KvEncryptionMigrationReport {
1060    /// Whether this run was a dry run (no writes performed).
1061    pub dry_run: bool,
1062    /// Total keys examined under the given prefix. Always equal to
1063    /// `already_encrypted + legacy_v0_found + encrypted + vanished +
1064    /// failed.len()`.
1065    pub scanned: u64,
1066    /// Keys that were already a current-format envelope -- left
1067    /// untouched.
1068    pub already_encrypted: u64,
1069    /// Keys that were a LEGACY envelope (format version 0 or 1; the name
1070    /// is historical) that decrypted successfully -- counted here whether
1071    /// or not they were actually rewritten (see `upgraded_from_legacy`).
1072    /// A v0 envelope has no AAD binding its plaintext to this specific
1073    /// record, so this plaintext's association with this key could not
1074    /// be cryptographically verified -- it is exactly as trustworthy as
1075    /// it was before migration, no more, no less. A v1 envelope's AAD
1076    /// does bind the record key (its decryption just verified that), but
1077    /// not its own metadata.
1078    pub legacy_v0_found: u64,
1079    /// Keys whose legacy (v0 or v1) envelope was actually rewritten under
1080    /// the current format. Zero unless this was a real (non-dry) run
1081    /// AND `accept_legacy_v0` was `true` -- see
1082    /// [`migrate_kv_to_encrypted`]'s docs for why that flag exists and
1083    /// what rewriting a v0 envelope does and does not verify.
1084    pub upgraded_from_legacy: u64,
1085    /// Keys that were plaintext (not an envelope at all) and got
1086    /// encrypted (or would have, in a dry run).
1087    pub encrypted: u64,
1088    /// Keys that were read but had vanished by the time of the write-back
1089    /// (concurrent deletion) -- not an error, just skipped.
1090    pub vanished: u64,
1091    /// Format-version-0 records whose envelope could not be decrypted
1092    /// under any loaded key (wrong/missing key, or corrupted). Skipped,
1093    /// not treated as fatal -- the rest of the run still completes.
1094    /// **Only v0 envelopes are decrypt-checked by this function** --
1095    /// a current-format (v1) envelope that can't decrypt (e.g. its key
1096    /// was rotated out) is not migration's concern (it's already in the
1097    /// target format) and is counted in `already_encrypted`, not here.
1098    /// Entries are a **safe identifier** (see [`safe_log_id`]), never the
1099    /// raw storage key -- some keys in this crate are themselves bearer
1100    /// secrets (e.g. `api_key:{raw_key}`).
1101    pub failed: Vec<String>,
1102}
1103
1104/// Options for [`migrate_kv_to_encrypted`]. A named struct rather than
1105/// two adjacent `bool` parameters, specifically so a caller can't
1106/// transpose them -- `(false, true)` instead of `(true, false)` would
1107/// otherwise silently turn an intended dry run into a real upgrade.
1108#[derive(Debug, Clone, Copy, Default)]
1109#[non_exhaustive]
1110pub struct MigrationOptions {
1111    /// Preview only; don't write anything. See
1112    /// [`migrate_kv_to_encrypted`]'s own docs for exactly what a dry run
1113    /// still does (it attempts every decrypt a real run would, for
1114    /// accurate reporting).
1115    pub dry_run: bool,
1116    /// Required, together with `dry_run: false`, to actually rewrite a
1117    /// format-version-0 envelope to the current format. See
1118    /// [`migrate_kv_to_encrypted`]'s own docs for why this is a separate,
1119    /// explicit opt-in.
1120    pub accept_legacy_v0: bool,
1121    /// A backend that cannot report KV TTLs ([`AuthStorage::tracks_kv_ttl`]
1122    /// is `false`) makes a real migration turn every expiring entry into a
1123    /// permanent one. Such a run is refused unless this is `true`.
1124    pub accept_ttl_loss: bool,
1125}
1126
1127impl MigrationOptions {
1128    /// Builder-style setter; see [`Self::with_dry_run`].
1129    pub fn with_accept_ttl_loss(mut self, accept_ttl_loss: bool) -> Self {
1130        self.accept_ttl_loss = accept_ttl_loss;
1131        self
1132    }
1133
1134    /// Builder-style setter. `#[non_exhaustive]` means `MigrationOptions {
1135    /// dry_run: true, ..Default::default() }` only compiles *inside*
1136    /// this crate -- a downstream caller needs `let mut o =
1137    /// MigrationOptions::default(); o.dry_run = true;` or this method
1138    /// chain instead: `MigrationOptions::default().with_dry_run(true)`.
1139    pub fn with_dry_run(mut self, dry_run: bool) -> Self {
1140        self.dry_run = dry_run;
1141        self
1142    }
1143
1144    /// Builder-style setter; see [`Self::with_dry_run`] for why this
1145    /// exists instead of a struct literal.
1146    pub fn with_accept_legacy_v0(mut self, accept_legacy_v0: bool) -> Self {
1147        self.accept_legacy_v0 = accept_legacy_v0;
1148        self
1149    }
1150}
1151
1152/// Re-encrypts every already-plaintext value under `prefix` in the given
1153/// KV storage, in place.
1154///
1155/// - **Idempotent and resumable**: a value already in the *current*
1156///   envelope format is left untouched. Re-running this function (e.g.
1157///   after it was interrupted, or because some keys were skipped as
1158///   `failed`) only ever touches the plaintext and not-yet-upgraded v0
1159///   values still remaining -- there's no separate resume cursor to
1160///   manage.
1161/// - **A single undecryptable v0 envelope never aborts the run**: if one
1162///   key's format-version-0 envelope can't be decrypted under any
1163///   loaded key (wrong/missing key, or corrupted -- only v0 envelopes
1164///   are decrypt-checked this way, see
1165///   [`KvEncryptionMigrationReport::failed`]'s own docs), a safe
1166///   identifier for it (never the raw key) is recorded in `failed` and
1167///   it's skipped -- every other key is still processed. Anyone who can
1168///   write one envelope-shaped value under `prefix` can otherwise make
1169///   an `?` on the first failure block the entire run.
1170/// - **Dry-run is accurate, not optimistic**: `dry_run: true` actually
1171///   attempts every decrypt it would need for a real run (it just skips
1172///   the write-back), so its counts -- including `failed` -- match what
1173///   a real run would do, rather than assuming every v0 envelope found
1174///   would succeed.
1175/// - **Format-version-0 upgrades require `accept_legacy_v0: true` AND a
1176///   real (non-dry) run.** A v0 envelope has no AAD, so decrypting it
1177///   proves nothing about *which record* its plaintext actually belongs
1178///   to -- it decrypts successfully under any loaded key regardless of
1179///   where it's stored. **This function cannot detect a v0 envelope
1180///   that's been copied from one record onto another**; it can only
1181///   decrypt-then-re-encrypt whatever is there, inheriting that
1182///   plaintext's association with this key exactly as unverified as it
1183///   was before. `accept_legacy_v0` exists so that upgrading is never a
1184///   silent, implicit side effect of running this function -- an
1185///   operator must explicitly accept that risk. With it `false` (or in
1186///   a dry run), v0 envelopes are still *decrypted* for reporting
1187///   accuracy (see the bullet above) and counted in
1188///   [`KvEncryptionMigrationReport::legacy_v0_found`], but never
1189///   written back; `upgraded_from_legacy` only increases on an actual
1190///   real-run upgrade. Every real upgrade logs one `tracing::warn!` line
1191///   naming a safe identifier for the record (never its raw key or
1192///   value -- see below).
1193/// - **Never logs or reports the raw storage key, plaintext, or
1194///   ciphertext**: in this crate, some storage keys are themselves
1195///   bearer secrets (e.g. `api_key:{raw_api_key}`), so logging a key
1196///   name verbatim can leak a working credential. Everywhere this
1197///   function logs or reports a record (`tracing::warn!` lines,
1198///   [`KvEncryptionMigrationReport::failed`]), it uses a short,
1199///   non-reversible, safe identifier instead of the raw key; callers
1200///   should preserve that if they add their own logging around this.
1201/// - **Not safe to run concurrently with live writes to the same keys**:
1202///   this does a read, then a write-back, with no compare-and-swap. If
1203///   something else writes a fresh value to a key between this function's
1204///   read and write, the write-back here overwrites it with the stale
1205///   value it read. Run this offline, or at least pause writers to the
1206///   given `prefix`, before running it against a live deployment.
1207///
1208/// `storage` and `encryption` are the same values the caller would pass to
1209/// [`EncryptedStorage::new`] -- this function talks to the *inner*,
1210/// unwrapped storage directly, since [`EncryptedStorage::get_kv`] would
1211/// already transparently decrypt (and thus hide which rows still need
1212/// migrating).
1213///
1214/// **TTLs are preserved** on backends that report them
1215/// ([`AuthStorage::tracks_kv_ttl`]): each rewritten entry is stored with
1216/// the remaining TTL it had (read via [`AuthStorage::get_kv_ttl`] before the
1217/// value, so an entry that expires mid-run is skipped, never made
1218/// permanent). A backend that cannot report TTLs would turn every expiring
1219/// entry (OAuth codes, MFA/SMS codes, WebAuthn challenges, rate-limit
1220/// windows, expiring API keys) permanent, so a real (non-dry) run on one is
1221/// **refused** unless [`MigrationOptions::accept_ttl_loss`] is set; if it
1222/// is, scope `prefix` to durable-secret namespaces only. The CLI
1223/// (`security encrypt-kv`) exposes this as `--accept-ttl-loss`.
1224pub async fn migrate_kv_to_encrypted<S: AuthStorage + ?Sized>(
1225    storage: &S,
1226    encryption: &StorageEncryption,
1227    prefix: &str,
1228    options: MigrationOptions,
1229) -> Result<KvEncryptionMigrationReport> {
1230    let MigrationOptions {
1231        dry_run,
1232        accept_legacy_v0,
1233        accept_ttl_loss,
1234    } = options;
1235
1236    // A backend that cannot report TTLs would have every expiring entry
1237    // re-stored as permanent. Refuse before touching anything unless the
1238    // caller accepts that; a dry run writes nothing, so it is always fine.
1239    if !dry_run && !accept_ttl_loss && !storage.tracks_kv_ttl() {
1240        return Err(AuthError::validation(
1241            "This storage backend does not report KV TTLs, so migrating would make every \
1242             expiring entry (OAuth codes, MFA/SMS codes, rate-limit windows, expiring API \
1243             keys, ...) permanent. Scope the prefix to durable secrets and pass \
1244             accept_ttl_loss (CLI: --accept-ttl-loss) to proceed anyway.",
1245        ));
1246    }
1247    let mut report = KvEncryptionMigrationReport {
1248        dry_run,
1249        ..Default::default()
1250    };
1251
1252    let keys = storage.list_kv_keys(prefix).await?;
1253    report.scanned = keys.len() as u64;
1254
1255    for key in keys {
1256        // The TTL is read BEFORE the value (see the maintenance snapshot
1257        // code): an entry that expires in between yields a TTL and no value
1258        // (counted as vanished), never a value whose expiry was lost.
1259        let ttl = storage.get_kv_ttl(&key).await?;
1260        let Some(mut raw) = storage.get_kv(&key).await? else {
1261            // Deleted concurrently between list_kv_keys and get_kv.
1262            report.vanished += 1;
1263            continue;
1264        };
1265
1266        if let Some(envelope) = StorageEncryption::parse_envelope(&raw) {
1267            if envelope.v >= CURRENT_FORMAT_VERSION {
1268                report.already_encrypted += 1;
1269                continue;
1270            }
1271
1272            // Format-version-0 envelope: always attempt the decrypt (so
1273            // dry-run reporting is accurate), but never let a failure
1274            // here abort the rest of the run.
1275            match encryption.decrypt(&envelope, key.as_bytes()) {
1276                Err(_) => {
1277                    tracing::warn!(
1278                        record = %safe_log_id(&key),
1279                        "migrate_kv_to_encrypted: could not decrypt format-version-0 \
1280                         envelope with any loaded key -- skipping, not aborting the rest \
1281                         of the run"
1282                    );
1283                    report.failed.push(safe_log_id(&key));
1284                }
1285                Ok(mut plaintext) => {
1286                    report.legacy_v0_found += 1;
1287                    if !dry_run && accept_legacy_v0 {
1288                        if envelope.v == 0 {
1289                            tracing::warn!(
1290                                record = %safe_log_id(&key),
1291                                "migrate_kv_to_encrypted: upgrading format-version-0 \
1292                                 envelope to the current format -- v0 has no AAD, so this \
1293                                 plaintext's association with this specific key was not \
1294                                 cryptographically verified by this upgrade"
1295                            );
1296                        } else {
1297                            tracing::info!(
1298                                record = %safe_log_id(&key),
1299                                v = envelope.v,
1300                                "migrate_kv_to_encrypted: upgrading legacy envelope to the \
1301                                 current format (its AAD bound the record key)"
1302                            );
1303                        }
1304                        let encrypt_result =
1305                            encryption.encrypt_for_storage(&plaintext, key.as_bytes());
1306                        plaintext.zeroize();
1307                        let new_envelope = encrypt_result?;
1308                        storage.store_kv(&key, &new_envelope, ttl).await?;
1309                        report.upgraded_from_legacy += 1;
1310                    } else {
1311                        plaintext.zeroize();
1312                    }
1313                }
1314            }
1315            continue;
1316        }
1317
1318        report.encrypted += 1;
1319        if !dry_run {
1320            let encrypt_result = encryption.encrypt_for_storage(&raw, key.as_bytes());
1321            raw.zeroize();
1322            let envelope = encrypt_result?;
1323            storage.store_kv(&key, &envelope, ttl).await?;
1324        } else {
1325            raw.zeroize();
1326        }
1327    }
1328
1329    Ok(report)
1330}
1331
1332#[cfg(test)]
1333mod tests {
1334    use super::*;
1335    use crate::storage::MemoryStorage;
1336
1337    #[test]
1338    fn test_key_generation() {
1339        let key = StorageEncryption::generate_key();
1340        assert!(!key.is_empty());
1341        let decoded = BASE64.decode(&key).unwrap();
1342        assert_eq!(decoded.len(), 32);
1343    }
1344
1345    #[test]
1346    fn test_encrypt_decrypt_roundtrip() {
1347        let enc = StorageEncryption::new_random();
1348        let plaintext = b"super secret totp seed, not utf8 safe either: \xff\xfe";
1349        let encrypted = enc.encrypt(plaintext, b"user:alice:totp_secret").unwrap();
1350        let decrypted = enc.decrypt(&encrypted, b"user:alice:totp_secret").unwrap();
1351        assert_eq!(decrypted, plaintext);
1352    }
1353
1354    /// Proves the AAD actually binds the ciphertext to its storage key:
1355    /// decrypting under a DIFFERENT aad than it was encrypted with must
1356    /// fail, not silently succeed with wrong-but-plausible plaintext. This
1357    /// is the mechanism that stops a ciphertext from being swapped between
1358    /// two records.
1359    #[test]
1360    fn test_decrypt_rejects_wrong_aad() {
1361        let enc = StorageEncryption::new_random();
1362        let encrypted = enc
1363            .encrypt(b"alice's secret", b"user:alice:totp_secret")
1364            .unwrap();
1365        let result = enc.decrypt(&encrypted, b"user:bob:totp_secret");
1366        assert!(
1367            result.is_err(),
1368            "decrypting with the wrong AAD (a different record's key) must fail"
1369        );
1370    }
1371
1372    /// Proves nonces are actually random per call, not reused -- the
1373    /// security of AES-GCM depends on this. Encrypts the same plaintext
1374    /// many times and checks every nonce is unique.
1375    #[test]
1376    fn test_nonces_are_unique_across_many_encryptions() {
1377        let enc = StorageEncryption::new_random();
1378        let mut seen = std::collections::HashSet::new();
1379        for _ in 0..1000 {
1380            let encrypted = enc
1381                .encrypt(b"same plaintext every time", b"same:aad")
1382                .unwrap();
1383            assert_eq!(
1384                BASE64.decode(&encrypted.nonce).unwrap().len(),
1385                12,
1386                "nonce must be 96 bits"
1387            );
1388            assert!(
1389                seen.insert(encrypted.nonce.clone()),
1390                "nonce reused across encryptions -- this breaks AES-GCM's security guarantee"
1391            );
1392        }
1393    }
1394
1395    #[test]
1396    fn test_storage_roundtrip_non_utf8_bytes() {
1397        let enc = StorageEncryption::new_random();
1398        let raw_salt: &[u8] = &[0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0xFF, 0x80, 0x81];
1399        let stored = enc.encrypt_for_storage(raw_salt, b"salt:key").unwrap();
1400        let restored = enc.decrypt_from_storage(&stored, b"salt:key").unwrap();
1401        assert_eq!(restored, raw_salt);
1402    }
1403
1404    /// A key provider that resolves to no usable key at all must make
1405    /// construction fail, not silently produce a `StorageEncryption` that
1406    /// can't actually encrypt anything (e.g. by skipping encryption).
1407    struct EmptyKeyProvider;
1408    impl KeyProvider for EmptyKeyProvider {
1409        fn load_keys(&self) -> Result<LoadedKeys> {
1410            Err(AuthError::config("no key configured (test)"))
1411        }
1412    }
1413
1414    #[test]
1415    fn test_construction_fails_closed_with_no_key() {
1416        let result = StorageEncryption::new(&EmptyKeyProvider);
1417        assert!(
1418            result.is_err(),
1419            "StorageEncryption::new must fail, not silently construct an unusable/no-op encryptor"
1420        );
1421    }
1422
1423    struct FixedKeyProvider(LoadedKeys);
1424    impl KeyProvider for FixedKeyProvider {
1425        fn load_keys(&self) -> Result<LoadedKeys> {
1426            Ok(LoadedKeys {
1427                current_key_id: self.0.current_key_id.clone(),
1428                keys: self.0.keys.clone(),
1429            })
1430        }
1431    }
1432
1433    #[test]
1434    fn test_construction_rejects_empty_key_id() {
1435        // current_key_id is non-empty and present in the map (so the
1436        // separate, earlier checks for "current_key_id is empty" and
1437        // "current_key_id isn't in the map" don't fire first) -- this
1438        // specifically exercises the "no key in the map has an empty id"
1439        // check via a SECOND entry.
1440        let mut keys = HashMap::new();
1441        keys.insert("1".to_string(), [1u8; 32]);
1442        keys.insert(String::new(), [2u8; 32]);
1443        let result = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
1444            current_key_id: "1".to_string(),
1445            keys,
1446        }));
1447        assert!(
1448            result.is_err(),
1449            "an empty key id anywhere in the loaded key set must be rejected (it's reserved \
1450             for format-version-0 envelopes), even when current_key_id itself is valid"
1451        );
1452    }
1453
1454    /// Key rotation: an envelope encrypted under an OLD key must still
1455    /// decrypt once the current key id has moved on, as long as the old
1456    /// key is still present in the loaded key set.
1457    struct TwoKeyProvider {
1458        current_id: String,
1459        old_key: [u8; 32],
1460        new_key: [u8; 32],
1461        old_id: String,
1462    }
1463    impl KeyProvider for TwoKeyProvider {
1464        fn load_keys(&self) -> Result<LoadedKeys> {
1465            let mut keys = HashMap::new();
1466            keys.insert(self.old_id.clone(), self.old_key);
1467            keys.insert(self.current_id.clone(), self.new_key);
1468            Ok(LoadedKeys {
1469                current_key_id: self.current_id.clone(),
1470                keys,
1471            })
1472        }
1473    }
1474
1475    #[test]
1476    fn test_old_key_still_decrypts_after_rotation() {
1477        let mut keys = HashMap::new();
1478        keys.insert("1".to_string(), [7u8; 32]);
1479        let enc_before_rotation = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
1480            current_key_id: "1".to_string(),
1481            keys,
1482        }))
1483        .unwrap();
1484        let old_envelope = enc_before_rotation
1485            .encrypt(b"written before rotation", b"some:key")
1486            .unwrap();
1487        assert_eq!(old_envelope.key_id, "1");
1488
1489        // Now rotate: current key id moves to "2", but "1" is kept around.
1490        let provider = TwoKeyProvider {
1491            current_id: "2".to_string(),
1492            old_id: "1".to_string(),
1493            old_key: [7u8; 32],
1494            new_key: [9u8; 32],
1495        };
1496        let enc_after_rotation = StorageEncryption::new(&provider).unwrap();
1497
1498        // New writes use the new key.
1499        let new_envelope = enc_after_rotation
1500            .encrypt(b"written after rotation", b"some:key")
1501            .unwrap();
1502        assert_eq!(new_envelope.key_id, "2");
1503
1504        // The OLD envelope (key_id "1") must still decrypt.
1505        let decrypted_old = enc_after_rotation
1506            .decrypt(&old_envelope, b"some:key")
1507            .unwrap();
1508        assert_eq!(decrypted_old, b"written before rotation");
1509    }
1510
1511    /// Format-version-0 compatibility: an envelope shaped like the
1512    /// original (pre-redesign) `EncryptedStorage` produced -- no `key_id`,
1513    /// no `v`, no AAD at encryption time -- must still decrypt under the
1514    /// new `StorageEncryption`, since real deployments may already hold
1515    /// data in that shape.
1516    #[test]
1517    fn test_decrypts_format_version_0_envelope() {
1518        let mut keys = HashMap::new();
1519        keys.insert("1".to_string(), [3u8; 32]);
1520        let enc = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
1521            current_key_id: "1".to_string(),
1522            keys,
1523        }))
1524        .unwrap();
1525
1526        // Hand-build a format-version-0 envelope the way the original
1527        // `EncryptedStorage::encrypt` did: no AAD, no key_id, no v.
1528        let cipher = {
1529            let key = Key::<Aes256Gcm>::from_slice(&[3u8; 32]);
1530            Aes256Gcm::new(key)
1531        };
1532        let nonce_bytes = [5u8; 12];
1533        let nonce = Nonce::from_slice(&nonce_bytes);
1534        let ciphertext = cipher
1535            .encrypt(nonce, b"legacy-format plaintext".as_ref())
1536            .unwrap();
1537        let legacy_json = format!(
1538            r#"{{"data":"{}","nonce":"{}","algorithm":"AES-256-GCM","key_derivation":"direct"}}"#,
1539            BASE64.encode(&ciphertext),
1540            BASE64.encode(nonce_bytes)
1541        );
1542
1543        assert!(StorageEncryption::looks_like_envelope(
1544            legacy_json.as_bytes()
1545        ));
1546        let decrypted = enc
1547            .decrypt_from_storage(legacy_json.as_bytes(), b"irrelevant-for-v0")
1548            .unwrap();
1549        assert_eq!(decrypted, b"legacy-format plaintext".to_vec());
1550    }
1551
1552    /// Negative case for the v0 downgrade attack: a GENUINE current-format
1553    /// (v1) envelope, with its `v` and `key_id` fields stripped (so it now
1554    /// parses as a v0-shaped envelope), must not be accepted as that
1555    /// record's value. It fails for two independent reasons here -- the
1556    /// policy check (`allow_legacy_v0: false` by default) rejects it before
1557    /// any decryption is attempted, and even without that check the
1558    /// ciphertext itself was sealed with a real (non-empty) AAD, so the v0
1559    /// path's empty-AAD decrypt attempt would fail the authentication tag
1560    /// anyway.
1561    #[tokio::test]
1562    async fn test_wrapper_rejects_v1_envelope_downgraded_to_look_like_v0() {
1563        let mut keys = HashMap::new();
1564        keys.insert("1".to_string(), [4u8; 32]);
1565        let encryption = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
1566            current_key_id: "1".to_string(),
1567            keys,
1568        }))
1569        .unwrap();
1570
1571        let inner = MemoryStorage::new();
1572        let wrapped = EncryptedStorage::new(inner, encryption, false, false);
1573
1574        wrapped
1575            .store_kv("user:alice:totp_secret", b"real secret", None)
1576            .await
1577            .unwrap();
1578
1579        let inner = wrapped.into_inner();
1580        let real_envelope: EncryptedData = serde_json::from_slice(
1581            &inner
1582                .get_kv("user:alice:totp_secret")
1583                .await
1584                .unwrap()
1585                .unwrap(),
1586        )
1587        .unwrap();
1588
1589        // Strip the fields a v0 envelope never had, simulating an
1590        // attacker (or a bug) downgrading a real v1 envelope.
1591        let downgraded_json = serde_json::json!({
1592            "data": real_envelope.data,
1593            "nonce": real_envelope.nonce,
1594            "algorithm": real_envelope.algorithm,
1595        })
1596        .to_string();
1597        inner
1598            .store_kv("user:alice:totp_secret", downgraded_json.as_bytes(), None)
1599            .await
1600            .unwrap();
1601
1602        let mut keys2 = HashMap::new();
1603        keys2.insert("1".to_string(), [4u8; 32]);
1604        let encryption2 = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
1605            current_key_id: "1".to_string(),
1606            keys: keys2,
1607        }))
1608        .unwrap();
1609        let wrapped = EncryptedStorage::new(inner, encryption2, false, false);
1610
1611        let result = wrapped.get_kv("user:alice:totp_secret").await;
1612        assert!(
1613            result.is_err(),
1614            "a v1 envelope downgraded to look like v0 must not be accepted as the record's \
1615             value, with allow_legacy_v0 at its default (false)"
1616        );
1617    }
1618
1619    #[tokio::test]
1620    async fn test_list_kv_keys_passes_through_unencrypted() {
1621        let inner = MemoryStorage::new();
1622        inner
1623            .store_kv("prefix:a", b"ignored by this test", None)
1624            .await
1625            .unwrap();
1626        inner
1627            .store_kv("prefix:b", b"ignored by this test", None)
1628            .await
1629            .unwrap();
1630        let wrapped = EncryptedStorage::new(inner, StorageEncryption::new_random(), false, false);
1631
1632        let mut keys = wrapped.list_kv_keys("prefix:").await.unwrap();
1633        keys.sort();
1634        assert_eq!(
1635            keys,
1636            vec!["prefix:a".to_string(), "prefix:b".to_string()],
1637            "list_kv_keys must pass through to the inner backend, not use the trait's \
1638             empty-Vec default"
1639        );
1640    }
1641
1642    #[tokio::test]
1643    async fn test_encrypted_storage_roundtrip() {
1644        let inner = MemoryStorage::new();
1645        let wrapped = EncryptedStorage::new(inner, StorageEncryption::new_random(), false, false);
1646
1647        wrapped
1648            .store_kv("user:alice:totp_secret", b"JBSWY3DPEHPK3PXP", None)
1649            .await
1650            .unwrap();
1651        let value = wrapped.get_kv("user:alice:totp_secret").await.unwrap();
1652        assert_eq!(value, Some(b"JBSWY3DPEHPK3PXP".to_vec()));
1653    }
1654
1655    /// Proves the wrapper actually changes what's on disk/in the backend
1656    /// -- reading through the INNER storage directly (bypassing
1657    /// `EncryptedStorage`) must NOT show the plaintext.
1658    #[tokio::test]
1659    async fn test_encrypted_storage_actually_encrypts_the_underlying_value() {
1660        let wrapped = EncryptedStorage::new(
1661            MemoryStorage::new(),
1662            StorageEncryption::new_random(),
1663            false,
1664            false,
1665        );
1666
1667        wrapped
1668            .store_kv("user:alice:totp_secret", b"JBSWY3DPEHPK3PXP", None)
1669            .await
1670            .unwrap();
1671
1672        let inner = wrapped.into_inner();
1673        let raw = inner
1674            .get_kv("user:alice:totp_secret")
1675            .await
1676            .unwrap()
1677            .unwrap();
1678        assert_ne!(
1679            raw,
1680            b"JBSWY3DPEHPK3PXP".to_vec(),
1681            "the underlying storage must not hold the plaintext value"
1682        );
1683        assert!(
1684            StorageEncryption::looks_like_envelope(&raw),
1685            "the underlying storage must hold a proper encrypted envelope"
1686        );
1687    }
1688
1689    /// Proves the wrapper's own AAD wiring (not just `StorageEncryption`
1690    /// directly, which `test_decrypt_rejects_wrong_aad` already covers) --
1691    /// swapping two records' raw envelopes in the INNER backend must make
1692    /// both unreadable through the wrapper, because each envelope's AAD no
1693    /// longer matches the key it's stored under. If the wrapper passed a
1694    /// constant (e.g. empty) AAD instead of the real key, this swap would
1695    /// go undetected and both reads would "succeed" with the wrong value.
1696    #[tokio::test]
1697    async fn test_wrapper_rejects_ciphertext_swapped_between_records() {
1698        let mut keys = HashMap::new();
1699        keys.insert("1".to_string(), [11u8; 32]);
1700        let loaded = LoadedKeys {
1701            current_key_id: "1".to_string(),
1702            keys,
1703        };
1704        let encryption_for_wrapper = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
1705            current_key_id: loaded.current_key_id.clone(),
1706            keys: loaded.keys.clone(),
1707        }))
1708        .unwrap();
1709        // An independent `StorageEncryption` built from the SAME key, used
1710        // only to verify what AAD the wrapper actually used -- never to
1711        // produce the envelopes under test.
1712        let encryption_for_verification =
1713            StorageEncryption::new(&FixedKeyProvider(loaded)).unwrap();
1714
1715        let inner = MemoryStorage::new();
1716        let wrapped = EncryptedStorage::new(inner, encryption_for_wrapper, false, false);
1717
1718        wrapped
1719            .store_kv("user:alice:totp_secret", b"alice-secret", None)
1720            .await
1721            .unwrap();
1722
1723        let inner = wrapped.into_inner();
1724        let raw = inner
1725            .get_kv("user:alice:totp_secret")
1726            .await
1727            .unwrap()
1728            .unwrap();
1729
1730        // The wrapper must have used the storage key itself as AAD: decrypting
1731        // with that exact AAD must succeed...
1732        let decrypted = encryption_for_verification
1733            .decrypt(
1734                &serde_json::from_slice(&raw).unwrap(),
1735                b"user:alice:totp_secret",
1736            )
1737            .unwrap();
1738        assert_eq!(decrypted, b"alice-secret".to_vec());
1739
1740        // ...and decrypting the SAME envelope under a DIFFERENT record's key
1741        // name must fail. If the wrapper instead used some constant AAD (the
1742        // exact mutation this test exists to catch), this swap-style check
1743        // would succeed instead of failing.
1744        let wrong_aad_result = encryption_for_verification.decrypt(
1745            &serde_json::from_slice(&raw).unwrap(),
1746            b"user:bob:totp_secret",
1747        );
1748        assert!(
1749            wrong_aad_result.is_err(),
1750            "the wrapper's envelope must not decrypt under a different record's key name -- \
1751             if it does, the wrapper is using a constant AAD instead of the real storage key"
1752        );
1753    }
1754
1755    /// A value stored by some pre-encryption version of the framework (or
1756    /// while `storage_encryption.enabled = false`) is readable when
1757    /// `allow_plaintext_reads` is explicitly true (the migration-window
1758    /// setting).
1759    #[tokio::test]
1760    async fn test_reads_legacy_plaintext_when_allowed() {
1761        let inner = MemoryStorage::new();
1762        inner
1763            .store_kv("legacy:key", b"pre-existing plaintext value", None)
1764            .await
1765            .unwrap();
1766        let wrapped = EncryptedStorage::new(inner, StorageEncryption::new_random(), true, false);
1767
1768        let value = wrapped.get_kv("legacy:key").await.unwrap();
1769        assert_eq!(value, Some(b"pre-existing plaintext value".to_vec()));
1770    }
1771
1772    /// With `allow_plaintext_reads` false (the normal, post-migration
1773    /// setting), a value that isn't a valid envelope -- whether genuine
1774    /// untouched legacy plaintext, a corrupted envelope, or an attacker's
1775    /// overwrite -- must be a hard error, not silently accepted. This is
1776    /// the fix for the finding that an attacker able to write to the
1777    /// backing store could otherwise overwrite an encrypted secret with
1778    /// chosen plaintext and have it accepted forever.
1779    #[tokio::test]
1780    async fn test_rejects_non_envelope_value_when_plaintext_reads_disallowed() {
1781        let inner = MemoryStorage::new();
1782        inner
1783            .store_kv("user:alice:totp_secret", b"attacker-chosen-plaintext", None)
1784            .await
1785            .unwrap();
1786        let wrapped = EncryptedStorage::new(inner, StorageEncryption::new_random(), false, false);
1787
1788        let result = wrapped.get_kv("user:alice:totp_secret").await;
1789        assert!(
1790            result.is_err(),
1791            "a non-envelope value must be rejected, not silently treated as plaintext, \
1792             when allow_plaintext_reads is false"
1793        );
1794    }
1795
1796    /// The real fix for the v0-downgrade finding: a format-version-0
1797    /// envelope must be actively rewritten to the current format by
1798    /// migration (not just counted as "already encrypted" and left
1799    /// alone), since nothing else in this crate ever upgrades one.
1800    #[tokio::test]
1801    async fn test_migration_upgrades_v0_envelope_to_current_format() {
1802        let mut keys = HashMap::new();
1803        keys.insert("1".to_string(), [6u8; 32]);
1804        let encryption = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
1805            current_key_id: "1".to_string(),
1806            keys,
1807        }))
1808        .unwrap();
1809
1810        // Hand-build a v0 envelope the way the original pre-redesign
1811        // `EncryptedStorage` did (no AAD, no key_id, no v).
1812        let cipher = {
1813            let key = Key::<Aes256Gcm>::from_slice(&[6u8; 32]);
1814            Aes256Gcm::new(key)
1815        };
1816        let nonce_bytes = [8u8; 12];
1817        let nonce = Nonce::from_slice(&nonce_bytes);
1818        let ciphertext = cipher.encrypt(nonce, b"v0 secret".as_ref()).unwrap();
1819        let v0_json = format!(
1820            r#"{{"data":"{}","nonce":"{}","algorithm":"AES-256-GCM","key_derivation":"direct"}}"#,
1821            BASE64.encode(&ciphertext),
1822            BASE64.encode(nonce_bytes)
1823        );
1824
1825        let storage = MemoryStorage::new();
1826        storage
1827            .store_kv("secret:legacy", v0_json.as_bytes(), None)
1828            .await
1829            .unwrap();
1830
1831        let report = migrate_kv_to_encrypted(
1832            &storage,
1833            &encryption,
1834            "secret:",
1835            MigrationOptions {
1836                dry_run: false,
1837                accept_legacy_v0: true,
1838                ..Default::default()
1839            },
1840        )
1841        .await
1842        .unwrap();
1843        assert_eq!(
1844            report.legacy_v0_found, 1,
1845            "a decryptable v0 envelope must be counted as found"
1846        );
1847        assert_eq!(
1848            report.upgraded_from_legacy, 1,
1849            "with accept_legacy_v0 true on a real run, it must actually be upgraded"
1850        );
1851        assert_eq!(report.already_encrypted, 0);
1852        assert!(report.failed.is_empty());
1853
1854        let raw_after = storage.get_kv("secret:legacy").await.unwrap().unwrap();
1855        let envelope_after: EncryptedData = serde_json::from_slice(&raw_after).unwrap();
1856        assert_eq!(
1857            envelope_after.v, CURRENT_FORMAT_VERSION,
1858            "the stored envelope must now be the current format, not still v0"
1859        );
1860        assert!(
1861            !envelope_after.key_id.is_empty(),
1862            "the upgraded envelope must have a real key_id"
1863        );
1864
1865        // The upgraded envelope must decrypt correctly through the
1866        // normal (AAD-bound) path -- not just via the v0 fallback.
1867        let decrypted = encryption
1868            .decrypt(&envelope_after, b"secret:legacy")
1869            .unwrap();
1870        assert_eq!(decrypted, b"v0 secret".to_vec());
1871
1872        // Idempotent: running it again finds nothing left to upgrade.
1873        let report2 = migrate_kv_to_encrypted(
1874            &storage,
1875            &encryption,
1876            "secret:",
1877            MigrationOptions {
1878                dry_run: false,
1879                accept_legacy_v0: false,
1880                ..Default::default()
1881            },
1882        )
1883        .await
1884        .unwrap();
1885        assert_eq!(report2.upgraded_from_legacy, 0);
1886        assert_eq!(report2.already_encrypted, 1);
1887    }
1888
1889    /// Without `accept_legacy_v0`, a decryptable v0 envelope is reported
1890    /// (`legacy_v0_found`) but never written back as the current format --
1891    /// this is the fix for the laundering finding: upgrading must never be
1892    /// an implicit side effect of just running the migration.
1893    #[tokio::test]
1894    async fn test_migration_does_not_upgrade_legacy_v0_without_accept_flag() {
1895        let mut keys = HashMap::new();
1896        keys.insert("1".to_string(), [7u8; 32]);
1897        let encryption = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
1898            current_key_id: "1".to_string(),
1899            keys,
1900        }))
1901        .unwrap();
1902
1903        let cipher = {
1904            let key = Key::<Aes256Gcm>::from_slice(&[7u8; 32]);
1905            Aes256Gcm::new(key)
1906        };
1907        let nonce_bytes = [3u8; 12];
1908        let nonce = Nonce::from_slice(&nonce_bytes);
1909        let ciphertext = cipher.encrypt(nonce, b"v0 secret".as_ref()).unwrap();
1910        let v0_json = format!(
1911            r#"{{"data":"{}","nonce":"{}","algorithm":"AES-256-GCM","key_derivation":"direct"}}"#,
1912            BASE64.encode(&ciphertext),
1913            BASE64.encode(nonce_bytes)
1914        );
1915
1916        let storage = MemoryStorage::new();
1917        storage
1918            .store_kv("secret:legacy", v0_json.as_bytes(), None)
1919            .await
1920            .unwrap();
1921
1922        // Real run (not dry), but accept_legacy_v0 is false.
1923        let report = migrate_kv_to_encrypted(
1924            &storage,
1925            &encryption,
1926            "secret:",
1927            MigrationOptions {
1928                dry_run: false,
1929                accept_legacy_v0: false,
1930                ..Default::default()
1931            },
1932        )
1933        .await
1934        .unwrap();
1935        assert_eq!(
1936            report.legacy_v0_found, 1,
1937            "the v0 envelope must still be detected/decrypted"
1938        );
1939        assert_eq!(
1940            report.upgraded_from_legacy, 0,
1941            "without accept_legacy_v0, nothing must actually be rewritten"
1942        );
1943
1944        let raw_after = storage.get_kv("secret:legacy").await.unwrap().unwrap();
1945        assert_eq!(
1946            raw_after,
1947            v0_json.as_bytes(),
1948            "the stored envelope must be byte-for-byte unchanged without accept_legacy_v0"
1949        );
1950    }
1951
1952    /// Fix for the "one bad record aborts the whole run" finding: a v0
1953    /// envelope that fails to decrypt under any loaded key must be
1954    /// skipped and reported by name, not abort processing of the other
1955    /// keys in the same run.
1956    #[tokio::test]
1957    async fn test_migration_skips_undecryptable_v0_envelope_without_aborting() {
1958        let mut keys = HashMap::new();
1959        keys.insert("1".to_string(), [9u8; 32]);
1960        let encryption = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
1961            current_key_id: "1".to_string(),
1962            keys,
1963        }))
1964        .unwrap();
1965
1966        // A v0-shaped envelope with ciphertext that will NOT decrypt
1967        // under the loaded key (wrong key material entirely).
1968        let bad_cipher = {
1969            let key = Key::<Aes256Gcm>::from_slice(&[0u8; 32]);
1970            Aes256Gcm::new(key)
1971        };
1972        let nonce_bytes = [1u8; 12];
1973        let nonce = Nonce::from_slice(&nonce_bytes);
1974        let bad_ciphertext = bad_cipher
1975            .encrypt(nonce, b"undecryptable".as_ref())
1976            .unwrap();
1977        let bad_v0_json = format!(
1978            r#"{{"data":"{}","nonce":"{}","algorithm":"AES-256-GCM","key_derivation":"direct"}}"#,
1979            BASE64.encode(&bad_ciphertext),
1980            BASE64.encode(nonce_bytes)
1981        );
1982
1983        let storage = MemoryStorage::new();
1984        storage
1985            .store_kv("secret:bad", bad_v0_json.as_bytes(), None)
1986            .await
1987            .unwrap();
1988        storage
1989            .store_kv("secret:good_a", b"plaintext-a", None)
1990            .await
1991            .unwrap();
1992        storage
1993            .store_kv("secret:good_b", b"plaintext-b", None)
1994            .await
1995            .unwrap();
1996
1997        let report = migrate_kv_to_encrypted(
1998            &storage,
1999            &encryption,
2000            "secret:",
2001            MigrationOptions {
2002                dry_run: false,
2003                accept_legacy_v0: true,
2004                ..Default::default()
2005            },
2006        )
2007        .await
2008        .expect("one undecryptable record must not abort the whole migration");
2009
2010        assert_eq!(report.scanned, 3);
2011        assert_eq!(
2012            report.failed,
2013            vec![safe_log_id("secret:bad")],
2014            "the undecryptable record must be named (as a safe identifier, not the raw \
2015             key) in `failed`, not silently dropped"
2016        );
2017        assert_eq!(
2018            report.encrypted, 2,
2019            "the other two plaintext keys must still be processed despite the bad one"
2020        );
2021
2022        let good_a_after = storage.get_kv("secret:good_a").await.unwrap().unwrap();
2023        assert!(StorageEncryption::looks_like_envelope(&good_a_after));
2024        let good_b_after = storage.get_kv("secret:good_b").await.unwrap().unwrap();
2025        assert!(StorageEncryption::looks_like_envelope(&good_b_after));
2026
2027        // The bad record itself is untouched (still its original bytes).
2028        let bad_after = storage.get_kv("secret:bad").await.unwrap().unwrap();
2029        assert_eq!(bad_after, bad_v0_json.as_bytes());
2030    }
2031
2032    /// Fix for "dry run lies": a dry run must actually attempt the v0
2033    /// decrypt (not just assume success), so an undecryptable v0 envelope
2034    /// shows up in `failed` during a dry run too, matching what a real
2035    /// run would report.
2036    #[tokio::test]
2037    async fn test_migration_dry_run_detects_undecryptable_v0_envelope() {
2038        let mut keys = HashMap::new();
2039        keys.insert("1".to_string(), [5u8; 32]);
2040        let encryption = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
2041            current_key_id: "1".to_string(),
2042            keys,
2043        }))
2044        .unwrap();
2045
2046        let bad_cipher = {
2047            let key = Key::<Aes256Gcm>::from_slice(&[0u8; 32]);
2048            Aes256Gcm::new(key)
2049        };
2050        let nonce_bytes = [2u8; 12];
2051        let nonce = Nonce::from_slice(&nonce_bytes);
2052        let bad_ciphertext = bad_cipher
2053            .encrypt(nonce, b"undecryptable".as_ref())
2054            .unwrap();
2055        let bad_v0_json = format!(
2056            r#"{{"data":"{}","nonce":"{}","algorithm":"AES-256-GCM","key_derivation":"direct"}}"#,
2057            BASE64.encode(&bad_ciphertext),
2058            BASE64.encode(nonce_bytes)
2059        );
2060
2061        let storage = MemoryStorage::new();
2062        storage
2063            .store_kv("secret:bad", bad_v0_json.as_bytes(), None)
2064            .await
2065            .unwrap();
2066
2067        let dry_report = migrate_kv_to_encrypted(
2068            &storage,
2069            &encryption,
2070            "secret:",
2071            MigrationOptions {
2072                dry_run: true,
2073                accept_legacy_v0: true,
2074                ..Default::default()
2075            },
2076        )
2077        .await
2078        .unwrap();
2079        assert_eq!(
2080            dry_report.failed,
2081            vec![safe_log_id("secret:bad")],
2082            "a dry run must actually attempt the decrypt and report the same failure a \
2083             real run would, not optimistically assume every v0 envelope would succeed"
2084        );
2085        assert_eq!(dry_report.upgraded_from_legacy, 0);
2086        assert_eq!(dry_report.legacy_v0_found, 0);
2087    }
2088
2089    /// Fix for the high-severity finding: some storage keys in this
2090    /// crate ARE bearer secrets (`api_key:{raw_key}`), so a safe log
2091    /// identifier must never contain the raw key material -- only the
2092    /// namespace and a hash.
2093    #[test]
2094    fn test_safe_log_id_never_contains_the_raw_secret() {
2095        let raw_secret = "ak_live_super_secret_bearer_token_12345";
2096        let key = format!("api_key:{raw_secret}");
2097        let id = safe_log_id(&key);
2098
2099        assert!(
2100            !id.contains(raw_secret),
2101            "safe_log_id must never contain the raw secret portion of the key, got: {id}"
2102        );
2103        assert!(
2104            id.starts_with("api_key:"),
2105            "safe_log_id should keep the (non-secret) namespace prefix, got: {id}"
2106        );
2107        // Deterministic, so an operator with storage access can
2108        // recompute it to correlate a logged identifier back to a
2109        // specific record.
2110        assert_eq!(id, safe_log_id(&key));
2111    }
2112
2113    /// A key with no `:` at all has no non-secret namespace prefix to
2114    /// keep -- `key.split(':').next()` on a colonless key returns the
2115    /// WHOLE key, which would print the raw secret verbatim. This is
2116    /// the fix for that gap.
2117    #[test]
2118    fn test_safe_log_id_handles_colonless_key_without_leaking_it() {
2119        let raw_secret = "a_bearer_token_with_no_colon_in_it_at_all";
2120        let id = safe_log_id(raw_secret);
2121
2122        assert!(
2123            !id.contains(raw_secret),
2124            "a colonless key must not appear verbatim in its safe_log_id, got: {id}"
2125        );
2126        assert!(
2127            id.starts_with("key:"),
2128            "a colonless key should fall back to the literal 'key:' prefix, got: {id}"
2129        );
2130    }
2131
2132    /// Kills the mutation `if !dry_run && accept_legacy_v0` ->
2133    /// `if accept_legacy_v0` (dropping the dry-run check): with
2134    /// accept_legacy_v0 true but dry_run also true, over a DECRYPTABLE
2135    /// v0 record, nothing must be written -- the only existing
2136    /// dry-run-with-flag test used an undecryptable record, which never
2137    /// reaches this branch at all.
2138    #[tokio::test]
2139    async fn test_dry_run_with_accept_legacy_v0_does_not_write_a_decryptable_v0_record() {
2140        let mut keys = HashMap::new();
2141        keys.insert("1".to_string(), [4u8; 32]);
2142        let encryption = StorageEncryption::new(&FixedKeyProvider(LoadedKeys {
2143            current_key_id: "1".to_string(),
2144            keys,
2145        }))
2146        .unwrap();
2147
2148        let cipher = {
2149            let key = Key::<Aes256Gcm>::from_slice(&[4u8; 32]);
2150            Aes256Gcm::new(key)
2151        };
2152        let nonce_bytes = [6u8; 12];
2153        let nonce = Nonce::from_slice(&nonce_bytes);
2154        let ciphertext = cipher.encrypt(nonce, b"v0 secret".as_ref()).unwrap();
2155        let v0_json = format!(
2156            r#"{{"data":"{}","nonce":"{}","algorithm":"AES-256-GCM","key_derivation":"direct"}}"#,
2157            BASE64.encode(&ciphertext),
2158            BASE64.encode(nonce_bytes)
2159        );
2160
2161        let storage = MemoryStorage::new();
2162        storage
2163            .store_kv("secret:legacy", v0_json.as_bytes(), None)
2164            .await
2165            .unwrap();
2166
2167        // dry_run: true AND accept_legacy_v0: true.
2168        let report = migrate_kv_to_encrypted(
2169            &storage,
2170            &encryption,
2171            "secret:",
2172            MigrationOptions {
2173                dry_run: true,
2174                accept_legacy_v0: true,
2175                ..Default::default()
2176            },
2177        )
2178        .await
2179        .unwrap();
2180
2181        assert_eq!(
2182            report.legacy_v0_found, 1,
2183            "a dry run must still report a decryptable v0 record as found"
2184        );
2185        assert_eq!(
2186            report.upgraded_from_legacy, 0,
2187            "a dry run must never actually upgrade anything, even with accept_legacy_v0 true"
2188        );
2189
2190        let raw_after = storage.get_kv("secret:legacy").await.unwrap().unwrap();
2191        assert_eq!(
2192            raw_after,
2193            v0_json.as_bytes(),
2194            "a dry run with accept_legacy_v0 true must leave the record byte-for-byte \
2195             unchanged"
2196        );
2197    }
2198
2199    #[tokio::test]
2200    async fn test_migration_dry_run_reports_without_writing() {
2201        let storage = MemoryStorage::new();
2202        storage
2203            .store_kv("secret:a", b"plaintext-a", None)
2204            .await
2205            .unwrap();
2206        storage
2207            .store_kv("secret:b", b"plaintext-b", None)
2208            .await
2209            .unwrap();
2210        let encryption = StorageEncryption::new_random();
2211
2212        let report = migrate_kv_to_encrypted(
2213            &storage,
2214            &encryption,
2215            "secret:",
2216            MigrationOptions {
2217                dry_run: true,
2218                accept_legacy_v0: false,
2219                ..Default::default()
2220            },
2221        )
2222        .await
2223        .unwrap();
2224
2225        assert!(report.dry_run);
2226        assert_eq!(report.scanned, 2);
2227        assert_eq!(report.encrypted, 2);
2228        assert_eq!(report.already_encrypted, 0);
2229
2230        // Dry run must not have written anything.
2231        let still_plaintext = storage.get_kv("secret:a").await.unwrap().unwrap();
2232        assert_eq!(still_plaintext, b"plaintext-a".to_vec());
2233    }
2234
2235    #[tokio::test]
2236    async fn test_migration_encrypts_plaintext_values() {
2237        let storage = MemoryStorage::new();
2238        storage
2239            .store_kv("secret:a", b"plaintext-a", None)
2240            .await
2241            .unwrap();
2242        let encryption = StorageEncryption::new_random();
2243
2244        let report = migrate_kv_to_encrypted(
2245            &storage,
2246            &encryption,
2247            "secret:",
2248            MigrationOptions {
2249                dry_run: false,
2250                accept_legacy_v0: false,
2251                ..Default::default()
2252            },
2253        )
2254        .await
2255        .unwrap();
2256        assert_eq!(report.encrypted, 1);
2257
2258        let raw = storage.get_kv("secret:a").await.unwrap().unwrap();
2259        assert!(StorageEncryption::looks_like_envelope(&raw));
2260        let decrypted = encryption.decrypt_from_storage(&raw, b"secret:a").unwrap();
2261        assert_eq!(decrypted, b"plaintext-a".to_vec());
2262    }
2263
2264    /// Proves idempotency and resumability: running the migration a
2265    /// second time over a mix of already-migrated and still-plaintext
2266    /// keys (simulating an interrupted first run) must not re-encrypt
2267    /// (double-encrypt) the already-done ones, and must finish the rest.
2268    #[tokio::test]
2269    async fn test_migration_is_idempotent_and_resumable() {
2270        let storage = MemoryStorage::new();
2271        storage
2272            .store_kv("secret:a", b"plaintext-a", None)
2273            .await
2274            .unwrap();
2275        storage
2276            .store_kv("secret:b", b"plaintext-b", None)
2277            .await
2278            .unwrap();
2279        let encryption = StorageEncryption::new_random();
2280
2281        // Simulate a first run that only got through "secret:a" before
2282        // being interrupted.
2283        let envelope_a = encryption
2284            .encrypt_for_storage(b"plaintext-a", b"secret:a")
2285            .unwrap();
2286        storage
2287            .store_kv("secret:a", &envelope_a, None)
2288            .await
2289            .unwrap();
2290
2291        // Resume: should skip "secret:a" (already encrypted) and finish
2292        // "secret:b".
2293        let report = migrate_kv_to_encrypted(
2294            &storage,
2295            &encryption,
2296            "secret:",
2297            MigrationOptions {
2298                dry_run: false,
2299                accept_legacy_v0: false,
2300                ..Default::default()
2301            },
2302        )
2303        .await
2304        .unwrap();
2305        assert_eq!(report.scanned, 2);
2306        assert_eq!(report.already_encrypted, 1);
2307        assert_eq!(report.encrypted, 1);
2308
2309        let raw_a_after = storage.get_kv("secret:a").await.unwrap().unwrap();
2310        assert_eq!(
2311            raw_a_after, envelope_a,
2312            "an already-encrypted value must be left byte-for-byte unchanged, not double-encrypted"
2313        );
2314        let raw_b_after = storage.get_kv("secret:b").await.unwrap().unwrap();
2315        assert!(StorageEncryption::looks_like_envelope(&raw_b_after));
2316
2317        // Running it again changes nothing further.
2318        let report2 = migrate_kv_to_encrypted(
2319            &storage,
2320            &encryption,
2321            "secret:",
2322            MigrationOptions {
2323                dry_run: false,
2324                accept_legacy_v0: false,
2325                ..Default::default()
2326            },
2327        )
2328        .await
2329        .unwrap();
2330        assert_eq!(report2.already_encrypted, 2);
2331        assert_eq!(report2.encrypted, 0);
2332    }
2333
2334    #[tokio::test]
2335    async fn test_migration_only_touches_matching_prefix() {
2336        let storage = MemoryStorage::new();
2337        storage
2338            .store_kv("secret:a", b"plaintext-a", None)
2339            .await
2340            .unwrap();
2341        storage
2342            .store_kv("other:b", b"plaintext-b", None)
2343            .await
2344            .unwrap();
2345        let encryption = StorageEncryption::new_random();
2346
2347        let report = migrate_kv_to_encrypted(
2348            &storage,
2349            &encryption,
2350            "secret:",
2351            MigrationOptions {
2352                dry_run: false,
2353                accept_legacy_v0: false,
2354                ..Default::default()
2355            },
2356        )
2357        .await
2358        .unwrap();
2359        assert_eq!(report.scanned, 1);
2360
2361        let other_untouched = storage.get_kv("other:b").await.unwrap().unwrap();
2362        assert_eq!(
2363            other_untouched,
2364            b"plaintext-b".to_vec(),
2365            "a key outside the given prefix must not be touched"
2366        );
2367    }
2368
2369    /// The wrapper must report the inner backend's TTL: restore (#121)
2370    /// reads it through the wrapper the framework actually holds.
2371    #[tokio::test]
2372    async fn wrapper_passes_kv_ttl_through() {
2373        let wrapped = EncryptedStorage::new(
2374            MemoryStorage::new(),
2375            StorageEncryption::new_random(),
2376            false,
2377            false,
2378        );
2379        wrapped
2380            .store_kv("k", b"v", Some(Duration::from_secs(600)))
2381            .await
2382            .unwrap();
2383        let ttl = wrapped.get_kv_ttl("k").await.unwrap().unwrap();
2384        assert!(ttl > Duration::from_secs(590) && ttl <= Duration::from_secs(600));
2385    }
2386
2387    // ---- envelope v2 + hardening ------------------------------------------------
2388
2389    struct FixedKeys {
2390        current: &'static str,
2391        keys: Vec<(&'static str, [u8; 32])>,
2392    }
2393
2394    impl KeyProvider for FixedKeys {
2395        fn load_keys(&self) -> Result<LoadedKeys> {
2396            Ok(LoadedKeys {
2397                current_key_id: self.current.to_string(),
2398                keys: self
2399                    .keys
2400                    .iter()
2401                    .map(|(id, key)| (id.to_string(), *key))
2402                    .collect(),
2403            })
2404        }
2405    }
2406
2407    const KEY_A: [u8; 32] = [0x11; 32];
2408    const KEY_B: [u8; 32] = [0x22; 32];
2409
2410    /// Builds a stored envelope by hand, the way an OLDER writer would have:
2411    /// `aad` is used verbatim (v1 used the bare storage key).
2412    fn manual_envelope(
2413        key: &[u8; 32],
2414        key_id: &str,
2415        v: u8,
2416        plaintext: &[u8],
2417        aad: &[u8],
2418    ) -> Vec<u8> {
2419        let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key));
2420        let nonce_bytes = [7u8; 12];
2421        let ciphertext = cipher
2422            .encrypt(
2423                Nonce::from_slice(&nonce_bytes),
2424                Payload {
2425                    msg: plaintext,
2426                    aad,
2427                },
2428            )
2429            .unwrap();
2430        serde_json::to_vec(&EncryptedData {
2431            data: BASE64.encode(ciphertext),
2432            nonce: BASE64.encode(nonce_bytes),
2433            algorithm: "AES-256-GCM".to_string(),
2434            key_id: key_id.to_string(),
2435            v,
2436            key_derivation: String::new(),
2437        })
2438        .unwrap()
2439    }
2440
2441    #[test]
2442    fn new_envelopes_use_format_v2() {
2443        let enc = StorageEncryption::new_random();
2444        assert_eq!(enc.encrypt(b"x", b"k").unwrap().v, 2);
2445    }
2446
2447    /// v2 binds the envelope's own metadata into the AAD: the same key
2448    /// loaded under two ids must NOT let an attacker relabel `key_id`, and
2449    /// rewriting `v` to 1 (a downgrade to the AAD that ignores metadata)
2450    /// must not make a v2 ciphertext verify.
2451    #[test]
2452    fn v2_aad_binds_key_id_and_version() {
2453        let enc = StorageEncryption::new(&FixedKeys {
2454            current: "a",
2455            keys: vec![("a", KEY_A), ("b", KEY_A)],
2456        })
2457        .unwrap();
2458        let envelope = enc.encrypt(b"secret", b"rec:1").unwrap();
2459        assert_eq!(enc.decrypt(&envelope, b"rec:1").unwrap(), b"secret");
2460
2461        let mut relabelled = envelope.clone();
2462        relabelled.key_id = "b".to_string();
2463        assert!(
2464            enc.decrypt(&relabelled, b"rec:1").is_err(),
2465            "relabelling key_id must fail authentication"
2466        );
2467
2468        let mut downgraded = envelope.clone();
2469        downgraded.v = 1;
2470        assert!(
2471            enc.decrypt(&downgraded, b"rec:1").is_err(),
2472            "rewriting v to 1 must not make a v2 ciphertext verify"
2473        );
2474    }
2475
2476    /// Format v1 (AAD = the bare storage key) is a LEGACY format now: only
2477    /// readable behind the allow-legacy policy, and the migration tool
2478    /// upgrades it to v2.
2479    #[tokio::test]
2480    async fn v1_envelopes_are_legacy_and_migrate_to_v2() {
2481        let storage = MemoryStorage::new();
2482        storage
2483            .store_kv(
2484                "rec:1",
2485                &manual_envelope(&KEY_A, "1", 1, b"secret", b"rec:1"),
2486                None,
2487            )
2488            .await
2489            .unwrap();
2490        let provider = || FixedKeys {
2491            current: "1",
2492            keys: vec![("1", KEY_A)],
2493        };
2494
2495        let strict = EncryptedStorage::new(
2496            storage.clone(),
2497            StorageEncryption::new(&provider()).unwrap(),
2498            false,
2499            false,
2500        );
2501        assert!(
2502            strict.get_kv("rec:1").await.is_err(),
2503            "v1 must need the legacy policy"
2504        );
2505
2506        let lenient = EncryptedStorage::new(
2507            storage.clone(),
2508            StorageEncryption::new(&provider()).unwrap(),
2509            false,
2510            true,
2511        );
2512        assert_eq!(lenient.get_kv("rec:1").await.unwrap().unwrap(), b"secret");
2513
2514        let report = migrate_kv_to_encrypted(
2515            &storage,
2516            &StorageEncryption::new(&provider()).unwrap(),
2517            "",
2518            MigrationOptions::default().with_accept_legacy_v0(true),
2519        )
2520        .await
2521        .unwrap();
2522        assert_eq!(report.upgraded_from_legacy, 1, "{report:?}");
2523
2524        let raw = storage.get_kv("rec:1").await.unwrap().unwrap();
2525        assert_eq!(StorageEncryption::parse_envelope(&raw).unwrap().v, 2);
2526        // (`MemoryStorage::clone` copies, so re-wrap the migrated storage.)
2527        let strict_after = EncryptedStorage::new(
2528            storage,
2529            StorageEncryption::new(&provider()).unwrap(),
2530            false,
2531            false,
2532        );
2533        assert_eq!(
2534            strict_after.get_kv("rec:1").await.unwrap().unwrap(),
2535            b"secret"
2536        );
2537    }
2538
2539    /// After the upgrade, a v2 ciphertext copied onto another record must
2540    /// not decrypt (the AAD still binds it to its own key).
2541    #[tokio::test]
2542    async fn upgraded_records_cannot_be_swapped_between_keys() {
2543        let storage = MemoryStorage::new();
2544        for (key, secret) in [("rec:1", &b"one"[..]), ("rec:2", b"two")] {
2545            storage
2546                .store_kv(key, &manual_envelope(&KEY_A, "1", 0, secret, b""), None)
2547                .await
2548                .unwrap();
2549        }
2550        let provider = || FixedKeys {
2551            current: "1",
2552            keys: vec![("1", KEY_A)],
2553        };
2554        migrate_kv_to_encrypted(
2555            &storage,
2556            &StorageEncryption::new(&provider()).unwrap(),
2557            "",
2558            MigrationOptions::default().with_accept_legacy_v0(true),
2559        )
2560        .await
2561        .unwrap();
2562
2563        let swapped = storage.get_kv("rec:1").await.unwrap().unwrap();
2564        storage.store_kv("rec:2", &swapped, None).await.unwrap();
2565        let strict = EncryptedStorage::new(
2566            storage,
2567            StorageEncryption::new(&provider()).unwrap(),
2568            false,
2569            false,
2570        );
2571        assert!(strict.get_kv("rec:2").await.is_err());
2572    }
2573
2574    /// A plaintext JSON value that merely looks like an envelope must not be
2575    /// classified as one: v>=1 needs an explicit non-empty key_id.
2576    #[test]
2577    fn envelope_classification_requires_version_and_key_id() {
2578        let shape = |extra: &str| {
2579            format!(
2580                r#"{{"data":"AAAA","nonce":"AAAAAAAAAAAAAAAA","algorithm":"AES-256-GCM"{extra}}}"#
2581            )
2582        };
2583        // v2 without a key_id: not an envelope.
2584        assert!(StorageEncryption::parse_envelope(shape(r#","v":2"#).as_bytes()).is_none());
2585        // v1 with an empty key_id: not an envelope.
2586        assert!(
2587            StorageEncryption::parse_envelope(shape(r#","v":1,"key_id":"""#).as_bytes()).is_none()
2588        );
2589        // v2 with a key_id: an envelope.
2590        assert!(
2591            StorageEncryption::parse_envelope(shape(r#","v":2,"key_id":"1""#).as_bytes()).is_some()
2592        );
2593        // The original (v0) shape has neither field and is still recognised.
2594        assert!(StorageEncryption::parse_envelope(shape("").as_bytes()).is_some());
2595    }
2596
2597    /// Every way decryption can fail yields the same error text, so the
2598    /// failure itself is not an oracle for which check tripped.
2599    #[test]
2600    fn decrypt_failures_share_one_error_text() {
2601        let enc = StorageEncryption::new(&FixedKeys {
2602            current: "a",
2603            keys: vec![("a", KEY_A), ("b", KEY_B)],
2604        })
2605        .unwrap();
2606        let good = enc.encrypt(b"secret", b"rec:1").unwrap();
2607
2608        let mut bad_base64 = good.clone();
2609        bad_base64.data = "!!not base64!!".to_string();
2610        let mut short_nonce = good.clone();
2611        short_nonce.nonce = BASE64.encode([1u8; 4]);
2612        let mut unknown_key = good.clone();
2613        unknown_key.key_id = "zzz".to_string();
2614        let mut wrong_algorithm = good.clone();
2615        wrong_algorithm.algorithm = "ROT13".to_string();
2616        let mut tampered = good.clone();
2617        let mut raw = BASE64.decode(&tampered.data).unwrap();
2618        raw[0] ^= 0x01;
2619        tampered.data = BASE64.encode(raw);
2620
2621        let messages: Vec<String> = [
2622            (&bad_base64, &b"rec:1"[..]),
2623            (&short_nonce, b"rec:1"),
2624            (&unknown_key, b"rec:1"),
2625            (&wrong_algorithm, b"rec:1"),
2626            (&tampered, b"rec:1"),
2627            (&good, b"rec:OTHER"),
2628        ]
2629        .iter()
2630        .map(|(envelope, aad)| enc.decrypt(envelope, aad).unwrap_err().to_string())
2631        .collect();
2632        assert!(
2633            messages.windows(2).all(|w| w[0] == w[1]),
2634            "decrypt failures must be indistinguishable, got: {messages:#?}"
2635        );
2636    }
2637
2638    #[test]
2639    fn legacy_trial_decryption_order_is_stable() {
2640        let enc = StorageEncryption::new(&FixedKeys {
2641            current: "k0",
2642            keys: (0..8)
2643                .map(|i| {
2644                    let id: &'static str = Box::leak(format!("k{i}").into_boxed_str());
2645                    (id, [i as u8 + 1; 32])
2646                })
2647                .rev()
2648                .collect(),
2649        })
2650        .unwrap();
2651        let ids = enc.sorted_key_ids();
2652        let mut expected = ids.clone();
2653        expected.sort();
2654        assert_eq!(ids, expected);
2655        assert_eq!(ids.len(), 8);
2656    }
2657
2658    #[test]
2659    fn safe_log_id_keeps_eight_hash_bytes() {
2660        let id = safe_log_id("api_key:abc123");
2661        let hash = id.strip_prefix("api_key:").unwrap();
2662        assert_eq!(hash.len(), 16, "8 bytes = 16 hex chars, got {id}");
2663        let colonless = safe_log_id("rawsecret");
2664        assert_eq!(colonless.strip_prefix("key:").unwrap().len(), 16);
2665    }
2666
2667    // ---- key loading fails closed (review gap) ----------------------------------
2668
2669    fn load_with_env(key: Option<&str>) -> Result<LoadedKeys> {
2670        let _lock = TEST_ENCRYPTION_ENV_LOCK.blocking_lock();
2671        // SAFETY: serialized by TEST_ENCRYPTION_ENV_LOCK.
2672        unsafe {
2673            std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE");
2674            match key {
2675                Some(key) => std::env::set_var("AUTH_STORAGE_ENCRYPTION_KEY", key),
2676                None => std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY"),
2677            }
2678        }
2679        let result = EnvKeyProvider.load_keys();
2680        // SAFETY: serialized by TEST_ENCRYPTION_ENV_LOCK (held above).
2681        unsafe { std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY") };
2682        result
2683    }
2684
2685    #[test]
2686    fn malformed_env_keys_fail_closed() {
2687        assert!(load_with_env(None).is_err(), "no key at all");
2688        assert!(load_with_env(Some("")).is_err(), "empty key");
2689        assert!(
2690            load_with_env(Some("!!!not base64!!!")).is_err(),
2691            "bad base64"
2692        );
2693        assert!(
2694            load_with_env(Some(&BASE64.encode([1u8; 16]))).is_err(),
2695            "16-byte key"
2696        );
2697        assert!(
2698            load_with_env(Some(&BASE64.encode([1u8; 33]))).is_err(),
2699            "33-byte key"
2700        );
2701        assert!(load_with_env(Some(&BASE64.encode([1u8; 32]))).is_ok());
2702    }
2703
2704    #[test]
2705    fn malformed_keys_file_fails_closed() {
2706        let dir = tempfile::tempdir().unwrap();
2707        let good = BASE64.encode([3u8; 32]);
2708        let cases: [(&str, String); 4] = [
2709            ("not json", "{{{".to_string()),
2710            (
2711                "current missing from keys",
2712                format!(r#"{{"current":"x","keys":{{"1":"{good}"}}}}"#),
2713            ),
2714            (
2715                "one malformed entry",
2716                format!(r#"{{"current":"1","keys":{{"1":"{good}","2":"short"}}}}"#),
2717            ),
2718            ("empty keys", r#"{"current":"1","keys":{}}"#.to_string()),
2719        ];
2720        let _lock = TEST_ENCRYPTION_ENV_LOCK.blocking_lock();
2721        for (name, body) in cases {
2722            let path = dir.path().join("keys.json");
2723            std::fs::write(&path, body).unwrap();
2724            // SAFETY: serialized by TEST_ENCRYPTION_ENV_LOCK.
2725            unsafe {
2726                std::env::set_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE", &path);
2727            }
2728            let result = EnvKeyProvider.load_keys();
2729            // SAFETY: serialized by TEST_ENCRYPTION_ENV_LOCK (held above).
2730            unsafe { std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE") };
2731            assert!(result.is_err(), "{name} must fail closed");
2732        }
2733    }
2734
2735    // ---- migration preserves KV TTLs ---------------------------------------------
2736
2737    fn ttl_provider() -> FixedKeys {
2738        FixedKeys {
2739            current: "1",
2740            keys: vec![("1", KEY_A)],
2741        }
2742    }
2743
2744    #[tokio::test]
2745    async fn migration_preserves_ttl_when_encrypting_plaintext() {
2746        let storage = MemoryStorage::new();
2747        storage
2748            .store_kv("otp:1", b"123456", Some(Duration::from_secs(600)))
2749            .await
2750            .unwrap();
2751        storage.store_kv("durable:1", b"keep", None).await.unwrap();
2752
2753        migrate_kv_to_encrypted(
2754            &storage,
2755            &StorageEncryption::new(&ttl_provider()).unwrap(),
2756            "",
2757            MigrationOptions::default(),
2758        )
2759        .await
2760        .unwrap();
2761
2762        let ttl = storage.get_kv_ttl("otp:1").await.unwrap().unwrap();
2763        assert!(
2764            ttl > Duration::from_secs(590) && ttl <= Duration::from_secs(600),
2765            "TTL must survive migration, got {ttl:?}"
2766        );
2767        assert_eq!(storage.get_kv_ttl("durable:1").await.unwrap(), None);
2768        let raw = storage.get_kv("otp:1").await.unwrap().unwrap();
2769        assert!(
2770            StorageEncryption::looks_like_envelope(&raw),
2771            "must be encrypted"
2772        );
2773    }
2774
2775    #[tokio::test]
2776    async fn legacy_upgrade_preserves_ttl() {
2777        let storage = MemoryStorage::new();
2778        storage
2779            .store_kv(
2780                "rec:1",
2781                &manual_envelope(&KEY_A, "", 0, b"secret", b""),
2782                Some(Duration::from_secs(600)),
2783            )
2784            .await
2785            .unwrap();
2786
2787        migrate_kv_to_encrypted(
2788            &storage,
2789            &StorageEncryption::new(&ttl_provider()).unwrap(),
2790            "",
2791            MigrationOptions::default().with_accept_legacy_v0(true),
2792        )
2793        .await
2794        .unwrap();
2795
2796        let ttl = storage.get_kv_ttl("rec:1").await.unwrap().unwrap();
2797        assert!(ttl > Duration::from_secs(590) && ttl <= Duration::from_secs(600));
2798        let raw = storage.get_kv("rec:1").await.unwrap().unwrap();
2799        assert_eq!(
2800            StorageEncryption::parse_envelope(&raw).unwrap().v,
2801            CURRENT_FORMAT_VERSION
2802        );
2803    }
2804
2805    /// A backend that cannot report TTLs must not be migrated silently: a
2806    /// real run would make every expiring entry permanent. It needs an
2807    /// explicit opt-in, and a dry run (which writes nothing) is always fine.
2808    #[tokio::test]
2809    async fn migration_refuses_backend_that_cannot_report_ttl_without_opt_in() {
2810        let storage = crate::testing::utilities::MockStorage::new();
2811        let encryption = StorageEncryption::new(&ttl_provider()).unwrap();
2812
2813        assert!(
2814            migrate_kv_to_encrypted(&storage, &encryption, "", MigrationOptions::default())
2815                .await
2816                .is_err(),
2817            "a real run on a TTL-blind backend must be refused"
2818        );
2819        assert!(
2820            migrate_kv_to_encrypted(
2821                &storage,
2822                &encryption,
2823                "",
2824                MigrationOptions::default().with_dry_run(true)
2825            )
2826            .await
2827            .is_ok(),
2828            "a dry run writes nothing, so it is allowed"
2829        );
2830        assert!(
2831            migrate_kv_to_encrypted(
2832                &storage,
2833                &encryption,
2834                "",
2835                MigrationOptions::default().with_accept_ttl_loss(true)
2836            )
2837            .await
2838            .is_ok(),
2839            "explicit opt-in proceeds"
2840        );
2841    }
2842
2843    #[tokio::test]
2844    async fn backends_that_honour_ttl_say_so() {
2845        let memory = MemoryStorage::new();
2846        assert!(memory.tracks_kv_ttl());
2847        let wrapped = EncryptedStorage::new(
2848            MemoryStorage::new(),
2849            StorageEncryption::new_random(),
2850            false,
2851            false,
2852        );
2853        assert!(
2854            wrapped.tracks_kv_ttl(),
2855            "the wrapper forwards the inner answer"
2856        );
2857        let shared: std::sync::Arc<dyn AuthStorage> = std::sync::Arc::new(MemoryStorage::new());
2858        assert!(shared.tracks_kv_ttl(), "the Arc impl forwards too");
2859        assert!(
2860            !crate::testing::utilities::MockStorage::new().tracks_kv_ttl(),
2861            "a backend that ignores TTLs must say so"
2862        );
2863    }
2864
2865    // ---- keys-file permissions (L4) and env-key rotation warning (L3) ------------
2866
2867    #[test]
2868    fn keys_file_mode_check_flags_group_and_other_access() {
2869        for open in [0o644, 0o640, 0o604, 0o660, 0o666, 0o777, 0o601, 0o610] {
2870            assert!(keys_file_mode_too_open(open), "{open:o} must be flagged");
2871        }
2872        for closed in [0o600, 0o400, 0o700, 0o500, 0o200] {
2873            assert!(!keys_file_mode_too_open(closed), "{closed:o} must pass");
2874        }
2875    }
2876
2877    #[test]
2878    fn strict_permissions_env_parsing() {
2879        let _lock = TEST_ENCRYPTION_ENV_LOCK.blocking_lock();
2880        let read = |value: Option<&str>| {
2881            // SAFETY: serialized by TEST_ENCRYPTION_ENV_LOCK (held above).
2882            unsafe {
2883                match value {
2884                    Some(v) => std::env::set_var(STRICT_KEY_FILE_PERMISSIONS_ENV, v),
2885                    None => std::env::remove_var(STRICT_KEY_FILE_PERMISSIONS_ENV),
2886                }
2887            }
2888            strict_permissions_requested()
2889        };
2890        assert!(!read(None));
2891        assert!(!read(Some("")));
2892        assert!(!read(Some("0")));
2893        assert!(!read(Some("no")));
2894        assert!(read(Some("1")));
2895        assert!(read(Some("true")));
2896        assert!(read(Some("TRUE")));
2897        assert!(read(Some("Yes")));
2898        // SAFETY: serialized by TEST_ENCRYPTION_ENV_LOCK (held above).
2899        unsafe { std::env::remove_var(STRICT_KEY_FILE_PERMISSIONS_ENV) };
2900    }
2901
2902    /// Runs on Unix CI only (Windows has no group/other mode bits).
2903    #[cfg(unix)]
2904    #[test]
2905    fn keys_file_permissions_strict_mode_fails_startup() {
2906        use std::os::unix::fs::PermissionsExt;
2907        let dir = tempfile::tempdir().unwrap();
2908        let path = dir.path().join("keys.json");
2909        std::fs::write(&path, "{}").unwrap();
2910        let path_str = path.to_str().unwrap();
2911
2912        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
2913        assert!(
2914            check_keys_file_permissions(path_str, true).is_err(),
2915            "strict + 0644"
2916        );
2917        assert!(
2918            check_keys_file_permissions(path_str, false).is_ok(),
2919            "warn-only + 0644"
2920        );
2921
2922        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
2923        assert!(
2924            check_keys_file_permissions(path_str, true).is_ok(),
2925            "strict + 0600"
2926        );
2927    }
2928
2929    #[test]
2930    fn env_key_source_detection() {
2931        let _lock = TEST_ENCRYPTION_ENV_LOCK.blocking_lock();
2932        // SAFETY: serialized by TEST_ENCRYPTION_ENV_LOCK (held above).
2933        unsafe {
2934            std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE");
2935            std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY");
2936        }
2937        assert!(!env_key_source_in_use(), "no key configured at all");
2938        // SAFETY: as above.
2939        unsafe { std::env::set_var("AUTH_STORAGE_ENCRYPTION_KEY", "irrelevant") };
2940        assert!(
2941            env_key_source_in_use(),
2942            "no keys file => the env var is the source"
2943        );
2944        // SAFETY: as above.
2945        unsafe { std::env::set_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE", "/some/keys.json") };
2946        assert!(!env_key_source_in_use(), "a keys file supports rotation");
2947        // SAFETY: as above.
2948        unsafe {
2949            std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE");
2950            std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY");
2951        }
2952    }
2953
2954    #[tokio::test]
2955    async fn envelope_probe_finds_stored_envelopes_within_its_limit() {
2956        let enc = StorageEncryption::new_random();
2957        let storage = MemoryStorage::new();
2958        storage
2959            .store_kv("plain:1", b"just text", None)
2960            .await
2961            .unwrap();
2962        assert!(
2963            !stored_envelopes_exist(&storage, 10).await.unwrap(),
2964            "plaintext only"
2965        );
2966
2967        let sealed = enc.encrypt_for_storage(b"secret", b"sealed:1").unwrap();
2968        storage.store_kv("sealed:1", &sealed, None).await.unwrap();
2969        assert!(
2970            stored_envelopes_exist(&storage, 10).await.unwrap(),
2971            "envelope present"
2972        );
2973
2974        // The probe is bounded: with a limit of 0 it looks at nothing.
2975        assert!(!stored_envelopes_exist(&storage, 0).await.unwrap());
2976    }
2977
2978    #[tokio::test]
2979    async fn encrypted_storage_says_it_encrypts() {
2980        let wrapped = EncryptedStorage::new(
2981            MemoryStorage::new(),
2982            StorageEncryption::new_random(),
2983            false,
2984            false,
2985        );
2986        assert!(wrapped.encrypts_kv_at_rest());
2987        assert!(!MemoryStorage::new().encrypts_kv_at_rest());
2988        let shared: std::sync::Arc<dyn AuthStorage> = std::sync::Arc::new(wrapped);
2989        assert!(shared.encrypts_kv_at_rest(), "the Arc impl forwards");
2990    }
2991}