keres 0.7.1

A memory-safe, high-performance Rust library for modern file encryption and secure vaults.
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
//! The universal keres container format.
//!
//! Every encrypted object the library produces — single-file `.krs`
//! containers, vault entry blobs and vault manifests — uses this one
//! envelope. Future object kinds are new trailer payload types, never new
//! formats.
//!
//! # Wire layout
//!
//! ```text
//! b"KERES\0\0\0"     8-byte magic (never changes)
//! [u16 LE = 1]     envelope format version
//! [u8 kind]        key-derivation selector:
//!                    0 = content key is HKDF(master, object_salt[32])
//!                    1 = password-derived: argon2 salt[32] +
//!                        object salt[32] + KDF parameters[12]
//! [kind data]      kind-specific bytes (see above)
//! [len u32][ct||tag] …   chunk records (64 KiB plaintext each)
//! [00 00 00 00]    end-of-chunks marker
//! [len u32][ct||tag]     authenticated trailer record
//! ```
//!
//! All header bytes are bound to key derivation: flipping any of them
//! yields a wrong key and authentication fails. The payload type is bound
//! into every chunk and trailer AAD, so records cannot be transplanted
//! between containers of different types.

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

use serde::{Deserialize, Serialize};
use zeroize::Zeroizing;

use crate::crypto::{self, Key};
use crate::error::{Error, Result};
use crate::kdf::KdfParams;
use crate::padding::Padding;
use crate::stream;

/// Magic header shared by every Keres container.
///
/// The trailing NUL bytes are control bytes: they prevent the magic from
/// occurring in ordinary text and survive naive character-set mangling.
pub const MAGIC: &[u8; 8] = b"KERES\0\0\0";

/// Current envelope version for unpadded containers. Written into every
/// unpadded container; readers reject unknown values with
/// [`Error::UnsupportedVersion`].
pub const ENVELOPE_VERSION: u16 = 1;

/// Envelope version used by size-padded containers. It adds one authenticated
/// metadata record before the chunk section that carries the real plaintext
/// size, letting readers trim before yielding plaintext.
pub(crate) const ENVELOPE_VERSION_PADDED: u16 = 2;

pub(crate) const SALT_LEN: usize = crate::crypto::SALT_LEN;
const HKDF_INFO: &[u8] = b"keres-container-v1";
const KIND_HKDF: u8 = 0;
const KIND_PASSWORD: u8 = 1;

/// Reserved nonce for the optional padding metadata record.
const PADDING_NONCE: crypto::Nonce12 = [0xFEu8; 12];
/// AAD for the padding metadata record.
const PADDING_AAD: &[u8] = b"keres-container-v2/padding";
/// Upper bound on an accepted padding metadata record.
const MAX_PADDING_HEADER_LEN: usize = 4096;

/// What a container holds. Serialized into the authenticated trailer and
/// bound into chunk AAD, so records cannot be transplanted between payload
/// types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PayloadType {
    /// Encrypted file contents (standalone `.krs` or vault blob).
    File,
    /// Directory placeholder (vault only); carries no chunks.
    Directory,
    /// Vault index JSON (vault only).
    Manifest,
}

impl PayloadType {
    pub(crate) fn context(self, version: u16) -> Result<Vec<u8>> {
        let version = match version {
            ENVELOPE_VERSION => &b"v1"[..],
            ENVELOPE_VERSION_PADDED => &b"v2"[..],
            other => return Err(Error::UnsupportedVersion(u32::from(other))),
        };
        let mut c = b"keres-container-".to_vec();
        c.extend_from_slice(version);
        c.push(b'/');
        c.extend_from_slice(match self {
            PayloadType::File => &b"file"[..],
            PayloadType::Directory => &b"directory"[..],
            PayloadType::Manifest => &b"manifest"[..],
        });
        Ok(c)
    }
}

