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