entropy-auth 2026.7.31

Authentication and authorization for Entropy Softworks server and API projects
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! Authenticated symmetric encryption for secrets at rest.
//!
//! Wraps [`aes_gcm::Aes256Gcm`] in a tiny API for encrypting small
//! secrets (TOTP secrets, OAuth client secrets, S3 credentials,
//! Kerberos keytabs, …) before storing them in a database.
//!
//! ```
//! use entropy_auth::SecretBox;
//!
//! // In production, derive or load a real 32-byte key (e.g. from a KMS);
//! // never hard-code one as shown here.
//! let key = [0u8; 32];
//! let sb = SecretBox::from_key(&key);
//! let stored = sb.encrypt(b"my plaintext")?;     // "enc:<b64-nonce>:<b64-ct>"
//! let plain  = sb.decrypt(&stored)?;
//! assert_eq!(plain.as_slice(), b"my plaintext");
//! # Ok::<(), entropy_auth::SecretBoxError>(())
//! ```
//!
//! # Wire format
//!
//! Encrypted blobs are encoded as:
//!
//! ```text
//! enc:<base64url-nonce>:<base64url-ciphertext>
//! ```
//!
//! Both fields use base64url **without padding** (RFC 4648 §5). The
//! literal `enc:` prefix distinguishes encrypted blobs from legacy
//! plaintext during migration windows; see [`SecretBox::is_encrypted`].
//!
//! A blob written by [`SecretBox::encrypt_with_context`] instead carries the
//! `enc2:` prefix and is bound to its context (see below).
//!
//! # Context binding
//!
//! `enc:` blobs are encrypted with **empty** associated data, so ciphertext
//! carries no record of what it was encrypted *for*. Under a single
//! deployment-wide key that makes every blob portable: an actor who can write
//! the database (SQL injection on an update path, a restored backup, a
//! compromised replica) can move one row's ciphertext into another row,
//! another column, or another tenant, and it still decrypts. The AEAD
//! authenticates the bytes, not their location.
//!
//! [`SecretBox::encrypt_with_context`] fixes that by passing a caller-supplied
//! context — purpose, tenant, row id — as AES-GCM associated data, so a blob
//! only decrypts where it was written. Prefer it for anything stored per-row.
//! [`SecretBox::decrypt_with_context`] still accepts legacy `enc:` blobs
//! (unbound) so existing rows keep working; each rewrite upgrades a row to
//! `enc2:`, and a later release can drop the legacy branch once no `enc:`
//! rows remain.
//!
//! # Security
//!
//! - **AES-256-GCM** — 256-bit key, 96-bit nonce, 128-bit authentication
//!   tag. The ciphertext returned by `aes_gcm` includes the tag at the
//!   end, so the on-the-wire ciphertext field carries plaintext + tag
//!   together.
//! - **Random nonce per encryption** — every call to [`SecretBox::encrypt`]
//!   draws a fresh 96-bit nonce from the platform CSPRNG via the crate's
//!   [`fill_random`] helper, which surfaces an error instead of panicking
//!   if the OS RNG is unavailable. **Do not** reuse a
//!   `(key, nonce)` pair: GCM loses both confidentiality and authenticity
//!   under nonce reuse.
//! - **Key custody** — the caller is responsible for loading and
//!   protecting the 32-byte key. This module never accepts a passphrase
//!   or runs a KDF; pass an already-derived key.
//! - **Error messages** never contain plaintext, ciphertext, nonce, or
//!   key material.

use core::fmt;

use aes_gcm::aead::Aead;
use aes_gcm::{Aes256Gcm, KeyInit, Nonce};

use crate::crypto::fill_random;
use crate::crypto::zeroize::Zeroizing;
use crate::encoding::{Base64DecodeError, base64url_decode, base64url_encode};

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// AES-GCM nonce length in bytes (96 bits, the recommended size).
const NONCE_LEN: usize = 12;

/// Wire-format prefix that marks an encrypted blob (empty associated data).
const PREFIX: &str = "enc:";

/// Wire-format prefix for a context-bound blob (non-empty associated data).
const PREFIX_V2: &str = "enc2:";

// ---------------------------------------------------------------------------
// SecretBox
// ---------------------------------------------------------------------------

/// Authenticated symmetric encryption helper backed by AES-256-GCM.
///
/// Holds a configured cipher instance — construct once per key and reuse
/// across many encrypt/decrypt calls. The struct is `Send + Sync` so it
/// can live inside an `AppState` shared across async handlers.
///
/// See the [module documentation](self) for the wire format and
/// security notes.
pub struct SecretBox {
    cipher: Aes256Gcm,
}

