tzap-core 0.1.0

Core library for reading and writing encrypted, recoverable tzap archives
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
use aes_gcm::Aes256Gcm;
use aes_gcm_siv::Aes256GcmSiv;
use argon2::{Algorithm, Argon2, Params, Version};
use chacha20poly1305::XChaCha20Poly1305;
use hkdf::Hkdf;
use hmac::{Hmac, Mac};
use sha2::Sha256;
use unicode_normalization::UnicodeNormalization;
use zeroize::{Zeroize, ZeroizeOnDrop};

use aes_gcm_siv::aead::{Aead, KeyInit as AeadKeyInit, Payload};

use crate::format::{
    AeadAlgo, FormatError, KdfAlgo, MASTER_KEY_LEN, READER_MAX_ARGON2ID_M_COST_KIB,
    READER_MAX_ARGON2ID_PARALLELISM, READER_MAX_ARGON2ID_T_COST, SUBKEY_LEN,
};
use crate::padding::{depad_suffix_padding, suffix_pad_for_aead};

type HmacSha256 = Hmac<Sha256>;

const HKDF_SALT_DOMAIN: &[u8] = b"tzap-v1-subkeys";
const CRYPTO_HEADER_HMAC_DOMAIN: &[u8] = b"tzap-v1-crypto-header";
const MANIFEST_FOOTER_HMAC_DOMAIN: &[u8] = b"tzap-v1-manifest-footer";
const VOLUME_TRAILER_HMAC_DOMAIN: &[u8] = b"tzap-v1-volume-trailer";
const BOOTSTRAP_SIDECAR_HMAC_DOMAIN: &[u8] = b"tzap-v1-sidecar";

const RAW_KDF_PARAMS_LEN: usize = 2;
const ARGON2ID_FIXED_PARAMS_LEN: usize = 16;
const ARGON2ID_MIN_SALT_LEN: u16 = 8;
const ARGON2ID_MAX_SALT_LEN: u16 = 64;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KdfParams {
    Raw,
    Argon2id {
        t_cost: u32,
        m_cost_kib: u32,
        parallelism: u32,
        salt: Vec<u8>,
    },
}