/// How a container's content key is derived.
#[derive(Debug, Clone)]
pub(crate) enum KeyDerivation {
    /// Content key = HKDF(master key, random per-object salt). Used inside
    /// vaults, where the master key is already unlocked in memory.
    Hkdf {
        /// Random HKDF salt; gives each object an independent subkey.
        object_salt: [u8; SALT_LEN],
    },
    /// Content key = HKDF(Argon2id(password, argon2_salt, params),
    /// object_salt). Used for standalone `.krs` files decryptable from a
    /// password alone.
    Password {
        /// Argon2id salt.
        argon_salt: [u8; SALT_LEN],
        /// Per-object HKDF salt.
        object_salt: [u8; SALT_LEN],
        /// Argon2id cost parameters, stored so defaults can evolve.
        params: KdfParams,
    },
}

impl KeyDerivation {
    fn kind(&self) -> u8 {
        match self {
            KeyDerivation::Hkdf { .. } => KIND_HKDF,
            KeyDerivation::Password { .. } => KIND_PASSWORD,
        }
    }

    fn header_len(&self) -> usize {
        MAGIC.len()
            + 2
            + 1
            + match self {
                KeyDerivation::Hkdf { .. } => SALT_LEN,
                KeyDerivation::Password { .. } => 2 * SALT_LEN + KdfParams::SERIALIZED_LEN,
            }
    }

    pub(crate) fn write_header<W: Write>(&self, w: &mut W, version: u16) -> Result<()> {
        let mut head = Vec::with_capacity(self.header_len());
        head.extend_from_slice(MAGIC);
        head.extend_from_slice(&version.to_le_bytes());
        head.push(self.kind());
        match self {
            KeyDerivation::Hkdf { object_salt } => head.extend_from_slice(object_salt),
            KeyDerivation::Password {
                argon_salt,
                object_salt,
                params,
            } => {
                let mut pbuf = [0u8; KdfParams::SERIALIZED_LEN];
                params.write_to(&mut pbuf);
                head.extend_from_slice(argon_salt);
                head.extend_from_slice(object_salt);
                head.extend_from_slice(&pbuf);
            }
        }
        w.write_all(&head)?;
        Ok(())
    }

    pub(crate) fn parse_header(head: &[u8]) -> Result<(Self, u16)> {
        if head.len() < MAGIC.len() + 3 || &head[..MAGIC.len()] != MAGIC {
            return Err(Error::IncompatibleFormat);
        }
        let version = u16::from_le_bytes([head[8], head[9]]);
        if version != ENVELOPE_VERSION && version != ENVELOPE_VERSION_PADDED {
            return Err(Error::UnsupportedVersion(u32::from(version)));
        }
        let body = &head[11..];
        let kd = match head[10] {
            KIND_HKDF => {
                if body.len() != SALT_LEN {
                    return Err(Error::InvalidHeader);
                }
                let mut object_salt = [0u8; SALT_LEN];
                object_salt.copy_from_slice(body);
                KeyDerivation::Hkdf { object_salt }
            }
            KIND_PASSWORD => {
                if body.len() != 2 * SALT_LEN + KdfParams::SERIALIZED_LEN {
                    return Err(Error::InvalidHeader);
                }
                let mut argon_salt = [0u8; SALT_LEN];
                argon_salt.copy_from_slice(&body[..SALT_LEN]);
                let mut object_salt = [0u8; SALT_LEN];
                object_salt.copy_from_slice(&body[SALT_LEN..2 * SALT_LEN]);
                let params = KdfParams::read_from(&body[2 * SALT_LEN..])?;
                KeyDerivation::Password {
                    argon_salt,
                    object_salt,
                    params,
                }
            }
            _ => return Err(Error::InvalidHeader),
        };
        Ok((kd, version))
    }

    pub(crate) fn content_key(
        &self,
        password: Option<&str>,
        master: Option<&Key>,
        identity: &[u8],
    ) -> Result<Key> {
        let mut info = Vec::with_capacity(HKDF_INFO.len() + 1 + identity.len());
        info.extend_from_slice(HKDF_INFO);
        info.extend_from_slice(b"/");
        info.extend_from_slice(identity);
        match self {
            KeyDerivation::Hkdf { object_salt } => {
                let m = master.ok_or(Error::InvalidHeader)?;
                Ok(crypto::derive_subkey(m, object_salt, &info))
            }
            KeyDerivation::Password {
                argon_salt,
                object_salt,
                params,
            } => {
                let pw = password.ok_or(Error::InvalidHeader)?;
                let kek = crypto::derive_key(pw.as_bytes(), argon_salt, *params)?;
                Ok(crypto::derive_subkey(&kek, object_salt, &info))
            }
        }
    }
}

