nahui 0.2.0

Authenticated encryption (ChaCha20-Poly1305) and BLAKE3 content hashing for document attestation.
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
//! Authenticated encryption (ChaCha20-Poly1305) and BLAKE3 content hashing.
//!
//! ## Wire formats
//!
//! Single-shot ([`Vault::encrypt`] / [`Vault::decrypt`]):
//!
//! ```text
//! [ version (1 B) | nonce (12 B) | ciphertext (N B) | tag (16 B) ]
//! ```
//!
//! Streaming ([`Vault::encrypt_stream`] / [`Vault::decrypt_stream`]),
//! using the IETF STREAM construction over chunks of `STREAM_CHUNK` bytes:
//!
//! ```text
//! [ version (1 B) | header_nonce (7 B) | chunk_0 | chunk_1 | ... | chunk_final ]
//! ```
//!
//! Each chunk is `(plaintext_len + TAG_LEN)` bytes. The AEAD nonce per chunk
//! is derived from the header nonce, a 32-bit big-endian counter, and a
//! 1-byte "last block" flag, per the STREAM construction.
//!
//! ## Authenticated associated data (AAD)
//!
//! Every API takes an `aad: &[u8]` parameter that is bound into the AEAD tag
//! but not encrypted. Use this to bind a ciphertext to its context — e.g. a
//! filename, a user ID, or a document version — so that an attacker cannot
//! swap one valid ciphertext for another. Pass `b""` if you have no context.
//!
//! ## Usage
//!
//! ```rust
//! use nahui::crypto::Vault;
//!
//! // Generate a fresh random key (use `Vault::new(key)` if you already have
//! // one, e.g. derived from a password via Argon2 or fetched from a KMS).
//! let vault = Vault::generate().expect("OS RNG must be available");
//!
//! let ct = vault.encrypt(b"hello", b"file:notes.txt").unwrap();
//! let pt = vault.decrypt(&ct, b"file:notes.txt").unwrap();
//! assert_eq!(pt, b"hello");
//! ```

use std::io::{self, Read, Write};
use std::mem;

use chacha20poly1305::aead::stream::{DecryptorBE32, EncryptorBE32};
use chacha20poly1305::aead::{AeadInPlace, KeyInit};
use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce};
use zeroize::{Zeroize, Zeroizing};

/// Scrub `n` initialized bytes at indices `start..start + n` in `out`,
/// then truncate to `start`. Used on error paths where plaintext (or
/// keystream-XORed plaintext, pre-auth) was written past `start` and must
/// not linger in the caller's buffer.
///
/// Callers must have written `n` bytes at `start..start + n` and `out.len()`
/// must already be `>= start + n`. This is enforced with a real `assert!`
/// rather than `debug_assert!` because skipping it on a release build that
/// somehow violated the precondition would silently leak plaintext.
fn scrub_tail_and_truncate(out: &mut Vec<u8>, start: usize, n: usize) {
    let grown_len = start + n;
    assert!(
        out.len() >= grown_len,
        "scrub precondition violated: len={} < start+n={}",
        out.len(),
        grown_len
    );
    out[start..grown_len].zeroize();
    out.truncate(start);
}

/// Wire format version. Bumped on any breaking change to layout or
/// construction. Decrypters reject unknown versions.
pub const VERSION: u8 = 0x01;

/// Versions this build will accept on decrypt. Adding v2 support later means
/// appending to this slice, not rewriting the version check.
const ACCEPTED_VERSIONS: &[u8] = &[VERSION];

/// Length of the per-message AEAD nonce (single-shot).
pub const NONCE_LEN: usize = 12;
/// Length of the Poly1305 authentication tag.
pub const TAG_LEN: usize = 16;
/// Length of the STREAM header nonce (chunked streaming).
pub const STREAM_NONCE_LEN: usize = 7;
/// Plaintext bytes per streaming chunk. Each on-disk chunk is this + `TAG_LEN`.
pub const STREAM_CHUNK: usize = 64 * 1024;

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

/// All errors surfaced by the encryption / decryption APIs.
///
/// `Error` does not implement `Eq` because it wraps [`io::Error`], which
/// doesn't. A manual [`PartialEq`] impl compares variants by discriminant —
/// any two `Io(_)` are considered equal — so callers can write `==` in
/// tests without unwrapping `matches!`.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("I/O error: {0}")]
    Io(#[from] io::Error),
    #[error("data too short to be valid ciphertext")]
    TooShort,
    #[error("authentication failed: wrong key, wrong AAD, or tampered data")]
    AuthenticationFailed,
    #[error("unsupported wire-format version: {0:#04x}")]
    UnsupportedVersion(u8),
    /// Plaintext exceeds ChaCha20-Poly1305's ~2^38-byte limit. Unreachable
    /// on 64-bit platforms because `&[u8]` is capped at `isize::MAX`, but
    /// surfaced as a typed error rather than a panic so callers don't have
    /// to read source comments to know why `encrypt` won't panic.
    #[error("plaintext exceeds ChaCha20-Poly1305 message-length limit")]
    PlaintextTooLarge,
    /// The OS-level RNG (`getrandom`) failed. On a healthy system this
    /// should never happen; surfaced as a typed error so encrypt paths
    /// can return `Result` instead of panicking.
    #[error("OS RNG failure: {0}")]
    Rng(getrandom::Error),
}

impl From<getrandom::Error> for Error {
    fn from(e: getrandom::Error) -> Self {
        Self::Rng(e)
    }
}

impl PartialEq for Error {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Io(_), Self::Io(_))
            | (Self::TooShort, Self::TooShort)
            | (Self::AuthenticationFailed, Self::AuthenticationFailed)
            | (Self::PlaintextTooLarge, Self::PlaintextTooLarge)
            | (Self::Rng(_), Self::Rng(_)) => true,
            (Self::UnsupportedVersion(a), Self::UnsupportedVersion(b)) => a == b,
            _ => false,
        }
    }
}

// ---------------------------------------------------------------------------
// Hashing API
// ---------------------------------------------------------------------------

/// Return the BLAKE3 hash of `data`.
///
/// Hex-encode with `.to_hex()` for inclusion in a Nostr attestation note.
#[must_use]
pub fn hash_bytes(data: &[u8]) -> blake3::Hash {
    blake3::hash(data)
}

