vitaminc-aead 0.3.0

Authenticated Encryption with Associated Data (AEAD) primitives. Part of the Vitamin-C cryptographic suite.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
//! Context-tagged encryption.
//!
//! This module provides [`ContextTag`], a wrapper that binds additional authenticated data (AAD)
//! to a plaintext value **at the type level**. When a `ContextTag` is encrypted, the embedded tag
//! is automatically folded into the AAD alongside any extra AAD passed to
//! [`encrypt_with_aad`](crate::Encrypt::encrypt_with_aad).
//!
//! The point of the wrapper is the type-level guarantee: a value wrapped in `ContextTag` *cannot*
//! be encrypted without its context. The revised [`Cipher`]/[`Encrypt`] API already accepts tuple
//! AAD (e.g. `value.encrypt_with_aad(cipher, (tag, extra))`), so the byte-level behaviour is
//! nothing more than [`IntoAad`] composition — but tuple AAD is opt-in at every call site and easy
//! to forget. `ContextTag` moves the obligation into the type system so the compiler enforces it.
//!
//! # Where AAD lives in the revised API
//!
//! Encryption threads AAD through [`Encrypt::encrypt_with_aad`](crate::Encrypt::encrypt_with_aad),
//! so `ContextTag` participates by implementing [`Encrypt`]. Decryption is symmetric: the
//! [`Decrypt`]/[`Decipher`] traits thread AAD through the type being decrypted via
//! [`Decrypt::decrypt_with_aad`](crate::Decrypt::decrypt_with_aad), so `ContextTag` mirrors its
//! `Encrypt` impl with [`ContextTag::decrypt`] / [`ContextTag::decrypt_with_aad`].
//!
//! Rebuild the decrypt context with [`ContextTag::context`] (and the same
//! [`refine`](ContextTag::refine) chain used at encrypt time), then drive a [`Decipher`] obtained
//! from the concrete cipher — e.g. `ContextTag::context(tag).decrypt(cipher.decipher(ciphertext))`.
//! Because the tag (and any refinement) is reconstructed by the same code path that bound it, it is
//! never re-typed by hand.
//!
//! For lower-level use directly against a cipher's own decrypt entry point, [`ContextTag::aad`] /
//! [`ContextTag::aad_with`] build the raw AAD tuple the wrapper bound at encrypt time.
//!
//! # AAD encoding
//!
//! When encrypting a `ContextTag`, the final AAD is formed by combining the extra AAD with the
//! embedded tag as the tuple `(extra_aad, tag)`, which [`IntoAad`] PAE-encodes:
//!
//! ```text
//! final_aad = PAE(extra_aad, tag)
//! ```
//!
//! PAE (Pre-Authentication Encoding) prefixes each piece with its length, preventing
//! canonicalisation attacks where different inputs could otherwise produce identical byte strings.
//!
//! With [`refine`](ContextTag::refine), the tag itself is a nested tuple that is recursively
//! PAE-encoded:
//!
//! ```text
//! ContextTag::new(data, "a").refine("b")
//!   ──► tag = ("a", "b")
//!   ──► final_aad = PAE(extra_aad, PAE("a", "b"))
//! ```
//!
//! The cipher receives that context with its parts intact: `into_aad_piece()` on the value it is
//! handed is `List([extra_aad, List(["a", "b"])])` for the example, so a backend that names the
//! parts (a key-management service logging which field a key was issued for) reads them directly
//! rather than from pre-encoded bytes. A backend that only wants bytes calls `into_aad()`, which
//! writes `PAE(extra_aad, tag)` into one buffer — the same allocations as the plain tuple.

use crate::{Aad, AadPiece, Cipher, Decipher, Decrypt, Encrypt, IntoAad};