impl SecretBox {
    /// Constructs a `SecretBox` from a 32-byte key.
    ///
    /// The caller is responsible for deriving or loading the key —
    /// typically by hex-decoding an environment variable at startup or
    /// pulling from a key-management service.
    #[must_use]
    pub fn from_key(key: &[u8; 32]) -> Self {
        // `Aes256Gcm::new` accepts a fixed-size `Key` reference; using
        // `new_from_slice` would panic only on the wrong length, which
        // the type system already rules out here.
        Self {
            cipher: Aes256Gcm::new(key.into()),
        }
    }

    /// Returns `true` if `encoded` looks like a `SecretBox` ciphertext
    /// (starts with the `enc:` prefix).
    ///
    /// Useful during migration windows where some rows are still
    /// plaintext: callers can branch on this without paying the cost of
    /// a decode attempt.
    #[must_use]
    pub fn is_encrypted(encoded: &str) -> bool {
        encoded.starts_with(PREFIX) || encoded.starts_with(PREFIX_V2)
    }

    /// Encrypts `plaintext` and returns the wire-format string
    /// `enc:<base64url-nonce>:<base64url-ciphertext>`.
    ///
    /// A fresh 96-bit nonce is drawn from the platform CSPRNG for each
    /// call.
    ///
    /// # Nonce-reuse bound
    ///
    /// With random 96-bit nonces, NIST SP 800-38D §8.3 bounds a single key to
    /// roughly `2^32` encryptions before the birthday-collision probability of
    /// a repeated nonce (catastrophic for AES-GCM confidentiality) becomes
    /// non-negligible. This `SecretBox` is for *at-rest* material (TOTP/client
    /// secrets, credentials), where `2^32` writes under one never-rotated key
    /// is not realistically reachable. If a deployment ever approaches that
    /// volume, rotate `ACCESS_SECRETBOX_KEY` (re-encrypting stored values) or
    /// migrate to a nonce-misuse-resistant mode (AES-GCM-SIV).
    ///
    /// # Errors
    ///
    /// - `SecretBoxError::Random` if the platform CSPRNG is unavailable
    ///   when drawing the nonce.
    /// - `SecretBoxError::Aead` if the underlying AEAD encryption
    ///   primitive fails (effectively unreachable in practice for
    ///   AES-GCM with valid inputs).
    pub fn encrypt(&self, plaintext: &[u8]) -> Result<String, SecretBoxError> {
        self.seal(plaintext, b"", PREFIX)
    }

    /// Encrypts `plaintext` bound to `context`, returning
    /// `enc2:<base64url-nonce>:<base64url-ciphertext>`.
    ///
    /// `context` becomes the AES-GCM associated data: it is authenticated but
    /// not stored, so [`decrypt_with_context`](Self::decrypt_with_context)
    /// must be given the identical bytes. Anything that identifies *where* the
    /// blob lives works — purpose, tenant id, row id — and the resulting
    /// ciphertext cannot be relocated to a different row, column, or tenant
    /// (see the module-level "Context binding" section).
    ///
    /// # Errors
    ///
    /// As [`encrypt`](Self::encrypt).
    pub fn encrypt_with_context(
        &self,
        plaintext: &[u8],
        context: &[u8],
    ) -> Result<String, SecretBoxError> {
        self.seal(plaintext, context, PREFIX_V2)
    }

    /// Shared encryption path for both wire formats.
    fn seal(&self, plaintext: &[u8], aad: &[u8], prefix: &str) -> Result<String, SecretBoxError> {
        // SECURITY: Nonce must be unique per (key, message) pair. We pull
        // 96 bits through the crate's vetted CSPRNG path, which returns an
        // error (rather than panicking) if the OS RNG is unavailable —
        // collision probability is negligible for any realistic key
        // lifetime.
        let mut nonce_bytes = [0u8; NONCE_LEN];
        fill_random(&mut nonce_bytes)
            .map_err(|_| SecretBoxError::new(SecretBoxErrorKind::Random))?;
        let nonce = Nonce::from_slice(&nonce_bytes);

        let ciphertext = self
            .cipher
            .encrypt(
                nonce,
                aes_gcm::aead::Payload {
                    msg: plaintext,
                    aad,
                },
            )
            .map_err(|_| SecretBoxError::new(SecretBoxErrorKind::Aead))?;

        let nonce_b64 = base64url_encode(&nonce_bytes);
        let ct_b64 = base64url_encode(&ciphertext);
        Ok(format!("{prefix}{nonce_b64}:{ct_b64}"))
    }