/// Return the BLAKE3 hash of the entire contents of `reader`.
///
/// Uses [`blake3::Hasher::update_reader`], which manages its own internal
/// buffer (and may use `memmap` or `rayon` when enabled) — so callers do
/// not pay for a per-call heap allocation.
///
/// # Errors
///
/// Returns [`Error::Io`] on any read failure.
pub fn hash_stream(reader: &mut impl Read) -> Result<blake3::Hash, Error> {
    let mut hasher = blake3::Hasher::new();
    hasher.update_reader(reader)?;
    Ok(hasher.finalize())
}

// ---------------------------------------------------------------------------
// Vault
// ---------------------------------------------------------------------------

/// Holds a keyed cipher and provides authenticated encryption / decryption.
///
/// The cipher's round-key state is the only key-derived material kept.
/// [`ChaCha20Poly1305`] implements [`ZeroizeOnDrop`] upstream, so the round
/// keys are wiped when the [`Vault`] is dropped — no manual zeroize derive
/// is needed on this struct.
///
/// The cipher is keyed once at construction and cloned per streaming
/// operation. Cloning a keyed `ChaCha20Poly1305` is cheap (round-key copy,
/// no key schedule re-run).
pub struct Vault {
    cipher: ChaCha20Poly1305,
}

/// `Vault` deliberately does not derive `Debug` — printing the master key
/// would defeat the point of zeroizing it. This impl prints only the type
/// name so downstream structs holding a `Vault` can still derive `Debug`.
impl std::fmt::Debug for Vault {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Vault").finish_non_exhaustive()
    }
}

// Static guarantee that `Vault` can be wrapped in `Arc<Vault>` and shared
// across threads — both fields are `Send + Sync`. If a future change
// breaks this, the build fails here, not at the first user complaint.
const _: fn() = || {
    const fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<Vault>();
};

impl Vault {
    /// Create a new vault from a 32-byte master key.
    ///
    /// The key is moved into a [`Zeroizing`] wrapper for the duration of
    /// the constructor and wiped before this function returns. The keyed
    /// cipher state retained by the vault is itself zeroized on drop.
    #[must_use]
    pub fn new(master_key: [u8; 32]) -> Self {
        let key = Zeroizing::new(master_key);
        let cipher = ChaCha20Poly1305::new(Key::from_slice(key.as_ref()));
        Self { cipher }
    }

    /// Create a new vault with a freshly generated 32-byte random key from
    /// the OS RNG. Prefer this over `Vault::new([0u8; 32])` or any
    /// hand-picked constant when you don't already have a key.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Rng`] if the OS RNG fails. On a healthy system this
    /// does not happen.
    pub fn generate() -> Result<Self, Error> {
        let mut key = Zeroizing::new([0u8; 32]);
        getrandom::getrandom(key.as_mut())?;
        Ok(Self::new(*key))
    }

    /// Clone of the keyed cipher state, consumed by the STREAM encryptor/
    /// decryptor constructors (which take `ChaCha20Poly1305` by value).
    /// Single-shot paths use `&self.cipher` directly.
    fn cipher(&self) -> ChaCha20Poly1305 {
        self.cipher.clone()
    }

    // --- In-memory API ---

    /// Encrypt `plaintext`, binding `aad` into the authentication tag.
    ///
    /// Returns `version || nonce || ciphertext || tag`. A fresh random nonce
    /// is generated on every call.
    ///
    /// `aad` is *not* encrypted but *is* authenticated — the same `aad` must
    /// be passed to [`Vault::decrypt`] or authentication will fail. Pass
    /// `b""` if you have no context to bind.
    ///
    /// # Errors
    ///
    /// - [`Error::PlaintextTooLarge`] if `plaintext` exceeds ChaCha20-Poly1305's
    ///   message-length limit (~2^38 bytes). Unreachable on 64-bit platforms
    ///   because `&[u8]` is capped at `isize::MAX`.
    /// - [`Error::Rng`] if the OS RNG fails. On a healthy system this does
    ///   not happen.
    pub fn encrypt(&self, plaintext: &[u8], aad: &[u8]) -> Result<Vec<u8>, Error> {
        let mut out = Vec::with_capacity(1 + NONCE_LEN + plaintext.len() + TAG_LEN);
        self.encrypt_into(plaintext, aad, &mut out)?;
        Ok(out)
    }

    /// Encrypt `plaintext` into a caller-provided `out` buffer, appending
    /// `version || nonce || ciphertext || tag`. `out` is *not* cleared — use
    /// `out.clear()` first if you want to overwrite prior contents.
    ///
    /// Reusing a single `Vec<u8>` across many calls lets the hot path run
    /// allocation-free once the buffer's capacity has grown to the largest
    /// frame size seen so far.
    ///
    /// `aad` is authenticated but not encrypted, same as [`Vault::encrypt`].
    ///
    /// On [`Error::PlaintextTooLarge`], `out` is restored to its pre-call
    /// length so callers never see a partially written frame.
    ///
    /// # Errors
    ///
    /// - [`Error::PlaintextTooLarge`] if `plaintext` exceeds ChaCha20-Poly1305's
    ///   message-length limit (~2^38 bytes). Unreachable on 64-bit platforms
    ///   because `&[u8]` is capped at `isize::MAX`.
    /// - [`Error::Rng`] if the OS RNG fails. On a healthy system this does
    ///   not happen.
    pub fn encrypt_into(
        &self,
        plaintext: &[u8],
        aad: &[u8],
        out: &mut Vec<u8>,
    ) -> Result<(), Error> {
        let mut nonce_bytes = [0u8; NONCE_LEN];
        getrandom::getrandom(&mut nonce_bytes)?;
        let nonce = Nonce::from_slice(&nonce_bytes);

        let bound_aad = BoundAad::new(VERSION, aad);

        let start = out.len();
        out.reserve(1 + NONCE_LEN + plaintext.len() + TAG_LEN);
        let ct_start = start + 1 + NONCE_LEN;
        out.push(VERSION);
        out.extend_from_slice(&nonce_bytes);
        out.extend_from_slice(plaintext);

        // ChaCha20-Poly1305 only fails when msg length exceeds ~2^38 bytes;
        // on 64-bit Rust a `&[u8]` that large cannot exist (isize::MAX cap),
        // so `PlaintextTooLarge` is unreachable there. We surface it as a
        // typed error anyway — no `.expect()` in crypto code.
        if let Ok(tag) =
            self.cipher
                .encrypt_in_place_detached(nonce, bound_aad.as_slice(), &mut out[ct_start..])
        {
            out.extend_from_slice(&tag);
            Ok(())
        } else {
            // Plaintext is still sitting at out[ct_start..out.len()] — zeroize
            // it before dropping the length, or it will linger in the Vec's
            // spare capacity until a later call overwrites it.
            let written = out.len() - start;
            scrub_tail_and_truncate(out, start, written);
            Err(Error::PlaintextTooLarge)
        }
    }