/// Folds a context `tag` and `extra_aad` into the AAD layout bound by `ContextTag`.
///
/// This is the layout shared by the two *type-driven* paths: both the [`Encrypt`] impl and
/// [`ContextTag::decrypt_with_aad`] go through it, so those two sides cannot drift out of sync (a
/// divergence would silently break authentication). The low-level [`ContextTag::aad`] /
/// [`ContextTag::aad_with`] builders reproduce the same `(extra_aad, tag)` layout *by hand* (they
/// must return the unencoded tag for a cipher's own decrypt entry point to re-encode), so they are
/// a parallel construction kept in lockstep only by the `*_helper_matches_encrypt_binding` tests —
/// if you change the layout here, update those builders too.
///
/// The tag becomes an owned/`'static` [`AadPiece`] and is re-borrowed for the call's `'a`
/// lifetime (`AadPiece` is covariant in its lifetime, so `'static: 'a` permits the narrowing);
/// the result is a [`FoldedAad`], whose bytes are `PAE(extra_aad, tag)` — the same as the tuple
/// `(extra_aad, tag)` — and whose parts are `List([extra_aad, tag])`.
fn fold_tag_aad<'a, Tag, A>(tag: Tag, extra_aad: A) -> FoldedAad<'a, A>
where
    Tag: IntoAad<'static>,
{
    let tag: AadPiece<'static> = tag.into_aad_piece();
    let tag: AadPiece<'a> = tag;
    FoldedAad { extra_aad, tag }
}

/// The context a [`ContextTag`] hands its cipher: `extra_aad` and the tag, in that order.
///
/// Bytes and parts are produced by different paths so the parts view costs nothing unless asked
/// for: `into_aad` writes `PAE(extra_aad, tag)` straight into one buffer (no intermediate list, no
/// second copy of the tag), while `into_aad_piece` builds `List([extra_aad, tag])`. Both agree
/// with the tuple `(extra_aad, tag)` byte for byte — `cipher_receives_the_context_as_parts` and the
/// `*_helper_matches_encrypt_binding` tests pin it.
struct FoldedAad<'a, A> {
    extra_aad: A,
    tag: AadPiece<'a>,
}

impl<'a, A> IntoAad<'a> for FoldedAad<'a, A>
where
    A: IntoAad<'a>,
{
    fn into_aad(self) -> Aad<'a> {
        let extra_aad = self.extra_aad.into_aad();
        self.tag.pae_after(extra_aad.as_bytes())
    }

    fn into_aad_piece(self) -> AadPiece<'a> {
        AadPiece::List(vec![self.extra_aad.into_aad_piece(), self.tag])
    }
}

/// A wrapper that pairs a plaintext value with a context tag used as additional authenticated
/// data (AAD).
///
/// `ContextTag` guarantees, at the type level, that `tag` is folded into the AAD whenever `inner`
/// is encrypted. This is the recommended way to enforce that a value is always sealed against a
/// specific context (a user id, table name, column name, …): because the tag is part of the type,
/// the compiler will not let you forget it.
///
/// The tag can be any type that implements [`IntoAad<'static>`](IntoAad) — `&'static str`,
/// `String`, `u64`, `Vec<u8>`, and tuples of these. (Non-`'static` borrowed tags such as a
/// short-lived `&str` are intentionally excluded; promote them to an owned `String` or a
/// `&'static str`.)
///
/// # Encrypting
///
/// `ContextTag` implements [`Encrypt`], so it is encrypted like any other value. The embedded tag
/// is bound automatically:
///
/// ```rust,ignore
/// use vitaminc_aead::{ContextTag, Encrypt};
///
/// // `cipher` implements `Cipher` for `&MyCipher` (see crate docs / `Aes256Cipher`).
/// let tagged = ContextTag::new("secret message", "user:42");
/// let ciphertext = tagged.encrypt(&cipher)?;
/// # Ok::<(), vitaminc_aead::Unspecified>(())
/// ```
///
/// # Decrypting
///
/// Mirror the encrypt side: rebuild the context with [`ContextTag::context`] (and the same
/// [`refine`](ContextTag::refine) chain, if any), then recover the value with
/// [`decrypt`](ContextTag::decrypt) / [`decrypt_with_aad`](ContextTag::decrypt_with_aad),
/// driving a [`Decipher`] obtained from the concrete cipher:
///
/// ```rust,ignore
/// use vitaminc_aead::ContextTag;
///
/// let plaintext: String =
///     ContextTag::context("user:42").decrypt(cipher.decipher(ciphertext))?;
/// # Ok::<(), vitaminc_aead::Unspecified>(())
/// ```
///
/// For lower-level control you can instead build the raw AAD with [`ContextTag::aad`] /
/// [`ContextTag::aad_with`] and pass it to a cipher's own decrypt entry point.
///
/// # Limitations
///
/// `ContextTag` is designed to wrap the **outermost** value being encrypted. A few corollaries are
/// worth knowing — none is a soundness issue, but each produces ciphertext that the obvious decrypt
/// call will reject:
///
/// - **Use [`refine`](ContextTag::refine), not nesting, to layer context.** Wrapping a `ContextTag`
///   *inside another* `ContextTag` (`ContextTag::new(ContextTag::new(v, "b"), "a")`) folds the AAD
///   twice into `((extra, "a"), "b")`, which the symmetric [`context`](ContextTag::context) +
///   `refine` decrypt path *cannot* reconstruct (it produces `(extra, ("a", "b"))`). Always layer
///   hierarchy with `ContextTag::new(v, "a").refine("b")`.
/// - **`ContextTag` has no [`Decrypt`] impl**, only an [`Encrypt`] impl. It therefore composes on
///   the encrypt side (you *can* build `Vec<ContextTag<…>>` and encrypt it) but a `ContextTag`
///   nested inside another structure has no symmetric decrypt path — decrypt only at the top level
///   via [`context`](ContextTag::context) / [`aad`](ContextTag::aad). Don't bury a `ContextTag`
///   inside a collection or struct you intend to read back.
/// - **A unit tag `()` still binds a (non-empty) tag.** `ContextTag::new(v, ())` seals against
///   `PAE(empty, empty)`, not empty AAD, so `cipher.decrypt(ct)` (empty AAD) will fail. If you want
///   no context, encrypt the bare value; if you want a context, give a real tag.
/// - **Tags must be [`IntoAad<'static>`](IntoAad)** (owned or `&'static`), so a short-lived `&str`
///   must be promoted to `String` / `&'static str` — see the tag-type note above.
pub struct ContextTag<Tag, T> {
    inner: T,
    tag: Tag,
}