    /// Decrypts a `SecretBox` wire-format string and returns the
    /// recovered plaintext.
    ///
    /// # Errors
    ///
    /// - `SecretBoxError::InvalidFormat` if `encoded` does not start
    ///   with `enc:` or does not split into exactly three
    ///   colon-separated parts.
    /// - `SecretBoxError::Base64` if either field fails base64url
    ///   decoding.
    /// - `SecretBoxError::BadNonce` if the nonce is not exactly 12
    ///   bytes.
    /// - `SecretBoxError::Aead` if AEAD verification fails (wrong
    ///   key, tampered ciphertext, …).
    ///
    /// # Security
    ///
    /// The recovered plaintext is returned in a [`Zeroizing`] buffer so the
    /// decrypted secret is scrubbed from memory when the caller drops it,
    /// consistent with the crate-wide zeroization discipline. The wrapper
    /// derefs to `Vec<u8>`/`[u8]`, so existing read access is unaffected.
    pub fn decrypt(&self, encoded: &str) -> Result<Zeroizing<Vec<u8>>, SecretBoxError> {
        self.decrypt_with_context(encoded, b"")
    }

    /// Decrypts a blob written by
    /// [`encrypt_with_context`](Self::encrypt_with_context), verifying that it
    /// was sealed under the identical `context`.
    ///
    /// A legacy `enc:` blob is still accepted (it predates context binding and
    /// carries none), so a deployment can adopt binding without re-encrypting
    /// every stored secret up front. An `enc2:` blob presented with the wrong
    /// context fails as [`SecretBoxErrorKind::Aead`], indistinguishable from
    /// a tampered ciphertext.
    ///
    /// # Errors
    ///
    /// As [`decrypt`](Self::decrypt); additionally `Aead` when `context` does
    /// not match the value the blob was sealed with.
    pub fn decrypt_with_context(
        &self,
        encoded: &str,
        context: &[u8],
    ) -> Result<Zeroizing<Vec<u8>>, SecretBoxError> {
        // The AAD is empty for a legacy blob regardless of what the caller
        // passed — those bytes were never authenticated.
        let aad: &[u8] = if encoded.starts_with(PREFIX_V2) {
            context
        } else if encoded.starts_with(PREFIX) {
            b""
        } else {
            return Err(SecretBoxError::new(SecretBoxErrorKind::InvalidFormat));
        };

        // Splitting on the full input (rather than stripping the prefix
        // first) is safe because the prefix itself contains no further
        // colons, so the field count check below catches malformed input
        // either way.
        let parts: Vec<&str> = encoded.split(':').collect();
        if parts.len() != 3 {
            return Err(SecretBoxError::new(SecretBoxErrorKind::InvalidFormat));
        }
        // parts[0] == "enc"/"enc2"; parts[1] == nonce_b64; parts[2] == ct_b64.

        let nonce_bytes = base64url_decode(parts[1]).map_err(SecretBoxError::base64)?;
        let ciphertext = base64url_decode(parts[2]).map_err(SecretBoxError::base64)?;

        if nonce_bytes.len() != NONCE_LEN {
            return Err(SecretBoxError::new(SecretBoxErrorKind::BadNonce));
        }
        let nonce = Nonce::from_slice(&nonce_bytes);

        self.cipher
            .decrypt(
                nonce,
                aes_gcm::aead::Payload {
                    msg: ciphertext.as_ref(),
                    aad,
                },
            )
            .map(Zeroizing::new)
            .map_err(|_| SecretBoxError::new(SecretBoxErrorKind::Aead))
    }
}

// SECURITY: Debug must not expose key material. The cipher itself does
// not implement Debug, so we provide a redacted manual impl in case a
// containing struct derives Debug.
impl fmt::Debug for SecretBox {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SecretBox")
            .field("cipher", &"[REDACTED]")
            .finish()
    }
}

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// Internal classification of `SecretBoxError` variants.
#[derive(Debug, Clone, PartialEq, Eq)]
enum SecretBoxErrorKind {
    /// Input is not in the expected `enc:<nonce>:<ct>` form.
    InvalidFormat,
    /// One of the base64url fields failed to decode.
    Base64(Base64DecodeError),
    /// AEAD encryption or decryption failed (wrong key, tampered
    /// ciphertext, or upstream error).
    Aead,
    /// The decoded nonce is not the expected 12 bytes long.
    BadNonce,
    /// The platform CSPRNG was unavailable when drawing the nonce.
    Random,
}

/// Error returned by [`SecretBox`] operations.
///
/// Error messages never contain key, nonce, plaintext, or ciphertext
/// material.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SecretBoxError {
    kind: SecretBoxErrorKind,
}