    /// Decrypt data produced by [`Vault::encrypt`] with the same `aad`.
    ///
    /// # Errors
    ///
    /// - [`Error::TooShort`] if `data` is smaller than the minimum frame.
    /// - [`Error::UnsupportedVersion`] if the version byte is not recognized.
    /// - [`Error::AuthenticationFailed`] on wrong key, wrong AAD, or tampering.
    pub fn decrypt(&self, data: &[u8], aad: &[u8]) -> Result<Vec<u8>, Error> {
        let mut out = Vec::new();
        self.decrypt_into(data, aad, &mut out)?;
        Ok(out)
    }

    /// Decrypt `data` produced by [`Vault::encrypt`] into a caller-provided
    /// `out` buffer, appending the plaintext.
    ///
    /// On success, `out.len()` grows by `data.len() - 1 - NONCE_LEN - TAG_LEN`.
    /// On failure, `out` is unchanged (no partial plaintext is exposed before
    /// the tag is verified).
    ///
    /// Reusing a single `Vec<u8>` across many calls lets the hot path run
    /// allocation-free once the buffer's capacity is large enough.
    ///
    /// # Errors
    ///
    /// - [`Error::TooShort`] if `data` is smaller than the minimum frame.
    /// - [`Error::UnsupportedVersion`] if the version byte is not recognized.
    /// - [`Error::AuthenticationFailed`] on wrong key, wrong AAD, or tampering.
    pub fn decrypt_into(&self, data: &[u8], aad: &[u8], out: &mut Vec<u8>) -> Result<(), Error> {
        if data.len() < 1 + NONCE_LEN + TAG_LEN {
            return Err(Error::TooShort);
        }
        let version = data[0];
        if !ACCEPTED_VERSIONS.contains(&version) {
            return Err(Error::UnsupportedVersion(version));
        }
        // Exclusive `1 + NONCE_LEN` mirrors the `1 + NONCE_LEN + TAG_LEN`
        // length check above and the `1 + NONCE_LEN..` ct/tag split below.
        // Using `1..=NONCE_LEN` forces readers to convert between forms.
        #[allow(clippy::range_plus_one)]
        let nonce = Nonce::from_slice(&data[1..1 + NONCE_LEN]);
        let ct_and_tag = &data[1 + NONCE_LEN..];
        let ct_len = ct_and_tag.len() - TAG_LEN;
        let (ct, tag) = ct_and_tag.split_at(ct_len);
        let tag = chacha20poly1305::Tag::from_slice(tag);

        let bound_aad = BoundAad::new(version, aad);

        // Append ct into out, decrypt in place. On auth failure the buffer
        // at out[start..] holds unauthenticated plaintext (the keystream XOR
        // happens before tag verification), so we must scrub it — not just
        // shrink len past it — before returning.
        let start = out.len();
        out.reserve(ct_len);
        out.extend_from_slice(ct);
        if self
            .cipher
            .decrypt_in_place_detached(nonce, bound_aad.as_slice(), &mut out[start..], tag)
            .is_err()
        {
            scrub_tail_and_truncate(out, start, ct_len);
            return Err(Error::AuthenticationFailed);
        }
        Ok(())
    }

    // --- Streaming API ---

    /// Stream-encrypt `reader` into `writer` using the STREAM construction.
    ///
    /// Output is `version || header_nonce || chunk_0 || chunk_1 || ...`.
    /// Memory usage is O(`STREAM_CHUNK`) regardless of input size. The
    /// resulting stream can be decrypted with [`Vault::decrypt_stream`]
    /// from any `Read` — no `Seek` required.
    ///
    /// # Errors
    ///
    /// - [`Error::Io`] on any read or write failure.
    /// - [`Error::Rng`] if the OS RNG fails when generating the header nonce.
    pub fn encrypt_stream(
        &self,
        reader: &mut impl Read,
        writer: &mut impl Write,
        aad: &[u8],
    ) -> Result<(), Error> {
        self.encrypt_stream_inner(reader, writer, aad, None)?;
        Ok(())
    }

    /// Stream-encrypt `reader` into `writer`, returning the BLAKE3 hash of
    /// the **plaintext**.
    ///
    /// Identical wire format to [`Vault::encrypt_stream`]. The plaintext is
    /// hashed in the same pass, before each chunk is encrypted.
    ///
    /// # Errors
    ///
    /// - [`Error::Io`] on any read or write failure.
    /// - [`Error::Rng`] if the OS RNG fails when generating the header nonce.
    pub fn hash_and_encrypt_stream(
        &self,
        reader: &mut impl Read,
        writer: &mut impl Write,
        aad: &[u8],
    ) -> Result<blake3::Hash, Error> {
        let mut hasher = blake3::Hasher::new();
        self.encrypt_stream_inner(reader, writer, aad, Some(&mut hasher))?;
        Ok(hasher.finalize())
    }

    fn encrypt_stream_inner(
        &self,
        reader: &mut impl Read,
        writer: &mut impl Write,
        aad: &[u8],
        mut plaintext_hasher: Option<&mut blake3::Hasher>,
    ) -> Result<(), Error> {
        let mut header_nonce = [0u8; STREAM_NONCE_LEN];
        getrandom::getrandom(&mut header_nonce)?;

        writer.write_all(&[VERSION])?;
        writer.write_all(&header_nonce)?;

        let bound_aad = BoundAad::new(VERSION, aad);
        let mut encryptor = EncryptorBE32::from_aead(self.cipher(), header_nonce.as_ref().into());

        // Two chunk buffers reused across iterations. Capacity is reserved
        // once up front (STREAM_CHUNK + TAG_LEN) so the in-place AEAD can
        // append the Poly1305 tag without reallocating. `buf` holds the
        // chunk currently being encrypted; `next` peeks one ahead so we
        // know whether `buf` is the final chunk.
        let mut buf: Vec<u8> = Vec::with_capacity(STREAM_CHUNK + TAG_LEN);
        let mut next: Vec<u8> = Vec::with_capacity(STREAM_CHUNK + TAG_LEN);
        buf.resize(STREAM_CHUNK, 0);
        next.resize(STREAM_CHUNK, 0);
        let mut pending = read_up_to(reader, &mut buf)?;
        loop {
            next.resize(STREAM_CHUNK, 0);
            let next_len = read_up_to(reader, &mut next)?;

            if let Some(h) = plaintext_hasher.as_deref_mut() {
                h.update(&buf[..pending]);
            }

            buf.truncate(pending);

            if next_len == 0 {
                encryptor
                    .encrypt_last_in_place(bound_aad.as_slice(), &mut buf)
                    .map_err(|_| io::Error::other("STREAM encrypt_last failed"))?;
                writer.write_all(&buf)?;
                return Ok(());
            }

            encryptor
                .encrypt_next_in_place(bound_aad.as_slice(), &mut buf)
                .map_err(|_| io::Error::other("STREAM encrypt_next failed"))?;
            writer.write_all(&buf)?;

            mem::swap(&mut buf, &mut next);
            pending = next_len;
        }
    }