impl<Tag, T> ContextTag<Tag, T> {
    /// Creates a new `ContextTag` pairing `inner` with the given `tag`.
    ///
    /// The tag is folded into the AAD whenever `inner` is encrypted.
    ///
    /// ```rust
    /// use vitaminc_aead::ContextTag;
    ///
    /// let tagged = ContextTag::new("hello", "my-tag");
    /// # let _ = tagged;
    /// ```
    pub fn new(inner: T, tag: Tag) -> Self {
        ContextTag { inner, tag }
    }

    /// Adds a second layer of context, producing a new `ContextTag` whose tag is the tuple
    /// `(original_tag, tag)`.
    ///
    /// Useful for building hierarchical context such as `("table:users", "column:email")`. The
    /// nested tag is PAE-encoded when converted to AAD bytes, so distinct hierarchies never
    /// collide. `refine` can be chained to build deeper hierarchies.
    ///
    /// ```rust
    /// use vitaminc_aead::ContextTag;
    ///
    /// let tagged = ContextTag::new("secret", "table:users").refine("column:email");
    /// // The tag is now ("table:users", "column:email").
    /// # let _ = tagged;
    /// ```
    pub fn refine<B>(self, tag: B) -> ContextTag<(Tag, B), T> {
        ContextTag {
            inner: self.inner,
            tag: (self.tag, tag),
        }
    }

    /// Consumes the wrapper, returning the inner value and its tag.
    pub fn into_parts(self) -> (T, Tag) {
        (self.inner, self.tag)
    }
}

impl<Tag> ContextTag<Tag, ()> {
    /// Low-level: builds the raw AAD tuple for **decrypting** a value sealed with
    /// `ContextTag::new(value, tag).encrypt(cipher)` (i.e. with no extra AAD).
    ///
    /// Prefer [`ContextTag::context`] + [`decrypt`](ContextTag::decrypt) where a
    /// [`Decipher`] is available — it folds the AAD for you and reconstructs nested
    /// [`refine`](ContextTag::refine) tags via the same path used at encrypt time. Reach for `aad`
    /// only to drive a cipher's own decrypt entry point directly.
    ///
    /// This reproduces the `(empty, tag)` layout the [`Encrypt`] impl binds, so a concrete cipher's
    /// decrypt entry point authenticates against exactly the same bytes.
    ///
    /// ```rust
    /// use vitaminc_aead::{ContextTag, IntoAad};
    ///
    /// // The AAD recovered for decryption matches what `encrypt` bound at seal time.
    /// let decrypt_aad = ContextTag::aad("user:42");
    /// assert_eq!(
    ///     decrypt_aad.into_aad().as_bytes(),
    ///     ((), "user:42").into_aad().as_bytes(),
    /// );
    /// ```
    pub fn aad(tag: Tag) -> (Aad<'static>, Tag) {
        (Aad::empty(), tag)
    }