impl SecretBoxError {
    const fn new(kind: SecretBoxErrorKind) -> Self {
        Self { kind }
    }

    fn base64(err: Base64DecodeError) -> Self {
        Self {
            kind: SecretBoxErrorKind::Base64(err),
        }
    }
}

impl fmt::Display for SecretBoxError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            SecretBoxErrorKind::InvalidFormat => {
                write!(f, "secret_box: invalid encrypted format")
            }
            SecretBoxErrorKind::Base64(err) => {
                write!(f, "secret_box: base64 decode failed: {err}")
            }
            SecretBoxErrorKind::Aead => {
                // SECURITY: Do not distinguish "wrong key" from "tampered
                // ciphertext" — both indicate a decryption failure, and
                // hiding the difference avoids leaking oracle bits.
                write!(f, "secret_box: aead error")
            }
            SecretBoxErrorKind::BadNonce => {
                write!(f, "secret_box: nonce wrong length")
            }
            SecretBoxErrorKind::Random => {
                write!(f, "secret_box: csprng unavailable")
            }
        }
    }
}

impl std::error::Error for SecretBoxError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match &self.kind {
            SecretBoxErrorKind::Base64(err) => Some(err),
            _ => None,
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    /// All-zero test key. Acceptable for unit tests; never use in
    /// production.
    const TEST_KEY: [u8; 32] = [0u8; 32];

    /// A second, distinct key used to verify cross-key decryption fails.
    const OTHER_KEY: [u8; 32] = [1u8; 32];

    fn sb() -> SecretBox {
        SecretBox::from_key(&TEST_KEY)
    }

    #[test]
    fn round_trip_recovers_plaintext() {
        let sb = sb();
        let encoded = sb.encrypt(b"hello world").unwrap();
        let plain = sb.decrypt(&encoded).unwrap();
        assert_eq!(plain.as_slice(), b"hello world");
    }

    #[test]
    fn round_trip_empty_plaintext() {
        let sb = sb();
        let encoded = sb.encrypt(b"").unwrap();
        let plain = sb.decrypt(&encoded).unwrap();
        assert_eq!(plain.as_slice(), b"");
    }

    #[test]
    fn round_trip_long_plaintext() {
        let sb = sb();
        let plaintext = vec![0xABu8; 4096];
        let encoded = sb.encrypt(&plaintext).unwrap();
        let plain = sb.decrypt(&encoded).unwrap();
        assert_eq!(plain.as_slice(), plaintext.as_slice());
    }

    #[test]
    fn nonce_randomness_yields_distinct_ciphertexts() {
        let sb = sb();
        let a = sb.encrypt(b"same plaintext").unwrap();
        let b = sb.encrypt(b"same plaintext").unwrap();
        assert_ne!(a, b, "fresh nonce per encryption should differ");
    }

    #[test]
    fn encrypted_format_starts_with_prefix() {
        let sb = sb();
        let encoded = sb.encrypt(b"x").unwrap();
        assert!(encoded.starts_with("enc:"));
        let parts: Vec<&str> = encoded.split(':').collect();
        assert_eq!(parts.len(), 3);
        assert_eq!(parts[0], "enc");
    }

    #[test]
    fn is_encrypted_recognises_prefix() {
        assert!(SecretBox::is_encrypted("enc:foo:bar"));
        assert!(SecretBox::is_encrypted("enc:"));
        assert!(!SecretBox::is_encrypted("plaintext"));
        assert!(!SecretBox::is_encrypted(""));
        assert!(!SecretBox::is_encrypted("ENC:foo:bar"));
    }

    #[test]
    fn decrypt_rejects_missing_prefix() {
        let sb = sb();
        assert_eq!(
            sb.decrypt("aGVsbG8:d29ybGQ").unwrap_err(),
            SecretBoxError::new(SecretBoxErrorKind::InvalidFormat),
        );
    }

    #[test]
    fn decrypt_rejects_too_few_fields() {
        let sb = sb();
        assert_eq!(
            sb.decrypt("enc:onlyone").unwrap_err(),
            SecretBoxError::new(SecretBoxErrorKind::InvalidFormat),
        );
    }

    #[test]
    fn decrypt_rejects_too_many_fields() {
        let sb = sb();
        assert_eq!(
            sb.decrypt("enc:a:b:c").unwrap_err(),
            SecretBoxError::new(SecretBoxErrorKind::InvalidFormat),
        );
    }

    #[test]
    fn decrypt_rejects_bad_base64_nonce() {
        let sb = sb();
        // '!' is not in the base64url alphabet.
        let err = sb.decrypt("enc:!!!:AAAA").unwrap_err();
        assert!(
            matches!(err.kind, SecretBoxErrorKind::Base64(_)),
            "expected Base64 variant, got {err:?}"
        );
    }