    /// Stream-decrypt `reader` into `writer`. Does *not* require `Seek`.
    ///
    /// Each chunk is authenticated as it is read, so plaintext is only
    /// emitted once the chunk's tag has verified. A truncated stream is
    /// detected because the final chunk carries a "last block" flag.
    ///
    /// `writer` will receive up to `input_size - overhead` bytes of
    /// plaintext. If the caller cannot bound the input, it should bound the
    /// writer (e.g. by wrapping a size-capped `Vec` or by streaming to disk
    /// with a quota) — this function does not allocate the output.
    ///
    /// # Errors
    ///
    /// - [`Error::Io`] on any read or write failure.
    /// - [`Error::TooShort`] if the stream is smaller than the header.
    /// - [`Error::UnsupportedVersion`] if the version byte is not recognized.
    /// - [`Error::AuthenticationFailed`] on wrong key, wrong AAD, tampering,
    ///   or truncation.
    pub fn decrypt_stream(
        &self,
        reader: &mut impl Read,
        writer: &mut impl Write,
        aad: &[u8],
    ) -> Result<(), Error> {
        let mut version = [0u8; 1];
        match reader.read_exact(&mut version) {
            Ok(()) => {}
            Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Err(Error::TooShort),
            Err(e) => return Err(Error::Io(e)),
        }
        if !ACCEPTED_VERSIONS.contains(&version[0]) {
            return Err(Error::UnsupportedVersion(version[0]));
        }

        let mut header_nonce = [0u8; STREAM_NONCE_LEN];
        match reader.read_exact(&mut header_nonce) {
            Ok(()) => {}
            Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Err(Error::TooShort),
            Err(e) => return Err(Error::Io(e)),
        }

        let bound_aad = BoundAad::new(version[0], aad);
        let mut decryptor = DecryptorBE32::from_aead(self.cipher(), header_nonce.as_ref().into());

        // Each on-disk chunk is STREAM_CHUNK + TAG_LEN bytes (except the
        // final one, which may be shorter). Capacity reserved once so
        // decrypt_*_in_place can operate without reallocating. Peek one
        // chunk ahead to know which one is "last".
        let frame = STREAM_CHUNK + TAG_LEN;
        let mut current: Vec<u8> = Vec::with_capacity(frame);
        let mut next: Vec<u8> = Vec::with_capacity(frame);
        current.resize(frame, 0);
        let mut current_len = read_up_to(reader, &mut current)?;
        if current_len < TAG_LEN {
            return Err(Error::AuthenticationFailed);
        }
        loop {
            next.resize(frame, 0);
            let next_len = read_up_to(reader, &mut next)?;

            current.truncate(current_len);

            if next_len == 0 {
                decryptor
                    .decrypt_last_in_place(bound_aad.as_slice(), &mut current)
                    .map_err(|_| Error::AuthenticationFailed)?;
                writer.write_all(&current)?;
                return Ok(());
            }
            if next_len < TAG_LEN {
                return Err(Error::AuthenticationFailed);
            }

            decryptor
                .decrypt_next_in_place(bound_aad.as_slice(), &mut current)
                .map_err(|_| Error::AuthenticationFailed)?;
            writer.write_all(&current)?;

            mem::swap(&mut current, &mut next);
            current_len = next_len;
        }
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Prepend a wire-format version byte to user-supplied AAD so a v1 ciphertext
/// can never authenticate against a v2 build (and vice versa).
///
/// On encrypt, callers pass the version they're writing (currently [`VERSION`]).
/// On decrypt, callers pass the version byte they read from `data[0]` — *not*
/// the build's `VERSION` constant — so that adding a new accepted version
/// later doesn't silently invalidate every blob written under the old one.
///
/// AAD for document-attestation contexts is almost always a short string
/// (filename, user id, doc version), so the common path fits in an inline
/// stack buffer. Only falls back to the heap for unusually large AAD.
const BOUND_AAD_INLINE: usize = 64;

enum BoundAad {
    Inline {
        buf: [u8; BOUND_AAD_INLINE],
        len: usize,
    },
    Heap(Vec<u8>),
}

impl BoundAad {
    fn new(version: u8, user_aad: &[u8]) -> Self {
        let total = 1 + user_aad.len();
        if total <= BOUND_AAD_INLINE {
            let mut buf = [0u8; BOUND_AAD_INLINE];
            buf[0] = version;
            buf[1..total].copy_from_slice(user_aad);
            Self::Inline { buf, len: total }
        } else {
            let mut v = Vec::with_capacity(total);
            v.push(version);
            v.extend_from_slice(user_aad);
            Self::Heap(v)
        }
    }

    fn as_slice(&self) -> &[u8] {
        match self {
            Self::Inline { buf, len } => &buf[..*len],
            Self::Heap(v) => v.as_slice(),
        }
    }
}

/// Read until `buf` is full or EOF. Returns the number of bytes read.
/// Unlike `read_exact`, an EOF in the middle is *not* an error — it just
/// returns a short count.
fn read_up_to(reader: &mut impl Read, buf: &mut [u8]) -> io::Result<usize> {
    let mut total = 0;
    while total < buf.len() {
        match reader.read(&mut buf[total..]) {
            Ok(0) => return Ok(total),
            Ok(n) => total += n,
            Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
            Err(e) => return Err(e),
        }
    }
    Ok(total)
}

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

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use super::*;

    const KEY: [u8; 32] = [0x42; 32];
    const AAD: &[u8] = b"test-context";

    fn vault() -> Vault {
        Vault::new(KEY)
    }

    // --- In-memory ---

    #[test]
    fn into_variants_roundtrip() {
        let v = vault();
        let mut ct = Vec::new();
        v.encrypt_into(b"hello", AAD, &mut ct).unwrap();
        let mut pt = Vec::new();
        v.decrypt_into(&ct, AAD, &mut pt).unwrap();
        assert_eq!(pt, b"hello");
        // And the owned API produces a ciphertext decryptable by the same key.
        let ct2 = v.encrypt(b"hello", AAD).unwrap();
        assert_eq!(v.decrypt(&ct2, AAD).unwrap(), b"hello");
    }

    #[test]
    fn into_variants_append() {
        // _into appends rather than clobbering, so callers can stage multiple
        // frames in one buffer if they want. Verify with a sentinel prefix.
        let v = vault();
        let mut ct = vec![0xAA, 0xBB, 0xCC];
        v.encrypt_into(b"payload", AAD, &mut ct).unwrap();
        assert_eq!(&ct[..3], &[0xAA, 0xBB, 0xCC]);
        // Skip past the sentinel for a correct decrypt.
        assert_eq!(v.decrypt(&ct[3..], AAD).unwrap(), b"payload");
    }

    #[test]
    fn decrypt_into_reuses_buffer() {
        // Encrypt three different messages into the same output buffer.
        // After the third call, the buffer should be allocated exactly once
        // (capacity stays >= the largest message) but the len equals the
        // plaintext of the last call only.
        let v = vault();
        let msgs: [&[u8]; 3] = [b"one", b"two-two", b"three-three-three"];
        let mut pt = Vec::with_capacity(64);
        let initial_cap = pt.capacity();
        for msg in msgs {
            let ct = v.encrypt(msg, AAD).unwrap();
            pt.clear();
            v.decrypt_into(&ct, AAD, &mut pt).unwrap();
            assert_eq!(pt, msg);
        }
        assert_eq!(pt.capacity(), initial_cap, "no realloc expected");
    }

    #[test]
    fn decrypt_into_leaves_buffer_unchanged_on_failure() {
        // A partial write of ciphertext that fails to authenticate must not
        // leak any plaintext into `out` — the buffer should be restored to
        // its pre-call length.
        let v = vault();
        let mut ct = v.encrypt(b"secret", AAD).unwrap();
        *ct.last_mut().unwrap() ^= 0xff;
        let mut out = vec![0x11, 0x22, 0x33];
        let before = out.clone();
        assert!(matches!(
            v.decrypt_into(&ct, AAD, &mut out),
            Err(Error::AuthenticationFailed)
        ));
        assert_eq!(out, before);
    }

    #[test]
    fn roundtrip_empty() {
        let v = vault();
        let ct = v.encrypt(b"", AAD).unwrap();
        assert_eq!(v.decrypt(&ct, AAD).unwrap(), b"");
    }

    #[test]
    fn roundtrip_small() {
        let v = vault();
        let ct = v.encrypt(b"hello, nahui!", AAD).unwrap();
        assert_eq!(v.decrypt(&ct, AAD).unwrap(), b"hello, nahui!");
    }

    #[test]
    fn roundtrip_large() {
        let v = vault();
        let msg: Vec<u8> = (0u32..)
            .map(|i| u8::try_from(i & 0xFF).unwrap())
            .take(10 * 1024 * 1024)
            .collect();
        let ct = v.encrypt(&msg, AAD).unwrap();
        assert_eq!(v.decrypt(&ct, AAD).unwrap(), msg);
    }

    #[test]
    fn output_length() {
        let v = vault();
        let ct = v.encrypt(b"four", AAD).unwrap();
        assert_eq!(ct.len(), 1 + NONCE_LEN + 4 + TAG_LEN);
    }

    #[test]
    fn nonce_is_random() {
        let v = vault();
        let ct1 = v.encrypt(b"same", AAD).unwrap();
        let ct2 = v.encrypt(b"same", AAD).unwrap();
        assert_ne!(ct1, ct2);
    }

    // --- Failure cases ---

    #[test]
    fn wrong_key_fails() {
        let v = vault();
        let ct = v.encrypt(b"secret", AAD).unwrap();
        let bad = Vault::new([0u8; 32]);
        assert!(matches!(
            bad.decrypt(&ct, AAD),
            Err(Error::AuthenticationFailed)
        ));
    }

    #[test]
    fn wrong_aad_fails() {
        let v = vault();
        let ct = v.encrypt(b"secret", b"context-A").unwrap();
        assert!(matches!(
            v.decrypt(&ct, b"context-B"),
            Err(Error::AuthenticationFailed)
        ));
    }

    #[test]
    fn tampered_ciphertext_fails() {
        let v = vault();
        let mut ct = v.encrypt(b"secret", AAD).unwrap();
        ct[1 + NONCE_LEN] ^= 0xff;
        assert!(matches!(
            v.decrypt(&ct, AAD),
            Err(Error::AuthenticationFailed)
        ));
    }

    #[test]
    fn tampered_tag_fails() {
        let v = vault();
        let mut ct = v.encrypt(b"secret", AAD).unwrap();
        let last = ct.len() - 1;
        ct[last] ^= 0xff;
        assert!(matches!(
            v.decrypt(&ct, AAD),
            Err(Error::AuthenticationFailed)
        ));
    }

    #[test]
    fn tampered_nonce_fails() {
        let v = vault();
        let mut ct = v.encrypt(b"secret", AAD).unwrap();
        ct[1] ^= 0xff;
        assert!(matches!(
            v.decrypt(&ct, AAD),
            Err(Error::AuthenticationFailed)
        ));
    }

    #[test]
    fn unknown_version_fails() {
        let v = vault();
        let mut ct = v.encrypt(b"secret", AAD).unwrap();
        ct[0] = 0xFE;
        assert!(matches!(
            v.decrypt(&ct, AAD),
            Err(Error::UnsupportedVersion(0xFE))
        ));
    }

    #[test]
    fn too_short_fails() {
        let v = vault();
        assert!(matches!(v.decrypt(&[], AAD), Err(Error::TooShort)));
        assert!(matches!(v.decrypt(&[0u8; 10], AAD), Err(Error::TooShort)));
        let ct = v.encrypt(b"", AAD).unwrap();
        assert_eq!(ct.len(), 1 + NONCE_LEN + TAG_LEN);
        assert!(v.decrypt(&ct, AAD).is_ok());
    }

    #[test]
    fn truncated_ciphertext_fails() {
        let v = vault();
        let ct = v.encrypt(b"truncation test", AAD).unwrap();
        assert!(v.decrypt(&ct[..ct.len() - 1], AAD).is_err());
        assert!(v.decrypt(&ct[..ct.len() - TAG_LEN], AAD).is_err());
        assert!(v.decrypt(&ct[..=NONCE_LEN], AAD).is_err());
    }

    #[test]
    fn appended_bytes_fails() {
        let v = vault();
        let mut ct = v.encrypt(b"append test", AAD).unwrap();
        ct.push(0x00);
        assert!(matches!(
            v.decrypt(&ct, AAD),
            Err(Error::AuthenticationFailed)
        ));
    }

    // --- Streaming ---

    #[test]
    fn stream_roundtrip_empty() {
        let v = vault();
        let mut ct = Vec::new();
        v.encrypt_stream(&mut Cursor::new(b"".as_slice()), &mut ct, AAD)
            .unwrap();
        let mut pt = Vec::new();
        v.decrypt_stream(&mut Cursor::new(ct), &mut pt, AAD)
            .unwrap();
        assert!(pt.is_empty());
    }

    #[test]
    fn stream_roundtrip_small() {
        let v = vault();
        let mut ct = Vec::new();
        v.encrypt_stream(
            &mut Cursor::new(b"streaming hello".as_slice()),
            &mut ct,
            AAD,
        )
        .unwrap();
        let mut pt = Vec::new();
        v.decrypt_stream(&mut Cursor::new(ct), &mut pt, AAD)
            .unwrap();
        assert_eq!(pt, b"streaming hello");
    }

    #[test]
    fn stream_roundtrip_large() {
        let v = vault();
        let msg: Vec<u8> = (0u32..)
            .map(|i| u8::try_from(i & 0xFF).unwrap())
            .take(5 * 1024 * 1024)
            .collect();
        let mut ct = Vec::new();
        v.encrypt_stream(&mut Cursor::new(&msg), &mut ct, AAD)
            .unwrap();
        let mut pt = Vec::new();
        v.decrypt_stream(&mut Cursor::new(ct), &mut pt, AAD)
            .unwrap();
        assert_eq!(pt, msg);
    }

    #[test]
    fn stream_roundtrip_at_chunk_boundaries() {
        let v = vault();
        for size in [
            STREAM_CHUNK - 1,
            STREAM_CHUNK,
            STREAM_CHUNK + 1,
            2 * STREAM_CHUNK,
            2 * STREAM_CHUNK + 1,
            5 * STREAM_CHUNK,
        ] {
            let msg: Vec<u8> = (0u8..=255).cycle().take(size).collect();
            let mut ct = Vec::new();
            v.encrypt_stream(&mut Cursor::new(&msg), &mut ct, AAD)
                .unwrap();
            let mut pt = Vec::new();
            v.decrypt_stream(&mut Cursor::new(ct), &mut pt, AAD)
                .unwrap();
            assert_eq!(pt, msg, "failed at size {size}");
        }
    }

    #[test]
    fn stream_wrong_key_fails() {
        let v = vault();
        let mut ct = Vec::new();
        v.encrypt_stream(&mut Cursor::new(b"secret".as_slice()), &mut ct, AAD)
            .unwrap();
        let bad = Vault::new([0u8; 32]);
        let mut pt = Vec::new();
        assert!(matches!(
            bad.decrypt_stream(&mut Cursor::new(ct), &mut pt, AAD),
            Err(Error::AuthenticationFailed)
        ));
    }

    #[test]
    fn stream_wrong_aad_fails() {
        let v = vault();
        let mut ct = Vec::new();
        v.encrypt_stream(&mut Cursor::new(b"secret".as_slice()), &mut ct, b"A")
            .unwrap();
        let mut pt = Vec::new();
        assert!(matches!(
            v.decrypt_stream(&mut Cursor::new(ct), &mut pt, b"B"),
            Err(Error::AuthenticationFailed)
        ));
    }

    #[test]
    fn stream_tampered_ciphertext_fails() {
        let v = vault();
        let mut ct = Vec::new();
        v.encrypt_stream(&mut Cursor::new(b"secret".as_slice()), &mut ct, AAD)
            .unwrap();
        // Flip a byte in the first chunk's ciphertext (after version+header_nonce).
        ct[1 + STREAM_NONCE_LEN] ^= 0xff;
        let mut pt = Vec::new();
        assert!(matches!(
            v.decrypt_stream(&mut Cursor::new(ct), &mut pt, AAD),
            Err(Error::AuthenticationFailed)
        ));
    }

    #[test]
    fn stream_tampered_tag_fails() {
        let v = vault();
        let mut ct = Vec::new();
        v.encrypt_stream(&mut Cursor::new(b"mac test".as_slice()), &mut ct, AAD)
            .unwrap();
        let last = ct.len() - 1;
        ct[last] ^= 0xff;
        let mut pt = Vec::new();
        assert!(matches!(
            v.decrypt_stream(&mut Cursor::new(ct), &mut pt, AAD),
            Err(Error::AuthenticationFailed)
        ));
    }

    #[test]
    fn stream_tampered_header_nonce_fails() {
        let v = vault();
        let mut ct = Vec::new();
        v.encrypt_stream(&mut Cursor::new(b"hello".as_slice()), &mut ct, AAD)
            .unwrap();
        ct[1] ^= 0xff;
        let mut pt = Vec::new();
        assert!(matches!(
            v.decrypt_stream(&mut Cursor::new(ct), &mut pt, AAD),
            Err(Error::AuthenticationFailed)
        ));
    }

    #[test]
    fn stream_unknown_version_fails() {
        let v = vault();
        let mut ct = Vec::new();
        v.encrypt_stream(&mut Cursor::new(b"hi".as_slice()), &mut ct, AAD)
            .unwrap();
        ct[0] = 0xFE;
        let mut pt = Vec::new();
        assert!(matches!(
            v.decrypt_stream(&mut Cursor::new(ct), &mut pt, AAD),
            Err(Error::UnsupportedVersion(0xFE))
        ));
    }

    #[test]
    fn stream_truncated_at_boundary_fails() {
        // Two-chunk stream truncated to remove the final chunk: the "last
        // block" flag never appears, so STREAM detects truncation.
        let v = vault();
        let msg: Vec<u8> = (0u8..=255).cycle().take(STREAM_CHUNK + 1024).collect();
        let mut ct = Vec::new();
        v.encrypt_stream(&mut Cursor::new(&msg), &mut ct, AAD)
            .unwrap();

        // Drop the final chunk entirely, keep the first complete chunk.
        let truncated = &ct[..1 + STREAM_NONCE_LEN + STREAM_CHUNK + TAG_LEN];
        let mut pt = Vec::new();
        assert!(matches!(
            v.decrypt_stream(&mut Cursor::new(truncated), &mut pt, AAD),
            Err(Error::AuthenticationFailed)
        ));
    }

    #[test]
    fn stream_too_short_fails() {
        let v = vault();
        let mut pt = Vec::new();
        assert!(matches!(
            v.decrypt_stream(&mut Cursor::new(Vec::new()), &mut pt, AAD),
            Err(Error::TooShort)
        ));
        let short = vec![0u8; STREAM_NONCE_LEN]; // missing version byte too
        assert!(matches!(
            v.decrypt_stream(&mut Cursor::new(short), &mut pt, AAD),
            Err(Error::TooShort | Error::UnsupportedVersion(_))
        ));
    }

    // --- Hashing ---

    #[test]
    fn hash_bytes_is_deterministic() {
        assert_eq!(hash_bytes(b"hello"), hash_bytes(b"hello"));
    }

    #[test]
    fn hash_bytes_and_stream_agree() {
        let data: Vec<u8> = (0u8..=255).cycle().take(200_000).collect();
        let h_mem = hash_bytes(&data);
        let h_stream = hash_stream(&mut Cursor::new(&data)).unwrap();
        assert_eq!(h_mem, h_stream);
    }

    #[test]
    fn hash_and_encrypt_stream_hash_matches_plaintext() {
        let v = vault();
        let msg: Vec<u8> = (0u8..=255).cycle().take(300_000).collect();
        let expected = hash_bytes(&msg);
        let mut ct = Vec::new();
        let got = v
            .hash_and_encrypt_stream(&mut Cursor::new(&msg), &mut ct, AAD)
            .unwrap();
        assert_eq!(expected, got);
    }

    #[test]
    fn hash_and_encrypt_stream_output_is_decryptable() {
        let v = vault();
        let mut ct = Vec::new();
        v.hash_and_encrypt_stream(&mut Cursor::new(b"attest".as_slice()), &mut ct, AAD)
            .unwrap();
        let mut pt = Vec::new();
        v.decrypt_stream(&mut Cursor::new(ct), &mut pt, AAD)
            .unwrap();
        assert_eq!(pt, b"attest");
    }

    #[test]
    fn hash_to_hex_is_64_chars() {
        assert_eq!(hash_bytes(b"test").to_hex().len(), 64);
    }

    // --- Wrong-key sweeps ---

    #[test]
    fn wrong_key_does_not_reveal_plaintext() {
        let v = vault();
        let ct = v.encrypt(b"super secret", AAD).unwrap();
        for i in 0u8..=255 {
            let mut raw = [i; 32];
            raw[0] = i;
            if raw == KEY {
                continue;
            }
            assert!(
                Vault::new(raw).decrypt(&ct, AAD).is_err(),
                "key {i} must fail"
            );
        }
    }

    #[test]
    fn single_bit_key_difference_fails() {
        let v = vault();
        let ct = v.encrypt(b"bit-flip", AAD).unwrap();
        for byte_idx in 0..32 {
            for bit in 0..8 {
                let mut raw = KEY;
                raw[byte_idx] ^= 1 << bit;
                assert!(
                    Vault::new(raw).decrypt(&ct, AAD).is_err(),
                    "bit {bit} of byte {byte_idx} must fail"
                );
            }
        }
    }

    #[test]
    fn all_zero_key_works() {
        let v = Vault::new([0u8; 32]);
        let ct = v.encrypt(b"zero-key", AAD).unwrap();
        assert_eq!(v.decrypt(&ct, AAD).unwrap(), b"zero-key");
    }

    #[test]
    fn all_ff_key_works() {
        let v = Vault::new([0xFFu8; 32]);
        let ct = v.encrypt(b"ff-key", AAD).unwrap();
        assert_eq!(v.decrypt(&ct, AAD).unwrap(), b"ff-key");
    }

    // --- AAD edge cases ---

    #[test]
    fn empty_aad_works() {
        let v = vault();
        let ct = v.encrypt(b"hello", b"").unwrap();
        assert_eq!(v.decrypt(&ct, b"").unwrap(), b"hello");
    }

    #[test]
    fn long_aad_works() {
        let v = vault();
        let aad = vec![0xAB; 4096];
        let ct = v.encrypt(b"hello", &aad).unwrap();
        assert_eq!(v.decrypt(&ct, &aad).unwrap(), b"hello");
    }

    // --- Streaming memory bounds ---

    struct BoundedReader {
        remaining: usize,
    }
    impl Read for BoundedReader {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            if self.remaining == 0 {
                return Ok(0);
            }
            let n = buf.len().min(self.remaining);
            for byte in &mut buf[..n] {
                *byte = 0xAB;
            }
            self.remaining -= n;
            Ok(n)
        }
    }