    /// Low-level: builds the raw AAD tuple for **decrypting** a value sealed with
    /// `ContextTag::new(value, tag).encrypt_with_aad(cipher, extra_aad)`.
    ///
    /// Prefer [`ContextTag::context`] + [`decrypt_with_aad`](ContextTag::decrypt_with_aad), which
    /// puts the tag in the receiver so it can't be transposed with `extra_aad`. This builder takes
    /// **both** as positional, same-typed args (`extra_aad` first, then `tag`) — swapping them
    /// silently produces the wrong AAD, so reach for it only to drive a cipher's own decrypt entry
    /// point directly.
    ///
    /// Reproduces the `(extra_aad, tag)` layout bound at encrypt time.
    ///
    /// ```rust
    /// use vitaminc_aead::{ContextTag, IntoAad};
    ///
    /// let decrypt_aad = ContextTag::aad_with("row:99", "table:users");
    /// assert_eq!(
    ///     decrypt_aad.into_aad().as_bytes(),
    ///     ("row:99", "table:users").into_aad().as_bytes(),
    /// );
    /// ```
    pub fn aad_with<A>(extra_aad: A, tag: Tag) -> (A, Tag) {
        (extra_aad, tag)
    }

    /// Begins a decrypt-side context carrying `tag` (and no value yet).
    ///
    /// This is the decrypt mirror of [`ContextTag::new`]: build (and
    /// [`refine`](ContextTag::refine)) the tag exactly as you did at encrypt time,
    /// then call [`decrypt`](ContextTag::decrypt) /
    /// [`decrypt_with_aad`](ContextTag::decrypt_with_aad) to recover the value —
    /// so the tag (and any nested refinement) is reconstructed by the same code
    /// path that bound it, never re-typed by hand.
    ///
    /// ```rust
    /// use vitaminc_aead::ContextTag;
    ///
    /// // mirrors `ContextTag::new(value, "table:users").refine("column:email")`
    /// let ctx = ContextTag::context("table:users").refine("column:email");
    /// # let _ = ctx;
    /// ```
    pub fn context(tag: Tag) -> Self {
        ContextTag { inner: (), tag }
    }
}

impl<Tag> ContextTag<Tag, ()>
where
    Tag: IntoAad<'static>,
{
    /// Decrypts a value sealed against this context, authenticating against the
    /// embedded tag (no extra AAD). The decrypt mirror of
    /// [`ContextTag::encrypt`](Encrypt::encrypt).
    ///
    /// Obtain `decipher` from a concrete cipher (e.g. `cipher.decipher(ciphertext)`).
    pub fn decrypt<'c, T, D>(self, decipher: D) -> D::Ok<T>
    where
        D: Decipher<'c>,
        T: Decrypt<'c> + 'c,
    {
        self.decrypt_with_aad(decipher, Aad::empty())
    }

    /// Decrypts a value sealed against this context plus `extra_aad`, mirroring
    /// [`ContextTag::encrypt_with_aad`](Encrypt::encrypt_with_aad).
    ///
    /// The tag lives in the receiver and `extra_aad` is the lone argument, so the
    /// two cannot be swapped; the bound AAD is `(extra_aad, tag)` — byte-identical
    /// to what the [`Encrypt`] impl folds in at seal time. Obtain `decipher` from
    /// a concrete cipher (e.g. `cipher.decipher(ciphertext)`).
    pub fn decrypt_with_aad<'c, 'a, T, D, A>(self, decipher: D, extra_aad: A) -> D::Ok<T>
    where
        D: Decipher<'c>,
        T: Decrypt<'c> + 'c,
        A: IntoAad<'a>,
    {
        T::decrypt_with_aad(decipher, fold_tag_aad(self.tag, extra_aad))
    }
}