    #[test]
    fn decrypt_rejects_bad_base64_ciphertext() {
        let sb = sb();
        // Valid 12-byte nonce, invalid ciphertext field.
        let nonce = base64url_encode(&[0u8; NONCE_LEN]);
        let err = sb.decrypt(&format!("enc:{nonce}:!!!")).unwrap_err();
        assert!(
            matches!(err.kind, SecretBoxErrorKind::Base64(_)),
            "expected Base64 variant, got {err:?}"
        );
    }

    #[test]
    fn decrypt_rejects_wrong_nonce_length() {
        let sb = sb();
        // 8-byte nonce instead of 12.
        let bad_nonce = base64url_encode(&[0u8; 8]);
        let ct = base64url_encode(&[0u8; 16]);
        assert_eq!(
            sb.decrypt(&format!("enc:{bad_nonce}:{ct}")).unwrap_err(),
            SecretBoxError::new(SecretBoxErrorKind::BadNonce),
        );
    }

    #[test]
    fn decrypt_with_wrong_key_fails_aead() {
        let alice = SecretBox::from_key(&TEST_KEY);
        let bob = SecretBox::from_key(&OTHER_KEY);

        let encoded = alice.encrypt(b"top secret").unwrap();
        assert_eq!(
            bob.decrypt(&encoded).unwrap_err(),
            SecretBoxError::new(SecretBoxErrorKind::Aead),
        );
    }

    #[test]
    fn decrypt_rejects_tampered_ciphertext() {
        let sb = sb();
        let encoded = sb.encrypt(b"protected").unwrap();

        // Flip a bit in the ciphertext field by re-encoding modified bytes.
        let parts: Vec<&str> = encoded.split(':').collect();
        let mut ct = base64url_decode(parts[2]).unwrap();
        ct[0] ^= 0x01;
        let tampered = format!("enc:{}:{}", parts[1], base64url_encode(&ct));

        assert_eq!(
            sb.decrypt(&tampered).unwrap_err(),
            SecretBoxError::new(SecretBoxErrorKind::Aead),
        );
    }

    #[test]
    fn error_display_contains_no_secrets() {
        let errors = [
            SecretBoxError::new(SecretBoxErrorKind::InvalidFormat),
            SecretBoxError::new(SecretBoxErrorKind::Aead),
            SecretBoxError::new(SecretBoxErrorKind::BadNonce),
        ];
        for err in &errors {
            let msg = err.to_string();
            assert!(
                msg.starts_with("secret_box:"),
                "error should be prefixed: {msg}"
            );
            assert!(
                !msg.contains("key") && !msg.contains("plaintext"),
                "error must not leak material: {msg}",
            );
        }
    }

    #[test]
    fn error_implements_std_error() {
        let err: Box<dyn std::error::Error> =
            Box::new(SecretBoxError::new(SecretBoxErrorKind::Aead));
        let _ = err.to_string();
    }

    #[test]
    fn debug_redacts_cipher() {
        let sb = sb();
        let dbg = format!("{sb:?}");
        assert!(dbg.contains("[REDACTED]"), "debug should redact: {dbg}");
    }

    #[test]
    fn context_bound_blob_only_decrypts_under_its_context() {
        let sb = SecretBox::from_key(&[7u8; 32]);
        let ctx = b"totp_secret:tenant-a:user-1";
        let blob = sb.encrypt_with_context(b"seed", ctx).unwrap();
        assert!(blob.starts_with("enc2:"));
        assert!(SecretBox::is_encrypted(&blob));
        assert_eq!(
            sb.decrypt_with_context(&blob, ctx).unwrap().as_slice(),
            b"seed"
        );
        // Moving the blob to another row/tenant/column no longer decrypts.
        assert!(
            sb.decrypt_with_context(&blob, b"totp_secret:tenant-b:user-1")
                .is_err()
        );
        assert!(sb.decrypt_with_context(&blob, b"").is_err());
        assert!(sb.decrypt(&blob).is_err());
    }

    #[test]
    fn legacy_blob_still_decrypts_under_any_context() {
        // Rows written before context binding must keep working, whatever the
        // caller now passes — they were sealed with no associated data.
        let sb = SecretBox::from_key(&[9u8; 32]);
        let legacy = sb.encrypt(b"old").unwrap();
        assert!(legacy.starts_with("enc:"));
        assert_eq!(
            sb.decrypt_with_context(&legacy, b"whatever:1:2")
                .unwrap()
                .as_slice(),
            b"old"
        );
    }
}