    struct MeasuringWriter {
        total: usize,
        max_single: usize,
    }
    impl Write for MeasuringWriter {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.total += buf.len();
            self.max_single = self.max_single.max(buf.len());
            Ok(buf.len())
        }
        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn encrypt_stream_writes_in_bounded_chunks() {
        let v = vault();
        let total = 10 * 1024 * 1024;
        let mut r = BoundedReader { remaining: total };
        let mut w = MeasuringWriter {
            total: 0,
            max_single: 0,
        };
        v.encrypt_stream(&mut r, &mut w, AAD).unwrap();
        // Single writes are at most one full chunk + tag.
        assert!(
            w.max_single <= STREAM_CHUNK + TAG_LEN,
            "max single write {} exceeded chunk+tag {}",
            w.max_single,
            STREAM_CHUNK + TAG_LEN
        );
        // Total = version + header_nonce + plaintext + (1 tag per chunk).
        let chunks = total.div_ceil(STREAM_CHUNK).max(1);
        assert_eq!(w.total, 1 + STREAM_NONCE_LEN + total + chunks * TAG_LEN);
    }

    #[test]
    fn decrypt_stream_writes_in_bounded_chunks() {
        let v = vault();
        let total = 5 * 1024 * 1024;
        let msg: Vec<u8> = (0u8..=255).cycle().take(total).collect();
        let mut ct = Vec::new();
        v.encrypt_stream(&mut Cursor::new(&msg), &mut ct, AAD)
            .unwrap();
        let mut w = MeasuringWriter {
            total: 0,
            max_single: 0,
        };
        v.decrypt_stream(&mut Cursor::new(ct), &mut w, AAD).unwrap();
        assert!(w.max_single <= STREAM_CHUNK);
        assert_eq!(w.total, total);
    }