/// Authenticated trailer describing the whole container.
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct Trailer {
    /// Payload type; also bound into all record AADs.
    pub typ: PayloadType,
    /// Original filename (single-file `.krs` only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Total plaintext length across all chunks.
    pub size: u64,
    /// Number of preceding chunk records.
    pub chunk_count: u32,
}

/// Authenticated metadata carried by size-padded containers before the chunk
/// section. The real size lets a reader trim padding before yielding any
/// plaintext; the trailer binds the padded length and chunk count.
///
/// The encoding is fixed-width (25 bytes) so the record length does not leak
/// the number of digits in the real size or which policy is in use.
#[derive(Debug)]
pub(crate) struct PaddingHeader {
    /// Real plaintext length.
    pub size: u64,
    /// Padded plaintext length actually present in the chunk section.
    pub padded_size: u64,
    /// Policy used to choose `padded_size`.
    pub padding: Padding,
}

/// Plaintext length of an encoded [`PaddingHeader`].
const PADDING_HEADER_LEN: usize = 8 + 8 + 1 + 8;

impl PaddingHeader {
    fn encode(&self) -> Vec<u8> {
        let (mode, fixed) = match self.padding {
            Padding::None => (0u8, 0u64),
            Padding::Adaptive => (1, 0),
            Padding::Fixed { size } => (2, size),
        };
        let mut out = Vec::with_capacity(PADDING_HEADER_LEN);
        out.extend_from_slice(&self.size.to_be_bytes());
        out.extend_from_slice(&self.padded_size.to_be_bytes());
        out.push(mode);
        out.extend_from_slice(&fixed.to_be_bytes());
        out
    }

    fn decode(bytes: &[u8]) -> Result<Self> {
        if bytes.len() != PADDING_HEADER_LEN {
            return Err(Error::MalformedPayload);
        }
        let size = u64::from_be_bytes(bytes[..8].try_into().expect("fixed slice"));
        let padded_size = u64::from_be_bytes(bytes[8..16].try_into().expect("fixed slice"));
        let mode = bytes[16];
        let fixed = u64::from_be_bytes(bytes[17..25].try_into().expect("fixed slice"));
        let padding = match (mode, fixed) {
            (0, 0) => Padding::None,
            (1, 0) => Padding::Adaptive,
            (2, size) => Padding::Fixed { size },
            _ => return Err(Error::MalformedPayload),
        };
        let header = Self {
            size,
            padded_size,
            padding,
        };
        header.validate()?;
        Ok(header)
    }

    fn validate(&self) -> Result<()> {
        if self.padded_size < self.size {
            return Err(Error::MalformedPayload);
        }
        let expected = self
            .padding
            .padded_len(self.size)
            .map_err(|_| Error::MalformedPayload)?;
        if expected != self.padded_size {
            return Err(Error::MalformedPayload);
        }
        Ok(())
    }
}

fn trailer_aad(context: &[u8]) -> Vec<u8> {
    let mut aad = Vec::with_capacity(context.len() + 8);
    aad.extend_from_slice(context);
    aad.extend_from_slice(b"/trailer");
    aad
}

/// A parsed container header plus the envelope version that determines the
/// record AAD domain and whether a padding metadata record follows.
pub(crate) struct ContainerHeader {
    pub kd: KeyDerivation,
    pub version: u16,
}