impl<Tag, T> Encrypt for ContextTag<Tag, T>
where
    T: Encrypt,
    // `Encrypt::encrypt_with_aad` chooses the AAD lifetime at the call site, but the tag is owned
    // by the wrapper. Requiring `IntoAad<'static>` lets the tag become an owned (or
    // `'static`-borrowed) `AadPiece` that we then re-borrow for the call's lifetime via covariance.
    // Owned tags (`String`, `u64`, `Vec<u8>`, tuples thereof) and `&'static str` satisfy this;
    // non-`'static` borrows do not — promote them to `String` or a `&'static str`.
    Tag: IntoAad<'static>,
{
    /// Encrypts the inner value, folding the embedded tag into the AAD.
    ///
    /// The final AAD is `(extra_aad, tag)`, PAE-encoded into an unambiguous byte representation
    /// that binds both pieces. The cipher receives it with its parts intact — `into_aad_piece()`
    /// gives `List([extra_aad, tag])` — and `into_aad()` writes the bytes in one allocation.
    fn encrypt_with_aad<'a, C, A>(self, cipher: C, extra_aad: A) -> Result<C::Ok, C::Error>
    where
        C: Cipher,
        A: IntoAad<'a>,
    {
        let ContextTag { inner, tag } = self;
        inner.encrypt_with_aad(cipher, fold_tag_aad(tag, extra_aad))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_util::MockCipher;
    use crate::DecipherVisitor;
    use std::cell::RefCell;
    use std::rc::Rc;

    #[test]
    fn cipher_receives_the_context_as_parts() {
        // The motivating consumer: a backend that names the parts must find
        // them intact — the tag as a nested list of its refinements, not as
        // pre-encoded bytes.
        use crate::test_util::PartsCipher;
        use std::borrow::Cow;
        let parts = PartsCipher::new();
        ContextTag::new("secret", "table:users")
            .refine("column:email")
            .encrypt_with_aad(&parts, "row:99")
            .expect("mock cipher cannot fail");
        let piece = parts.captured_piece().expect("aad captured");
        assert_eq!(
            piece,
            AadPiece::List(vec![
                AadPiece::Text(Cow::Borrowed("row:99")),
                AadPiece::List(vec![
                    AadPiece::Text(Cow::Borrowed("table:users")),
                    AadPiece::Text(Cow::Borrowed("column:email")),
                ]),
            ])
        );
        let names: Vec<String> = piece.leaves().map(ToString::to_string).collect();
        assert_eq!(names, ["\"row:99\"", "\"table:users\"", "\"column:email\""]);
        // Both views agree with the tuple: the parts tree re-encoded, and the
        // bytes a byte-oriented cipher gets from `FoldedAad::into_aad`.
        let expected = ("row:99", ("table:users", "column:email")).into_aad();
        assert_eq!(piece.into_aad().as_bytes(), expected.as_bytes());
        let bytes = MockCipher::new();
        ContextTag::new("secret", "table:users")
            .refine("column:email")
            .encrypt_with_aad(&bytes, "row:99")
            .expect("mock cipher cannot fail");
        assert_eq!(bytes.captured_aad(), expected.as_bytes());
    }

    #[test]
    fn encrypts_inner_value_and_binds_tag() {
        let plaintext = "hello world";
        let cipher = MockCipher::new();

        let ciphertext = ContextTag::new(plaintext, "tag_aad")
            .encrypt_with_aad(&cipher, "extra")
            .expect("encryption should succeed");

        // The inner value is encrypted unchanged...
        assert_eq!(ciphertext, plaintext.as_bytes());
        // ...and the bound AAD is PAE(extra, tag).
        let expected = Aad::pae(&[b"extra", b"tag_aad"]);
        assert_eq!(cipher.captured_aad(), expected.as_bytes());
    }

    #[test]
    fn encrypt_with_no_extra_aad_still_binds_tag() {
        let cipher = MockCipher::new();

        ContextTag::new("secret", "user:42")
            .encrypt(&cipher)
            .expect("encryption should succeed");

        // `encrypt` supplies an empty extra AAD, so the bound AAD is PAE(empty, tag).
        let expected = ((), "user:42").into_aad();
        assert_eq!(cipher.captured_aad(), expected.as_bytes());
    }

    #[test]
    fn unit_tag_still_binds_nonempty_aad() {
        let cipher = MockCipher::new();

        ContextTag::new("secret", ())
            .encrypt(&cipher)
            .expect("encryption should succeed");

        // Pins the documented boundary: a `()` tag binds PAE(empty, empty), which
        // is *not* empty AAD — so `cipher.decrypt(ct)` (empty AAD) must fail. A
        // regression that folded a `()` tag to empty AAD would silently break it.
        assert_eq!(cipher.captured_aad(), ((), ()).into_aad().as_bytes());
        assert_ne!(cipher.captured_aad(), Aad::empty().as_bytes());
    }

    #[test]
    fn refine_nests_the_tag() {
        let cipher = MockCipher::new();

        ContextTag::new("secret", "table:users")
            .refine("column:email")
            .encrypt_with_aad(&cipher, "extra")
            .expect("encryption should succeed");

        // extra + (table, column) => PAE(extra, PAE(table, column)).
        let inner = Aad::pae(&[b"table:users", b"column:email"]);
        let expected = Aad::pae(&[b"extra", inner.as_bytes()]);
        assert_eq!(cipher.captured_aad(), expected.as_bytes());
    }

    #[test]
    fn chained_refine_builds_left_nested_tuple() {
        let cipher = MockCipher::new();

        ContextTag::new("data", "a")
            .refine("b")
            .refine("c")
            .encrypt(&cipher)
            .expect("encryption should succeed");

        // tag = (("a", "b"), "c"); no extra AAD.
        let expected = ((), (("a", "b"), "c")).into_aad();
        assert_eq!(cipher.captured_aad(), expected.as_bytes());
    }

    #[test]
    fn nested_context_tag_folds_aad_twice() {
        let cipher = MockCipher::new();

        // The documented footgun: wrapping a `ContextTag` *inside another* rather
        // than layering with `refine`.
        ContextTag::new(ContextTag::new("secret", "b"), "a")
            .encrypt(&cipher)
            .expect("encryption should succeed");

        // Nesting folds the AAD twice into ((extra, "a"), "b") — extra = () here...
        assert_eq!(
            cipher.captured_aad(),
            (((), "a"), "b").into_aad().as_bytes()
        );
        // ...which is distinct from the symmetric refine layout ((), ("a", "b"))
        // that `context("a").refine("b")` decrypts against — hence the footgun.
        assert_ne!(
            cipher.captured_aad(),
            ((), ("a", "b")).into_aad().as_bytes()
        );
    }

    #[test]
    fn owned_string_tag_is_accepted() {
        let cipher = MockCipher::new();

        ContextTag::new("secret", String::from("owned-tag"))
            .encrypt(&cipher)
            .expect("encryption should succeed");

        let expected = ((), "owned-tag").into_aad();
        assert_eq!(cipher.captured_aad(), expected.as_bytes());
    }

    #[test]
    fn vec_u8_tag_is_accepted() {
        let cipher = MockCipher::new();

        // `Vec<u8>` is a documented tag type; exercise it like the &str/String cases.
        ContextTag::new("secret", vec![0xde_u8, 0xad, 0xbe, 0xef])
            .encrypt(&cipher)
            .expect("encryption should succeed");

        let expected = ((), vec![0xde_u8, 0xad, 0xbe, 0xef]).into_aad();
        assert_eq!(cipher.captured_aad(), expected.as_bytes());
    }

    #[test]
    fn aad_helper_matches_encrypt_binding() {
        // The AAD `ContextTag::aad` produces for decryption must equal what `encrypt` binds.
        let cipher = MockCipher::new();
        ContextTag::new("secret", "user:42")
            .encrypt(&cipher)
            .expect("encryption should succeed");

        let decrypt_aad = ContextTag::aad("user:42").into_aad();
        assert_eq!(cipher.captured_aad(), decrypt_aad.as_bytes());
    }

    #[test]
    fn aad_with_helper_matches_encrypt_binding() {
        let cipher = MockCipher::new();
        ContextTag::new("secret", "table:users")
            .encrypt_with_aad(&cipher, "row:99")
            .expect("encryption should succeed");

        let decrypt_aad = ContextTag::aad_with("row:99", "table:users").into_aad();
        assert_eq!(cipher.captured_aad(), decrypt_aad.as_bytes());
    }

    #[test]
    fn different_tags_produce_different_aad() {
        let cipher_a = MockCipher::new();
        let cipher_b = MockCipher::new();

        ContextTag::new("secret", "user:42")
            .encrypt(&cipher_a)
            .expect("encryption should succeed");
        ContextTag::new("secret", "user:99")
            .encrypt(&cipher_b)
            .expect("encryption should succeed");

        assert_ne!(cipher_a.captured_aad(), cipher_b.captured_aad());
    }

    #[test]
    fn into_parts_round_trips() {
        let tagged = ContextTag::new("secret", "ctx");
        let (inner, tag) = tagged.into_parts();
        assert_eq!(inner, "secret");
        assert_eq!(tag, "ctx");
    }

    /// A minimal [`Decipher`] that records the AAD bytes it is handed via `decrypt_bytes` and
    /// yields nothing. Lets the decrypt-side `ContextTag` helper's folded AAD be pinned
    /// byte-for-byte against an independent expected layout (and against the encrypt binding).
    struct CapturingDecipher {
        captured_aad: Rc<RefCell<Vec<u8>>>,
    }

    impl<'c> Decipher<'c> for CapturingDecipher {
        type Ok<T>
            = Option<T>
        where
            T: Send + 'c;

        type Passthrough = ();

        fn map_ok<T, U, F>(ok: Self::Ok<T>, f: F) -> Self::Ok<U>
        where
            T: Send + 'c,
            U: Send + 'c,
            F: FnOnce(T) -> U,
        {
            ok.map(f)
        }

        fn decrypt_bytes<'a, V, A>(self, _visitor: V, aad: A) -> Self::Ok<V::Value>
        where
            V: DecipherVisitor<'c> + Send + 'c,
            A: IntoAad<'a>,
        {
            *self.captured_aad.borrow_mut() = aad.into_aad().as_bytes().to_vec();
            None
        }

        fn decrypt_seq<'a, V, A>(self, _visitor: V, _aad: A) -> Self::Ok<V::Value>
        where
            V: DecipherVisitor<'c> + Send + 'c,
            A: IntoAad<'a>,
        {
            None
        }

        fn decrypt_map<'a, V, A>(self, _visitor: V, _aad: A) -> Self::Ok<V::Value>
        where
            V: DecipherVisitor<'c> + Send + 'c,
            A: IntoAad<'a>,
        {
            None
        }

        fn decrypt_any<'a, V, A>(self, _visitor: V, _aad: A) -> Self::Ok<V::Value>
        where
            V: DecipherVisitor<'c> + Send + 'c,
            A: IntoAad<'a>,
        {
            None
        }

        fn decrypt_passthrough(self) -> Self::Ok<Self::Passthrough> {
            None
        }

        fn decrypt_option<'a, T, A>(self, _aad: A) -> Self::Ok<Option<T>>
        where
            T: Decrypt<'c> + 'c,
            A: IntoAad<'a>,
        {
            None
        }
    }

    fn captured_helper_aad<F>(build: F) -> Vec<u8>
    where
        F: FnOnce(CapturingDecipher) -> Option<String>,
    {
        let captured = Rc::new(RefCell::new(Vec::new()));
        let _ = build(CapturingDecipher {
            captured_aad: Rc::clone(&captured),
        });
        let bytes = captured.borrow().clone();
        bytes
    }

    // The decrypt helper must fold byte-identical AAD to what the `Encrypt` impl binds. These pin
    // the helper against an *independent* expected layout (not the shared `fold_tag_aad`), so a
    // reorder of the fold would be caught even though both sides share it.

    #[test]
    fn decrypt_helper_folds_empty_extra_plus_tag() {
        let captured =
            captured_helper_aad(|d| ContextTag::context("user:42").decrypt::<String, _>(d));
        assert_eq!(captured, ((), "user:42").into_aad().as_bytes());
    }

    #[test]
    fn decrypt_helper_folds_extra_then_tag() {
        let captured = captured_helper_aad(|d| {
            ContextTag::context("table:users").decrypt_with_aad::<String, _, _>(d, "row:99")
        });
        assert_eq!(captured, ("row:99", "table:users").into_aad().as_bytes());
    }

    #[test]
    fn decrypt_helper_refine_folds_nested_tag() {
        let captured = captured_helper_aad(|d| {
            ContextTag::context("table:users")
                .refine("column:email")
                .decrypt::<String, _>(d)
        });
        assert_eq!(
            captured,
            ((), ("table:users", "column:email")).into_aad().as_bytes()
        );
    }

    #[test]
    fn decrypt_helper_matches_encrypt_binding() {
        // Cross-check: the helper's fold equals what the `Encrypt` impl actually binds.
        let cipher = MockCipher::new();
        ContextTag::new("secret", "table:users")
            .encrypt_with_aad(&cipher, "row:99")
            .expect("encryption should succeed");

        let captured = captured_helper_aad(|d| {
            ContextTag::context("table:users").decrypt_with_aad::<String, _, _>(d, "row:99")
        });
        assert_eq!(captured, cipher.captured_aad());
    }
}