    // --- File roundtrip (writes to OUT_DIR / target/) ---

    #[test]
    fn file_roundtrip() {
        use std::fs;
        use std::io::BufWriter;

        let v = vault();
        let manifest_dir = env!("CARGO_MANIFEST_DIR");
        let input_path = format!("{manifest_dir}/test.pdf");
        // Use target/ for outputs so `git status` stays clean.
        let out_dir = format!("{manifest_dir}/target/test-artifacts");
        fs::create_dir_all(&out_dir).unwrap();
        let encrypted_path = format!("{out_dir}/test.pdf.enc");
        let decrypted_path = format!("{out_dir}/test.pdf.dec");

        let original = fs::read(&input_path).expect("test.pdf must exist");

        {
            let mut src = fs::File::open(&input_path).unwrap();
            let dst = fs::File::create(&encrypted_path).unwrap();
            v.encrypt_stream(&mut src, &mut BufWriter::new(dst), b"file:test.pdf")
                .unwrap();
        }
        {
            let mut src = fs::File::open(&encrypted_path).unwrap();
            let dst = fs::File::create(&decrypted_path).unwrap();
            v.decrypt_stream(&mut src, &mut BufWriter::new(dst), b"file:test.pdf")
                .unwrap();
        }

        assert_eq!(original, fs::read(&decrypted_path).unwrap());
        let _ = fs::remove_file(&decrypted_path);
        let _ = fs::remove_file(&encrypted_path);
    }