/// Reads a container header (magic, version, kind byte, kind data).
///
/// Shared by the whole-container reader and the public streaming reader, so
/// both accept exactly the same envelope.
pub(crate) fn read_header<R: Read>(inner: &mut R) -> Result<ContainerHeader> {
    let mut first = vec![0u8; MAGIC.len() + 3];
    inner
        .read_exact(&mut first)
        .map_err(|_| Error::InvalidHeader)?;
    if &first[..MAGIC.len()] != MAGIC {
        return Err(Error::IncompatibleFormat);
    }
    let extra = match first[10] {
        KIND_HKDF => SALT_LEN,
        KIND_PASSWORD => 2 * SALT_LEN + KdfParams::SERIALIZED_LEN,
        _ => return Err(Error::InvalidHeader),
    };
    let mut rest = vec![0u8; extra];
    inner
        .read_exact(&mut rest)
        .map_err(|_| Error::InvalidHeader)?;
    first.extend_from_slice(&rest);
    let (kd, version) = KeyDerivation::parse_header(&first)?;
    Ok(ContainerHeader { kd, version })
}

/// Writes the authenticated padding metadata record used by envelope v2.
fn write_padding_header<W: Write>(
    dst: &mut W,
    content_key: &Key,
    padding: Padding,
    size: u64,
    padded_size: u64,
) -> Result<()> {
    let header = PaddingHeader {
        size,
        padded_size,
        padding,
    };
    let mut payload = Zeroizing::new(header.encode());
    crypto::seal_in_place(&PADDING_NONCE, &mut payload, content_key, PADDING_AAD)?;
    dst.write_all(&(payload.len() as u32).to_le_bytes())?;
    dst.write_all(payload.as_slice())?;
    Ok(())
}

/// Reads and authenticates the padding metadata record used by envelope v2.
pub(crate) fn read_padding_header<R: Read>(
    src: &mut R,
    content_key: &Key,
) -> Result<PaddingHeader> {
    let mut rec = Zeroizing::new(stream::read_record(src, MAX_PADDING_HEADER_LEN)?);
    if rec.len() != PADDING_HEADER_LEN + crypto::TAG_LEN {
        return Err(Error::InvalidHeader);
    }
    crypto::open_in_place(&PADDING_NONCE, &mut rec, content_key, PADDING_AAD)?;
    PaddingHeader::decode(rec.as_slice())
}

/// Writes the authenticated trailer record, including the end-of-chunks
/// marker that precedes it.
pub(crate) fn write_trailer<W: Write>(
    dst: &mut W,
    content_key: &Key,
    typ: PayloadType,
    version: u16,
    name: Option<&str>,
    size: u64,
    chunk_count: u32,
) -> Result<()> {
    let context = typ.context(version)?;
    let mut payload = Zeroizing::new(
        serde_json::to_vec(&Trailer {
            typ,
            name: name.map(String::from),
            size,
            chunk_count,
        })
        .map_err(|_| Error::Encryption)?,
    );
    crypto::seal_in_place(
        &stream::TRAILER_NONCE,
        &mut payload,
        content_key,
        &trailer_aad(&context),
    )?;
    dst.write_all(&stream::CHUNKS_END_MARKER)?;
    dst.write_all(&(payload.len() as u32).to_le_bytes())?;
    dst.write_all(payload.as_slice())?;
    Ok(())
}

/// Reads and authenticates the trailer record and checks its payload type.
///
/// Size and chunk-count consistency with the observed chunks is left to the
/// caller, which knows how much plaintext it produced.
pub(crate) fn read_trailer<R: Read>(
    src: &mut R,
    content_key: &Key,
    expected: PayloadType,
    version: u16,
) -> Result<Trailer> {
    let context = expected.context(version)?;
    let mut rec = Zeroizing::new(stream::read_record(src, stream::MAX_TRAILER_LEN)?);
    crypto::open_in_place(
        &stream::TRAILER_NONCE,
        &mut rec,
        content_key,
        &trailer_aad(&context),
    )?;
    let trailer: Trailer =
        serde_json::from_slice(rec.as_slice()).map_err(|_| Error::MalformedPayload)?;
    if trailer.typ != expected {
        return Err(Error::Authentication);
    }
    Ok(trailer)
}

/// Rejects bytes after a container's trailer.
pub(crate) fn ensure_eof<R: Read>(inner: &mut R) -> Result<()> {
    let mut probe = [0u8; 1];
    match inner.read(&mut probe) {
        Ok(0) => Ok(()),
        Ok(_) => Err(Error::InvalidHeader),
        Err(e) => Err(e.into()),
    }
}