impl KdfParams {
    pub fn parse(algo: KdfAlgo, bytes: &[u8]) -> Result<(Self, usize), FormatError> {
        match algo {
            KdfAlgo::Raw => parse_raw_kdf_params(bytes),
            KdfAlgo::Argon2id => parse_argon2id_kdf_params(bytes),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
pub struct MasterKey(pub [u8; MASTER_KEY_LEN]);

impl MasterKey {
    pub fn from_raw_key(raw_key: &[u8]) -> Result<Self, FormatError> {
        if raw_key.len() != MASTER_KEY_LEN {
            return Err(FormatError::InvalidRawMasterKeyLength);
        }
        let mut key = [0u8; MASTER_KEY_LEN];
        key.copy_from_slice(raw_key);
        Ok(Self(key))
    }

    pub fn derive_from_passphrase(
        params: &KdfParams,
        passphrase: &str,
    ) -> Result<Self, FormatError> {
        let KdfParams::Argon2id {
            t_cost,
            m_cost_kib,
            parallelism,
            salt,
        } = params
        else {
            return Err(FormatError::KeyMaterialMismatch);
        };

        let salt_length = u16::try_from(salt.len()).map_err(|_| {
            FormatError::InvalidKdfParams("argon2id salt length must be 8..64 bytes")
        })?;
        validate_argon2id_bounds(*t_cost, *m_cost_kib, *parallelism, salt_length)?;
        let params = Params::new(*m_cost_kib, *t_cost, *parallelism, Some(MASTER_KEY_LEN))
            .map_err(|_| FormatError::InvalidKdfParams("argon2 params rejected"))?;
        let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
        let mut output = [0u8; MASTER_KEY_LEN];
        let mut passphrase_bytes = normalize_passphrase_nfc(passphrase);
        let result = argon2.hash_password_into(&passphrase_bytes, salt, &mut output);
        passphrase_bytes.zeroize();
        result.map_err(|_| FormatError::Argon2idFailure)?;
        Ok(Self(output))
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
pub struct Subkeys {
    pub enc_key: [u8; SUBKEY_LEN],
    pub mac_key: [u8; SUBKEY_LEN],
    pub nonce_seed: [u8; SUBKEY_LEN],
    pub index_root_key: [u8; SUBKEY_LEN],
    pub index_shard_key: [u8; SUBKEY_LEN],
    pub dictionary_key: [u8; SUBKEY_LEN],
    pub dir_hint_key: [u8; SUBKEY_LEN],
    pub index_nonce_seed: [u8; SUBKEY_LEN],
}

impl Subkeys {
    pub fn derive(
        master_key: &MasterKey,
        archive_uuid: &[u8; 16],
        session_id: &[u8; 16],
    ) -> Result<Self, FormatError> {
        let mut salt = Vec::with_capacity(HKDF_SALT_DOMAIN.len() + 32);
        salt.extend_from_slice(HKDF_SALT_DOMAIN);
        salt.extend_from_slice(archive_uuid);
        salt.extend_from_slice(session_id);
        let hk = Hkdf::<Sha256>::new(Some(&salt), &master_key.0);
        salt.zeroize();

        Ok(Self {
            enc_key: expand_subkey(&hk, b"tzap-v1-enc")?,
            mac_key: expand_subkey(&hk, b"tzap-v1-mac")?,
            nonce_seed: expand_subkey(&hk, b"tzap-v1-nonce")?,
            index_root_key: expand_subkey(&hk, b"tzap-v1-idxroot")?,
            index_shard_key: expand_subkey(&hk, b"tzap-v1-idxshard")?,
            dictionary_key: expand_subkey(&hk, b"tzap-v1-dict")?,
            dir_hint_key: expand_subkey(&hk, b"tzap-v1-dirhint")?,
            index_nonce_seed: expand_subkey(&hk, b"tzap-v1-idxnonce")?,
        })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HmacDomain {
    CryptoHeader,
    ManifestFooter,
    VolumeTrailer,
    BootstrapSidecar,
}

impl HmacDomain {
    pub fn structure_name(self) -> &'static str {
        match self {
            Self::CryptoHeader => "CryptoHeader",
            Self::ManifestFooter => "ManifestFooter",
            Self::VolumeTrailer => "VolumeTrailer",
            Self::BootstrapSidecar => "BootstrapSidecarHeader",
        }
    }

    fn domain_bytes(self) -> &'static [u8] {
        match self {
            Self::CryptoHeader => CRYPTO_HEADER_HMAC_DOMAIN,
            Self::ManifestFooter => MANIFEST_FOOTER_HMAC_DOMAIN,
            Self::VolumeTrailer => VOLUME_TRAILER_HMAC_DOMAIN,
            Self::BootstrapSidecar => BOOTSTRAP_SIDECAR_HMAC_DOMAIN,
        }
    }
}

pub fn compute_hmac(
    domain: HmacDomain,
    mac_key: &[u8; SUBKEY_LEN],
    archive_uuid: &[u8; 16],
    session_id: &[u8; 16],
    covered_bytes: &[u8],
) -> [u8; SUBKEY_LEN] {
    let mut mac =
        <HmacSha256 as Mac>::new_from_slice(mac_key).expect("HMAC accepts any key length");
    mac.update(domain.domain_bytes());
    mac.update(archive_uuid);
    mac.update(session_id);
    mac.update(covered_bytes);
    let digest = mac.finalize().into_bytes();
    let mut output = [0u8; SUBKEY_LEN];
    output.copy_from_slice(&digest);
    output
}

pub fn verify_hmac(
    domain: HmacDomain,
    mac_key: &[u8; SUBKEY_LEN],
    archive_uuid: &[u8; 16],
    session_id: &[u8; 16],
    covered_bytes: &[u8],
    expected_hmac: &[u8],
) -> Result<(), FormatError> {
    let mut mac =
        <HmacSha256 as Mac>::new_from_slice(mac_key).expect("HMAC accepts any key length");
    mac.update(domain.domain_bytes());
    mac.update(archive_uuid);
    mac.update(session_id);
    mac.update(covered_bytes);
    mac.verify_slice(expected_hmac)
        .map_err(|_| FormatError::HmacMismatch {
            structure: domain.structure_name(),
        })
}

pub fn normalize_passphrase_nfc(passphrase: &str) -> Vec<u8> {
    passphrase.nfc().collect::<String>().into_bytes()
}

pub fn derive_nonce(
    seed: &[u8; SUBKEY_LEN],
    domain: &[u8],
    archive_uuid: &[u8; 16],
    session_id: &[u8; 16],
    counter: u64,
    len: usize,
) -> Result<Vec<u8>, FormatError> {
    let info = nonce_or_aad_info(b"tzap-v1-nonce", domain, archive_uuid, session_id, counter)?;
    let hk = Hkdf::<Sha256>::from_prk(seed)
        .map_err(|_| FormatError::InvalidKdfParams("bad nonce seed"))?;
    let mut nonce = vec![0u8; len];
    hk.expand(&info, &mut nonce)
        .map_err(|_| FormatError::HkdfExpandFailure)?;
    Ok(nonce)
}

pub fn build_aad(
    domain: &[u8],
    archive_uuid: &[u8; 16],
    session_id: &[u8; 16],
    counter: u64,
) -> Result<Vec<u8>, FormatError> {
    nonce_or_aad_info(b"tzap-v1-aad", domain, archive_uuid, session_id, counter)
}

pub fn aead_encrypt(
    algo: AeadAlgo,
    key: &[u8; SUBKEY_LEN],
    nonce: &[u8],
    aad: &[u8],
    plaintext: &[u8],
) -> Result<Vec<u8>, FormatError> {
    validate_nonce_len(algo, nonce)?;
    match algo {
        AeadAlgo::AesGcmSiv256 => {
            let cipher =
                Aes256GcmSiv::new_from_slice(key).map_err(|_| FormatError::InvalidAeadKeyLength)?;
            cipher
                .encrypt(
                    aes_gcm_siv::Nonce::from_slice(nonce),
                    Payload {
                        msg: plaintext,
                        aad,
                    },
                )
                .map_err(|_| FormatError::AeadFailure)
        }
        AeadAlgo::XChaCha20Poly1305 => {
            let cipher = XChaCha20Poly1305::new_from_slice(key)
                .map_err(|_| FormatError::InvalidAeadKeyLength)?;
            cipher
                .encrypt(
                    chacha20poly1305::XNonce::from_slice(nonce),
                    Payload {
                        msg: plaintext,
                        aad,
                    },
                )
                .map_err(|_| FormatError::AeadFailure)
        }
        AeadAlgo::AesGcm256 => {
            let cipher =
                Aes256Gcm::new_from_slice(key).map_err(|_| FormatError::InvalidAeadKeyLength)?;
            cipher
                .encrypt(
                    aes_gcm::Nonce::from_slice(nonce),
                    Payload {
                        msg: plaintext,
                        aad,
                    },
                )
                .map_err(|_| FormatError::AeadFailure)
        }
    }
}

pub fn aead_decrypt(
    algo: AeadAlgo,
    key: &[u8; SUBKEY_LEN],
    nonce: &[u8],
    aad: &[u8],
    ciphertext_and_tag: &[u8],
) -> Result<Vec<u8>, FormatError> {
    validate_nonce_len(algo, nonce)?;
    match algo {
        AeadAlgo::AesGcmSiv256 => {
            let cipher =
                Aes256GcmSiv::new_from_slice(key).map_err(|_| FormatError::InvalidAeadKeyLength)?;
            cipher
                .decrypt(
                    aes_gcm_siv::Nonce::from_slice(nonce),
                    Payload {
                        msg: ciphertext_and_tag,
                        aad,
                    },
                )
                .map_err(|_| FormatError::AeadFailure)
        }
        AeadAlgo::XChaCha20Poly1305 => {
            let cipher = XChaCha20Poly1305::new_from_slice(key)
                .map_err(|_| FormatError::InvalidAeadKeyLength)?;
            cipher
                .decrypt(
                    chacha20poly1305::XNonce::from_slice(nonce),
                    Payload {
                        msg: ciphertext_and_tag,
                        aad,
                    },
                )
                .map_err(|_| FormatError::AeadFailure)
        }
        AeadAlgo::AesGcm256 => {
            let cipher =
                Aes256Gcm::new_from_slice(key).map_err(|_| FormatError::InvalidAeadKeyLength)?;
            cipher
                .decrypt(
                    aes_gcm::Nonce::from_slice(nonce),
                    Payload {
                        msg: ciphertext_and_tag,
                        aad,
                    },
                )
                .map_err(|_| FormatError::AeadFailure)
        }
    }
}

pub fn encrypt_padded_aead_object(
    algo: AeadAlgo,
    key: &[u8; SUBKEY_LEN],
    nonce_seed: &[u8; SUBKEY_LEN],
    domain: &[u8],
    archive_uuid: &[u8; 16],
    session_id: &[u8; 16],
    counter: u64,
    block_size: usize,
    payload: &[u8],
) -> Result<Vec<u8>, FormatError> {
    let nonce = derive_nonce(
        nonce_seed,
        domain,
        archive_uuid,
        session_id,
        counter,
        algo.nonce_len(),
    )?;
    let aad = build_aad(domain, archive_uuid, session_id, counter)?;
    let padded = suffix_pad_for_aead(payload, algo.tag_len(), block_size)?;
    aead_encrypt(algo, key, &nonce, &aad, &padded)
}

pub fn decrypt_padded_aead_object(
    algo: AeadAlgo,
    key: &[u8; SUBKEY_LEN],
    nonce_seed: &[u8; SUBKEY_LEN],
    domain: &[u8],
    archive_uuid: &[u8; 16],
    session_id: &[u8; 16],
    counter: u64,
    ciphertext_and_tag: &[u8],
) -> Result<Vec<u8>, FormatError> {
    let nonce = derive_nonce(
        nonce_seed,
        domain,
        archive_uuid,
        session_id,
        counter,
        algo.nonce_len(),
    )?;
    let aad = build_aad(domain, archive_uuid, session_id, counter)?;
    let padded = aead_decrypt(algo, key, &nonce, &aad, ciphertext_and_tag)?;
    Ok(depad_suffix_padding(&padded)?.to_vec())
}

fn parse_raw_kdf_params(bytes: &[u8]) -> Result<(KdfParams, usize), FormatError> {
    if bytes.len() < RAW_KDF_PARAMS_LEN {
        return Err(FormatError::TruncatedKdfParams);
    }
    let algo_tag = read_u16(bytes, 0)?;
    if algo_tag != KdfAlgo::Raw as u16 {
        return Err(FormatError::KdfAlgoTagMismatch {
            expected: KdfAlgo::Raw as u16,
            actual: algo_tag,
        });
    }
    Ok((KdfParams::Raw, RAW_KDF_PARAMS_LEN))
}

fn parse_argon2id_kdf_params(bytes: &[u8]) -> Result<(KdfParams, usize), FormatError> {
    if bytes.len() < ARGON2ID_FIXED_PARAMS_LEN {
        return Err(FormatError::TruncatedKdfParams);
    }
    let algo_tag = read_u16(bytes, 0)?;
    if algo_tag != KdfAlgo::Argon2id as u16 {
        return Err(FormatError::KdfAlgoTagMismatch {
            expected: KdfAlgo::Argon2id as u16,
            actual: algo_tag,
        });
    }
    let t_cost = read_u32(bytes, 2)?;
    let m_cost_kib = read_u32(bytes, 6)?;
    let parallelism = read_u32(bytes, 10)?;
    let salt_length = read_u16(bytes, 14)?;
    if salt_length < ARGON2ID_MIN_SALT_LEN || salt_length > ARGON2ID_MAX_SALT_LEN {
        return Err(FormatError::InvalidKdfParams(
            "argon2id salt length must be 8..64 bytes",
        ));
    }
    if t_cost == 0 {
        return Err(FormatError::InvalidKdfParams(
            "argon2id t_cost must be non-zero",
        ));
    }
    if parallelism == 0 {
        return Err(FormatError::InvalidKdfParams(
            "argon2id parallelism must be non-zero",
        ));
    }
    validate_argon2id_bounds(t_cost, m_cost_kib, parallelism, salt_length)?;

    let total_len = ARGON2ID_FIXED_PARAMS_LEN + salt_length as usize;
    if bytes.len() < total_len {
        return Err(FormatError::TruncatedKdfParams);
    }
    Ok((
        KdfParams::Argon2id {
            t_cost,
            m_cost_kib,
            parallelism,
            salt: bytes[ARGON2ID_FIXED_PARAMS_LEN..total_len].to_vec(),
        },
        total_len,
    ))
}

fn validate_argon2id_bounds(
    t_cost: u32,
    m_cost_kib: u32,
    parallelism: u32,
    salt_length: u16,
) -> Result<(), FormatError> {
    if salt_length < ARGON2ID_MIN_SALT_LEN || salt_length > ARGON2ID_MAX_SALT_LEN {
        return Err(FormatError::InvalidKdfParams(
            "argon2id salt length must be 8..64 bytes",
        ));
    }
    if t_cost == 0 {
        return Err(FormatError::InvalidKdfParams(
            "argon2id t_cost must be non-zero",
        ));
    }
    if t_cost > READER_MAX_ARGON2ID_T_COST {
        return Err(FormatError::ReaderResourceLimitExceeded {
            field: "argon2id t_cost",
            cap: READER_MAX_ARGON2ID_T_COST as u64,
            actual: t_cost as u64,
        });
    }
    if parallelism == 0 {
        return Err(FormatError::InvalidKdfParams(
            "argon2id parallelism must be non-zero",
        ));
    }
    if parallelism > READER_MAX_ARGON2ID_PARALLELISM {
        return Err(FormatError::ReaderResourceLimitExceeded {
            field: "argon2id parallelism",
            cap: READER_MAX_ARGON2ID_PARALLELISM as u64,
            actual: parallelism as u64,
        });
    }
    if m_cost_kib > READER_MAX_ARGON2ID_M_COST_KIB {
        return Err(FormatError::ReaderResourceLimitExceeded {
            field: "argon2id m_cost_kib",
            cap: READER_MAX_ARGON2ID_M_COST_KIB as u64,
            actual: m_cost_kib as u64,
        });
    }
    let min_memory = parallelism
        .checked_mul(8)
        .ok_or(FormatError::InvalidKdfParams(
            "argon2id memory requirement overflow",
        ))?;
    if m_cost_kib < min_memory {
        return Err(FormatError::InvalidKdfParams(
            "argon2id memory must be at least 8 KiB per lane",
        ));
    }
    Ok(())
}

fn expand_subkey(hk: &Hkdf<Sha256>, info: &[u8]) -> Result<[u8; SUBKEY_LEN], FormatError> {
    let mut output = [0u8; SUBKEY_LEN];
    hk.expand(info, &mut output)
        .map_err(|_| FormatError::HkdfExpandFailure)?;
    Ok(output)
}

fn nonce_or_aad_info(
    prefix: &[u8],
    domain: &[u8],
    archive_uuid: &[u8; 16],
    session_id: &[u8; 16],
    counter: u64,
) -> Result<Vec<u8>, FormatError> {
    let domain_len = u16::try_from(domain.len()).map_err(|_| FormatError::DomainTooLong)?;
    let mut info = Vec::with_capacity(prefix.len() + 2 + domain.len() + 16 + 16 + 8);
    info.extend_from_slice(prefix);
    info.extend_from_slice(&domain_len.to_le_bytes());
    info.extend_from_slice(domain);
    info.extend_from_slice(archive_uuid);
    info.extend_from_slice(session_id);
    info.extend_from_slice(&counter.to_le_bytes());
    Ok(info)
}

fn validate_nonce_len(algo: AeadAlgo, nonce: &[u8]) -> Result<(), FormatError> {
    let expected = algo.nonce_len();
    if nonce.len() != expected {
        return Err(FormatError::InvalidNonceLength {
            algo,
            expected,
            actual: nonce.len(),
        });
    }
    Ok(())
}

fn read_u16(bytes: &[u8], offset: usize) -> Result<u16, FormatError> {
    let array: [u8; 2] = bytes
        .get(offset..offset + 2)
        .ok_or(FormatError::InvalidLength {
            structure: "u16",
            expected: offset + 2,
            actual: bytes.len(),
        })?
        .try_into()
        .expect("slice length checked");
    Ok(u16::from_le_bytes(array))
}

fn read_u32(bytes: &[u8], offset: usize) -> Result<u32, FormatError> {
    let array: [u8; 4] = bytes
        .get(offset..offset + 4)
        .ok_or(FormatError::InvalidLength {
            structure: "u32",
            expected: offset + 4,
            actual: bytes.len(),
        })?
        .try_into()
        .expect("slice length checked");
    Ok(u32::from_le_bytes(array))
}

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

    fn uuid() -> [u8; 16] {
        [0x11; 16]
    }

    fn session() -> [u8; 16] {
        [0x22; 16]
    }

    #[test]
    fn parses_raw_kdf_params() {
        let (params, consumed) = KdfParams::parse(KdfAlgo::Raw, &0u16.to_le_bytes()).unwrap();
        assert_eq!(params, KdfParams::Raw);
        assert_eq!(consumed, 2);
    }

    #[test]
    fn parses_argon2id_kdf_params() {
        let mut bytes = Vec::new();
        bytes.extend_from_slice(&(KdfAlgo::Argon2id as u16).to_le_bytes());
        bytes.extend_from_slice(&1u32.to_le_bytes());
        bytes.extend_from_slice(&8u32.to_le_bytes());
        bytes.extend_from_slice(&1u32.to_le_bytes());
        bytes.extend_from_slice(&8u16.to_le_bytes());
        bytes.extend_from_slice(b"12345678");

        let (params, consumed) = KdfParams::parse(KdfAlgo::Argon2id, &bytes).unwrap();
        assert_eq!(consumed, 24);
        assert_eq!(
            params,
            KdfParams::Argon2id {
                t_cost: 1,
                m_cost_kib: 8,
                parallelism: 1,
                salt: b"12345678".to_vec()
            }
        );
    }

    #[test]
    fn rejects_argon2id_params_above_reader_caps() {
        let mut bytes = Vec::new();
        bytes.extend_from_slice(&(KdfAlgo::Argon2id as u16).to_le_bytes());
        bytes.extend_from_slice(&(READER_MAX_ARGON2ID_T_COST + 1).to_le_bytes());
        bytes.extend_from_slice(&8u32.to_le_bytes());
        bytes.extend_from_slice(&1u32.to_le_bytes());
        bytes.extend_from_slice(&8u16.to_le_bytes());
        bytes.extend_from_slice(b"12345678");

        assert_eq!(
            KdfParams::parse(KdfAlgo::Argon2id, &bytes).unwrap_err(),
            FormatError::ReaderResourceLimitExceeded {
                field: "argon2id t_cost",
                cap: READER_MAX_ARGON2ID_T_COST as u64,
                actual: (READER_MAX_ARGON2ID_T_COST + 1) as u64,
            }
        );

        let err = MasterKey::derive_from_passphrase(
            &KdfParams::Argon2id {
                t_cost: 1,
                m_cost_kib: READER_MAX_ARGON2ID_M_COST_KIB + 1,
                parallelism: 1,
                salt: b"12345678".to_vec(),
            },
            "passphrase",
        )
        .unwrap_err();
        assert_eq!(
            err,
            FormatError::ReaderResourceLimitExceeded {
                field: "argon2id m_cost_kib",
                cap: READER_MAX_ARGON2ID_M_COST_KIB as u64,
                actual: (READER_MAX_ARGON2ID_M_COST_KIB + 1) as u64,
            }
        );
    }

    #[test]
    fn rejects_kdf_algo_tag_mismatch() {
        assert_eq!(
            KdfParams::parse(KdfAlgo::Raw, &(KdfAlgo::Argon2id as u16).to_le_bytes()).unwrap_err(),
            FormatError::KdfAlgoTagMismatch {
                expected: 0,
                actual: 1
            }
        );
    }

    #[test]
    fn passphrase_normalization_preserves_archive_semantics() {
        assert_eq!(normalize_passphrase_nfc("e\u{301}\n\0"), "é\n\0".as_bytes());
    }

    #[test]
    fn derives_argon2id_master_key_from_nfc_passphrase() {
        let params = KdfParams::Argon2id {
            t_cost: 1,
            m_cost_kib: 8,
            parallelism: 1,
            salt: b"12345678".to_vec(),
        };
        let one = MasterKey::derive_from_passphrase(&params, "e\u{301}").unwrap();
        let two = MasterKey::derive_from_passphrase(&params, "é").unwrap();
        assert_eq!(one.0, two.0);
        assert_ne!(one.0, [0u8; MASTER_KEY_LEN]);
    }

    #[test]
    fn derives_stable_distinct_subkeys() {
        let master = MasterKey::from_raw_key(&[0x33; MASTER_KEY_LEN]).unwrap();
        let subkeys = Subkeys::derive(&master, &uuid(), &session()).unwrap();
        assert_ne!(subkeys.enc_key, subkeys.mac_key);
        assert_ne!(subkeys.index_root_key, subkeys.index_shard_key);

        let repeat = Subkeys::derive(&master, &uuid(), &session()).unwrap();
        assert_eq!(subkeys, repeat);
    }

    #[test]
    fn computes_and_verifies_hmac_domains() {
        let key = [0x44; SUBKEY_LEN];
        let covered = b"covered bytes";
        let tag = compute_hmac(HmacDomain::CryptoHeader, &key, &uuid(), &session(), covered);
        verify_hmac(
            HmacDomain::CryptoHeader,
            &key,
            &uuid(),
            &session(),
            covered,
            &tag,
        )
        .unwrap();

        assert_eq!(
            verify_hmac(
                HmacDomain::ManifestFooter,
                &key,
                &uuid(),
                &session(),
                covered,
                &tag,
            )
            .unwrap_err(),
            FormatError::HmacMismatch {
                structure: "ManifestFooter"
            }
        );
    }

    #[test]
    fn derives_nonce_and_aad_with_domain_separation() {
        let seed = [0x55; SUBKEY_LEN];
        let nonce = derive_nonce(&seed, b"envelope", &uuid(), &session(), 7, 12).unwrap();
        let other = derive_nonce(&seed, b"idxroot", &uuid(), &session(), 7, 12).unwrap();
        assert_eq!(nonce.len(), 12);
        assert_ne!(nonce, other);

        let aad = build_aad(b"envelope", &uuid(), &session(), 7).unwrap();
        assert!(aad.starts_with(b"tzap-v1-aad"));
        assert_ne!(aad, nonce);
    }

    #[test]
    fn aead_round_trips_all_registered_algorithms() {
        for algo in [
            AeadAlgo::AesGcmSiv256,
            AeadAlgo::XChaCha20Poly1305,
            AeadAlgo::AesGcm256,
        ] {
            let key = [0x66; SUBKEY_LEN];
            let nonce = derive_nonce(
                &[0x77; SUBKEY_LEN],
                b"envelope",
                &uuid(),
                &session(),
                0,
                algo.nonce_len(),
            )
            .unwrap();
            let aad = build_aad(b"envelope", &uuid(), &session(), 0).unwrap();
            let ciphertext = aead_encrypt(algo, &key, &nonce, &aad, b"plaintext").unwrap();
            assert_ne!(ciphertext, b"plaintext");
            let plaintext = aead_decrypt(algo, &key, &nonce, &aad, &ciphertext).unwrap();
            assert_eq!(plaintext, b"plaintext");

            let mut tampered = ciphertext;
            tampered[0] ^= 1;
            assert_eq!(
                aead_decrypt(algo, &key, &nonce, &aad, &tampered).unwrap_err(),
                FormatError::AeadFailure
            );
        }
    }

    #[test]
    fn aead_rejects_wrong_nonce_length() {
        assert_eq!(
            aead_encrypt(AeadAlgo::AesGcmSiv256, &[0; SUBKEY_LEN], &[0; 11], b"", b"").unwrap_err(),
            FormatError::InvalidNonceLength {
                algo: AeadAlgo::AesGcmSiv256,
                expected: 12,
                actual: 11
            }
        );
    }

    #[test]
    fn padded_aead_object_round_trips_with_derived_nonce_and_aad() {
        let key = [0x66; SUBKEY_LEN];
        let nonce_seed = [0x77; SUBKEY_LEN];
        let ciphertext = encrypt_padded_aead_object(
            AeadAlgo::AesGcmSiv256,
            &key,
            &nonce_seed,
            b"envelope",
            &uuid(),
            &session(),
            3,
            4096,
            b"packed frames",
        )
        .unwrap();
        assert_eq!(ciphertext.len() % 4096, 0);

        let plaintext = decrypt_padded_aead_object(
            AeadAlgo::AesGcmSiv256,
            &key,
            &nonce_seed,
            b"envelope",
            &uuid(),
            &session(),
            3,
            &ciphertext,
        )
        .unwrap();
        assert_eq!(plaintext, b"packed frames");

        assert_eq!(
            decrypt_padded_aead_object(
                AeadAlgo::AesGcmSiv256,
                &key,
                &nonce_seed,
                b"idxroot",
                &uuid(),
                &session(),
                3,
                &ciphertext,
            )
            .unwrap_err(),
            FormatError::AeadFailure
        );
    }
}