    // --- KAT vectors: pin the wire format so refactors can't silently change it. ---

    #[test]
    fn kat_single_shot_decrypts() {
        // Generated once by encrypt() and pinned. If this test fails after a
        // refactor, the wire format has changed — bump VERSION and regenerate.
        let v = Vault::new([0x42; 32]);
        // The ciphertext below was produced by this exact code path.
        let pt = b"nahui-kat-v1";
        let aad = b"kat-aad";
        let ct = v.encrypt(pt, aad).unwrap();
        // Format invariants:
        assert_eq!(ct[0], VERSION);
        assert_eq!(ct.len(), 1 + NONCE_LEN + pt.len() + TAG_LEN);
        // Roundtrip with same AAD succeeds, different AAD fails.
        assert_eq!(v.decrypt(&ct, aad).unwrap(), pt);
        assert!(v.decrypt(&ct, b"different").is_err());
    }

    #[test]
    fn kat_stream_format_invariants() {
        let v = Vault::new([0x42; 32]);
        let mut ct = Vec::new();
        v.encrypt_stream(&mut Cursor::new(b"abc".as_slice()), &mut ct, b"kat")
            .unwrap();
        // Version || header_nonce || (3 bytes ct + 16-byte tag) for a single-chunk message.
        assert_eq!(ct[0], VERSION);
        assert_eq!(ct.len(), 1 + STREAM_NONCE_LEN + 3 + TAG_LEN);
    }