/// Generates the password-based key derivation used by standalone `.krs`
/// containers.
pub(crate) fn password_key_derivation() -> KeyDerivation {
    let mut argon_salt = [0u8; SALT_LEN];
    let mut object_salt = [0u8; SALT_LEN];
    crypto::fill_random(&mut argon_salt);
    crypto::fill_random(&mut object_salt);
    KeyDerivation::Password {
        argon_salt,
        object_salt,
        params: KdfParams::new(),
    }
}

/// Writes a complete container: header, chunks streamed from `src`, then
/// the authenticated trailer. Returns `(plaintext_bytes, chunk_count)`.
///
/// `identity` binds the container to its logical location (e.g. a vault
/// entry path); readers must pass the same value or authentication fails.
/// Pass `b""` for self-contained objects. `src: None` yields chunk-less
/// payloads (directory placeholders). Exactly one of `password`/`master`
/// is required, matching `kd`.
///
/// A non-[`Padding::None`] policy switches to envelope v2: the real size is
/// written in an authenticated prelude, the source is padded up to its bucket,
/// and `source_len` must supply the exact number of plaintext bytes `src`
/// will produce. Padding is only meaningful for [`PayloadType::File`].
#[allow(clippy::too_many_arguments)]
pub(crate) fn write_container<W: Write>(
    dst: &mut W,
    kd: &KeyDerivation,
    password: Option<&str>,
    master: Option<&Key>,
    typ: PayloadType,
    identity: &[u8],
    src: Option<&mut dyn Read>,
    trailer_name: Option<&str>,
    padding: Padding,
    source_len: Option<u64>,
) -> Result<(u64, u32)> {
    let content_key = kd.content_key(password, master, identity)?;

    if padding != Padding::None {
        if typ != PayloadType::File {
            return Err(Error::Operation(
                "size padding is only supported for file payloads".into(),
            ));
        }
        let source =
            src.ok_or_else(|| Error::Operation("size padding requires a non-empty source".into()))?;
        let source_len = source_len.ok_or_else(|| {
            Error::Operation("size padding requires a known source length".into())
        })?;
        let padded_len = padding.padded_len(source_len)?;
        let version = ENVELOPE_VERSION_PADDED;
        let context = typ.context(version)?;

        kd.write_header(dst, version)?;
        write_padding_header(dst, &content_key, padding, source_len, padded_len)?;
        let (total, count) = stream::write_chunks_padded(
            dst,
            source,
            &content_key,
            &context,
            source_len,
            padded_len,
        )?;
        // The v2 trailer binds the padded length and chunk count. The real
        // size lives in the fixed-width prelude, so the trailer's length does
        // not leak the number of digits in the plaintext size.
        write_trailer(
            dst,
            &content_key,
            typ,
            version,
            trailer_name,
            padded_len,
            count,
        )?;
        debug_assert_eq!(total, source_len);
        return Ok((total, count));
    }

    let version = ENVELOPE_VERSION;
    let context = typ.context(version)?;
    kd.write_header(dst, version)?;

    let (total, count) = match src {
        Some(r) => stream::write_chunks(dst, r, &content_key, &context)?,
        None => (0, 0),
    };

    write_trailer(dst, &content_key, typ, version, trailer_name, total, count)?;
    Ok((total, count))
}

/// Reads and authenticates a whole container, streaming plaintext chunks to
/// `sink`. Verifies the trailer against observed bytes and checks the
/// payload type matches `expected`. Returns the trailer.
///
/// Padded containers are trimmed to their authenticated real size before any
/// byte reaches `sink`; `trailer.size` is always the real plaintext length.
pub(crate) fn read_container<R: Read>(
    mut inner: R,
    password: Option<&str>,
    master: Option<&Key>,
    expected: PayloadType,
    identity: &[u8],
    mut sink: impl FnMut(&[u8]) -> Result<()>,
) -> Result<Trailer> {
    let header = read_header(&mut inner)?;
    let version = header.version;
    let content_key = header.kd.content_key(password, master, identity)?;
    let context = expected.context(version)?;

    let padding_header = if version == ENVELOPE_VERSION_PADDED {
        if expected != PayloadType::File {
            return Err(Error::InvalidHeader);
        }
        Some(read_padding_header(&mut inner, &content_key)?)
    } else {
        None
    };

    // `remaining` is the number of real bytes still owed to `sink`. It is
    // `None` for unpadded v1 containers, whose chunks are all real data.
    let mut remaining = padding_header.as_ref().map(|header| header.size);
    let (observed, count) =
        stream::read_chunks(
            &mut inner,
            &content_key,
            &context,
            |chunk| match remaining.as_mut() {
                Some(left) => {
                    let take = (*left).min(chunk.len() as u64) as usize;
                    if take > 0 {
                        sink(&chunk[..take])?;
                        *left -= take as u64;
                    }
                    Ok(())
                }
                None => sink(chunk),
            },
        )?;

    let mut trailer = read_trailer(&mut inner, &content_key, expected, version)?;
    match &padding_header {
        Some(header) => {
            // The v2 trailer binds the padded length (never the real size):
            // its record length must not reveal how many digits the real size
            // has. The authenticated prelude supplies the real size, and the
            // returned trailer is normalized to it so callers never see the
            // padding.
            if observed != header.padded_size || remaining != Some(0) {
                return Err(Error::Authentication);
            }
            if trailer.size != header.padded_size || trailer.chunk_count != count {
                return Err(Error::Authentication);
            }
            trailer.size = header.size;
        }
        None => {
            if trailer.size != observed || trailer.chunk_count != count {
                return Err(Error::Authentication);
            }
        }
    }

    ensure_eof(&mut inner)?;
    Ok(trailer)
}

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

    fn hkdf_kd() -> KeyDerivation {
        KeyDerivation::Hkdf {
            object_salt: [7u8; SALT_LEN],
        }
    }

    fn pw_kd() -> KeyDerivation {
        KeyDerivation::Password {
            argon_salt: [9u8; SALT_LEN],
            object_salt: [8u8; SALT_LEN],
            params: KdfParams {
                m_cost_kib: 8 * 1024,
                t_cost: 1,
                p_cost: 1,
            },
        }
    }

    fn seal(
        kd: &KeyDerivation,
        pw: Option<&str>,
        m: Option<&Key>,
        data: &[u8],
        typ: PayloadType,
    ) -> Vec<u8> {
        let mut out = Vec::new();
        let mut src = Cursor::new(data.to_vec());
        write_container(
            &mut out,
            kd,
            pw,
            m,
            typ,
            b"",
            Some(&mut src),
            None,
            Padding::None,
            None,
        )
        .unwrap();
        out
    }

    fn seal_padded(
        kd: &KeyDerivation,
        pw: Option<&str>,
        m: Option<&Key>,
        data: &[u8],
        padding: Padding,
    ) -> Vec<u8> {
        let mut out = Vec::new();
        let mut src = Cursor::new(data.to_vec());
        write_container(
            &mut out,
            kd,
            pw,
            m,
            PayloadType::File,
            b"",
            Some(&mut src),
            None,
            padding,
            Some(data.len() as u64),
        )
        .unwrap();
        out
    }

    fn unseal(blob: &[u8], pw: Option<&str>, m: Option<&Key>, typ: PayloadType) -> Trailer {
        let mut collected = Vec::new();
        let t = read_container(Cursor::new(blob.to_vec()), pw, m, typ, b"", |c| {
            collected.extend_from_slice(c);
            Ok(())
        })
        .unwrap();
        assert_eq!(collected.len(), t.size as usize);
        t
    }

    fn unseal_id(
        blob: &[u8],
        pw: Option<&str>,
        m: Option<&Key>,
        typ: PayloadType,
        identity: &[u8],
    ) -> Result<Trailer> {
        read_container(Cursor::new(blob.to_vec()), pw, m, typ, identity, |_| Ok(()))
    }

    #[test]
    fn roundtrip_both_kinds_and_types() {
        let master = Key::generate();
        let cases: [(KeyDerivation, Option<&str>, Option<&Key>, PayloadType); 3] = [
            (pw_kd(), Some("pw"), None, PayloadType::File),
            (hkdf_kd(), None, Some(&master), PayloadType::Manifest),
            (hkdf_kd(), None, Some(&master), PayloadType::Directory),
        ];
        for (kd, pw, m, typ) in cases {
            for data in [&b""[..], b"hello", &[42u8; 200_000][..]] {
                let blob = seal(&kd, pw, m, data, typ);
                let t = unseal(&blob, pw, m, typ);
                assert_eq!(t.typ, typ);
                assert_eq!(t.size, data.len() as u64);
            }
        }
    }

    #[test]
    fn wrong_payload_type_rejected() {
        let blob = seal(
            &hkdf_kd(),
            None,
            Some(&Key::generate()),
            b"data",
            PayloadType::File,
        );
        assert!(read_container(
            Cursor::new(blob),
            None,
            Some(&Key::generate()),
            PayloadType::Manifest,
            b"",
            |_| Ok(())
        )
        .is_err());
    }

    #[test]
    fn wrong_password_rejected() {
        let blob = seal(&pw_kd(), Some("pw"), None, b"data", PayloadType::File);
        assert!(matches!(
            read_container(
                Cursor::new(blob.clone()),
                Some("nope"),
                None,
                PayloadType::File,
                b"",
                |_| Ok(())
            ),
            Err(Error::Authentication)
        ));
    }

    #[test]
    fn tampered_byte_rejected_everywhere() {
        let blob = seal(
            &pw_kd(),
            Some("pw"),
            None,
            b"important data",
            PayloadType::File,
        );
        for pos in [0usize, 12, 40, blob.len() - 30, blob.len() - 1] {
            let mut corrupt = blob.clone();
            corrupt[pos] ^= 0x01;
            assert!(
                read_container(
                    Cursor::new(corrupt),
                    Some("pw"),
                    None,
                    PayloadType::File,
                    b"",
                    |_| Ok(())
                )
                .is_err(),
                "tamper at byte {pos} was not detected"
            );
        }
    }

    #[test]
    fn truncation_and_extension_rejected() {
        let blob = seal(&pw_kd(), Some("pw"), None, &[1u8; 500], PayloadType::File);
        assert!(read_container(
            Cursor::new(blob[..blob.len() - 1].to_vec()),
            Some("pw"),
            None,
            PayloadType::File,
            b"",
            |_| Ok(())
        )
        .is_err());
        let mut ext = blob.clone();
        ext.push(0);
        assert!(read_container(
            Cursor::new(ext),
            Some("pw"),
            None,
            PayloadType::File,
            b"",
            |_| Ok(())
        )
        .is_err());
    }

    #[test]
    fn non_keres_magics_rejected() {
        for magic in [
            b"KRYPTON\0".as_slice(),
            b"KRYPTON2\n",
            b"KRYPTON3\n",
            b"NOTKERES",
            b"\x89PNG\r\n\x1a\n",
        ] {
            let mut head = magic.to_vec();
            head.extend_from_slice(b"rest");
            let err = read_container(
                Cursor::new(head),
                None,
                None,
                PayloadType::File,
                b"",
                |_| Ok(()),
            )
            .unwrap_err();
            assert!(
                matches!(err, Error::IncompatibleFormat),
                "{magic:?} should be reported as incompatible, got {err:?}"
            );
        }
    }

    #[test]
    fn bad_version_rejected() {
        let mut blob = seal(
            &hkdf_kd(),
            None,
            Some(&Key::generate()),
            b"x",
            PayloadType::Manifest,
        );
        blob[8] = 99; // envelope version low byte
        assert!(matches!(
            read_container(
                Cursor::new(blob),
                None,
                Some(&Key::generate()),
                PayloadType::Manifest,
                b"",
                |_| Ok(())
            ),
            Err(Error::UnsupportedVersion(99))
        ));
    }

    #[test]
    fn wrong_identity_rejected() {
        let master = Key::generate();
        let blob = seal(&hkdf_kd(), None, Some(&master), b"data", PayloadType::File);
        // Whole-container transplant to a different logical location.
        assert!(unseal_id(
            &blob,
            None,
            Some(&master),
            PayloadType::File,
            b"other-entry"
        )
        .is_err());
        // Correct location still works and returns the trailer.
        assert!(unseal_id(&blob, None, Some(&master), PayloadType::File, b"").is_ok());
    }

    #[test]
    fn padded_containers_trim_to_the_real_size() {
        let master = Key::generate();
        let padding = Padding::Adaptive;
        for len in [0usize, 1, 4095, 4096, 4097, 70_000, 16 * 1024 * 1024 + 1] {
            let data = vec![0xABu8; len];
            let blob = seal_padded(&hkdf_kd(), None, Some(&master), &data, padding);

            let mut collected = Vec::new();
            let trailer = read_container(
                Cursor::new(blob),
                None,
                Some(&master),
                PayloadType::File,
                b"",
                |chunk| {
                    collected.extend_from_slice(chunk);
                    Ok(())
                },
            )
            .unwrap();

            assert_eq!(collected, data, "len {len} did not round-trip");
            assert_eq!(trailer.size, len as u64);
        }
    }

    #[test]
    fn padded_chunk_lengths_reveal_only_the_bucket() {
        let master = Key::generate();
        // 1 byte and 4095 bytes share the 4 KiB bucket, so their padded
        // containers must have exactly the same length.
        let tiny = seal_padded(&hkdf_kd(), None, Some(&master), b"x", Padding::Adaptive);
        let almost = seal_padded(
            &hkdf_kd(),
            None,
            Some(&master),
            &vec![0u8; 4095],
            Padding::Adaptive,
        );
        assert_eq!(tiny.len(), almost.len());

        // A payload one byte over the bucket moves to the next one.
        let over = seal_padded(
            &hkdf_kd(),
            None,
            Some(&master),
            &vec![0u8; 4097],
            Padding::Adaptive,
        );
        assert!(over.len() > tiny.len());
    }

    #[test]
    fn padding_requires_a_known_source_length() {
        let master = Key::generate();
        let mut src = Cursor::new(b"data".to_vec());
        let mut out = Vec::new();
        let err = write_container(
            &mut out,
            &hkdf_kd(),
            None,
            Some(&master),
            PayloadType::File,
            b"",
            Some(&mut src),
            None,
            Padding::Adaptive,
            None,
        )
        .unwrap_err();
        assert!(matches!(err, Error::Operation(_)));
    }

    #[test]
    fn padding_is_rejected_for_non_file_payloads() {
        let master = Key::generate();
        let mut src = Cursor::new(b"data".to_vec());
        let mut out = Vec::new();
        let err = write_container(
            &mut out,
            &hkdf_kd(),
            None,
            Some(&master),
            PayloadType::Manifest,
            b"",
            Some(&mut src),
            None,
            Padding::Adaptive,
            Some(4),
        )
        .unwrap_err();
        assert!(matches!(err, Error::Operation(_)));
    }

    #[test]
    fn tampered_padding_header_is_rejected() {
        let master = Key::generate();
        let blob = seal_padded(
            &hkdf_kd(),
            None,
            Some(&master),
            b"secret",
            Padding::Adaptive,
        );
        // The prelude sits directly after the 11-byte fixed header plus the
        // HKDF object salt; flip a byte in its authenticated payload.
        let mut corrupt = blob;
        let pos = 11 + SALT_LEN + 4 + 8;
        corrupt[pos] ^= 0x01;
        assert!(read_container(
            Cursor::new(corrupt),
            None,
            Some(&master),
            PayloadType::File,
            b"",
            |_| Ok(())
        )
        .is_err());
    }

    #[test]
    fn v1_containers_are_still_readable() {
        // `seal` writes envelope v1; the reader must accept both versions.
        let master = Key::generate();
        let blob = seal(
            &hkdf_kd(),
            None,
            Some(&master),
            b"legacy",
            PayloadType::File,
        );
        assert_eq!(u16::from_le_bytes([blob[8], blob[9]]), ENVELOPE_VERSION);
        let t = unseal(&blob, None, Some(&master), PayloadType::File);
        assert_eq!(t.size, 6);
    }
}