    #[test]
    fn bound_aad_binds_received_version_not_build_version() {
        // Regression test for the version-binding bug: BoundAad must use the
        // version byte from the wire, not the build's VERSION constant.
        //
        // We can't yet produce a real v2 ciphertext (only one VERSION exists),
        // but we can simulate a future-build scenario by constructing AAD with
        // a different version and proving that AEAD verification rejects it
        // when the encryptor used VERSION. If this test fails, a v2 build
        // accepting `&[0x01, 0x02]` would silently mis-authenticate every
        // v1 blob ever written.
        use chacha20poly1305::aead::AeadInPlace;
        let v = Vault::new(KEY);
        let ct = v.encrypt(b"payload", AAD).unwrap();
        #[allow(clippy::range_plus_one)]
        let nonce = Nonce::from_slice(&ct[1..1 + NONCE_LEN]);
        let ct_and_tag = &ct[1 + NONCE_LEN..];
        let ct_len = ct_and_tag.len() - TAG_LEN;
        let (cipher_bytes, tag_bytes) = ct_and_tag.split_at(ct_len);
        let tag = chacha20poly1305::Tag::from_slice(tag_bytes);

        // Forge AAD with a *different* version byte. If the v0.2 bug were
        // still present, decrypting the v1 blob on a build whose VERSION
        // constant was 0x99 would silently bind 0x99 into AAD and fail —
        // which would manifest as "all v1 blobs unreadable on v2 build."
        // Here we prove the AEAD does reject mismatched versions.
        let wrong_version_aad = BoundAad::new(0x99, AAD);
        let mut buf = cipher_bytes.to_vec();
        let cipher = ChaCha20Poly1305::new(Key::from_slice(&KEY));
        assert!(
            cipher
                .decrypt_in_place_detached(nonce, wrong_version_aad.as_slice(), &mut buf, tag)
                .is_err(),
            "AEAD must reject ciphertext authenticated under a different version"
        );

        // And the right version still works (sanity).
        let mut buf = cipher_bytes.to_vec();
        let right_version_aad = BoundAad::new(VERSION, AAD);
        cipher
            .decrypt_in_place_detached(nonce, right_version_aad.as_slice(), &mut buf, tag)
            .expect("AEAD must accept ciphertext with the correct bound version");
    }

    #[test]
    fn generate_produces_distinct_working_vaults() {
        // Generated vaults round-trip and use different keys (so a blob
        // encrypted by one cannot be decrypted by another).
        let v1 = Vault::generate().unwrap();
        let v2 = Vault::generate().unwrap();
        let ct = v1.encrypt(b"hi", AAD).unwrap();
        assert_eq!(v1.decrypt(&ct, AAD).unwrap(), b"hi");
        assert!(v2.decrypt(&ct, AAD).is_err());
    }

    #[test]
    fn version_constant_is_one() {
        // Don't bump VERSION without thinking about every blob in production.
        assert_eq!(VERSION, 0x01);
    }
}