hide-keyring 0.10.0

Passphrase-sealed key files (Argon2id) and armored public keys for HIDE. Experimental, unaudited.
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
//! Password-protected storage for HIDE secret keys.
//!
//! `hide-crypto` deliberately knows nothing about files or passwords. This crate
//! adds the at-rest layer: Argon2id stretches a passphrase into a wrapping key,
//! which seals the 32-byte recipient seed with ChaCha20-Poly1305.
//!
//! This protects a key file at rest. It is not a hardware-backed vault: while a
//! key is in use it lives in ordinary process memory.

use argon2::{Algorithm, Argon2, Params, Version};
use base64::{Engine, engine::general_purpose::STANDARD};
use chacha20poly1305::{
    AeadCore, ChaCha20Poly1305, KeyInit,
    aead::{Aead, Payload},
};
use hide_crypto::{CryptoError, RecipientSecret};
use hkdf::Hkdf;
use sha2::Sha256;
use thiserror::Error;
use zeroize::Zeroizing;

pub mod epoch_store;

pub use epoch_store::EpochStore;

const MAGIC: &[u8] = b"HIDE-KEY";
/// Version 1 sealed a bare recipient seed. Version 2 adds a purpose byte, so a
/// signing key and an encryption key are no longer byte-indistinguishable.
const FORMAT_VERSION: u8 = 2;
const LEGACY_VERSION: u8 = 1;
const SALT_LEN: usize = 16;
const NONCE_LEN: usize = 12;
const SEED_LEN: usize = 32;
const TAG_LEN: usize = 16;
const LEGACY_HEADER_LEN: usize = 8 + 1 + 1 + 4 + 4 + SALT_LEN + NONCE_LEN;
const HEADER_LEN: usize = LEGACY_HEADER_LEN + 1;
const SEALED_LEN: usize = HEADER_LEN + SEED_LEN + TAG_LEN;
const LEGACY_SEALED_LEN: usize = LEGACY_HEADER_LEN + SEED_LEN + TAG_LEN;

/// OWASP's 2024 baseline for Argon2id. Stored per file so raising these later
/// does not orphan existing keys.
const MEMORY_KIB: u32 = 19 * 1024;
const ITERATIONS: u32 = 2;
const PARALLELISM: u32 = 1;

/// A key file is untrusted input, and Argon2 allocates exactly what the header
/// asks for, so this ceiling is the only thing standing between a 95-byte file
/// and a multi-gigabyte allocation (issue #6: a 4 GiB ceiling let a fuzzer
/// reproducer request 2.37 GiB and pass). Writers only ever emit `MEMORY_KIB`,
/// so a bound they never approach costs nothing; 256 MiB leaves room for a
/// future raise of the baseline while staying well under what a machine
/// opening a key can be expected to have free.
const MAX_MEMORY_KIB: u32 = 256 * 1024;
const MAX_ITERATIONS: u32 = 64;
/// Each lane costs work and, in Argon2's threaded configuration, a thread;
/// writers emit `PARALLELISM`, so anything past a small multiple is hostile.
const MAX_PARALLELISM: u32 = 4;
/// And refuse parameters so weak the passphrase is effectively unprotected. The
/// header is authenticated, so this cannot be a downgrade of an honest file;
/// it stops a file written by a careless or hostile implementation from
/// opening without complaint. 8 MiB is the Argon2 RFC 9106 second recommended
/// configuration's floor for memory-constrained environments.
pub const MIN_MEMORY_KIB: u32 = 8 * 1024;
pub const MIN_ITERATIONS: u32 = 1;

/// The Argon2 parameters as a key file's v2 header stores them:
/// `parallelism u8 || memory_kib u32be || iterations u32be`. Shared with the
/// epoch store so both files are bounded by exactly the same code.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Argon2Params {
    pub(crate) parallelism: u8,
    pub(crate) memory: u32,
    pub(crate) iterations: u32,
}

pub(crate) const PARAMS_LEN: usize = 9;

impl Argon2Params {
    /// What every writer emits.
    pub(crate) const WRITER: Self = Self {
        parallelism: PARALLELISM as u8,
        memory: MEMORY_KIB,
        iterations: ITERATIONS,
    };

    pub(crate) fn encode(self) -> [u8; PARAMS_LEN] {
        let mut out = [0u8; PARAMS_LEN];
        out[0] = self.parallelism;
        out[1..5].copy_from_slice(&self.memory.to_be_bytes());
        out[5..9].copy_from_slice(&self.iterations.to_be_bytes());
        out
    }

    /// Reads and bounds-checks the parameters. Runs before anything is
    /// allocated for Argon2, so a hostile header costs nothing.
    pub(crate) fn parse(bytes: &[u8]) -> Result<Self, KeyringError> {
        let bytes: &[u8; PARAMS_LEN] = bytes.try_into().map_err(|_| KeyringError::Malformed)?;
        let parallelism = bytes[0];
        let memory = u32::from_be_bytes([bytes[1], bytes[2], bytes[3], bytes[4]]);
        let iterations = u32::from_be_bytes([bytes[5], bytes[6], bytes[7], bytes[8]]);
        let lanes = u32::from(parallelism);
        // `memory / 8 < parallelism` is Argon2's minimum of 8 blocks per lane; it
        // is checked here so the failure is attributable to our bound instead of
        // surfacing later from `Params::new`.
        if lanes == 0
            || lanes > MAX_PARALLELISM
            || !(MIN_MEMORY_KIB..=MAX_MEMORY_KIB).contains(&memory)
            || !(MIN_ITERATIONS..=MAX_ITERATIONS).contains(&iterations)
            || memory / 8 < lanes
        {
            return Err(KeyringError::UnreasonableParameters);
        }
        Ok(Self {
            parallelism,
            memory,
            iterations,
        })
    }

    pub(crate) fn derive(
        self,
        passphrase: &str,
        salt: &[u8],
    ) -> Result<Zeroizing<[u8; 32]>, KeyringError> {
        derive(
            passphrase,
            salt,
            self.memory,
            self.iterations,
            u32::from(self.parallelism),
        )
    }
}

#[derive(Debug, Error, PartialEq, Eq)]
pub enum KeyringError {
    #[error("not a HIDE key file")]
    NotAKeyFile,
    #[error("not a HIDE epoch store")]
    NotAnEpochStore,
    #[error("epoch store holds more than {0} entries")]
    TooManyEntries(usize),
    #[error("unsupported key file version {0}")]
    UnsupportedVersion(u8),
    #[error("key file is malformed")]
    Malformed,
    #[error("key file requests unreasonable Argon2 parameters")]
    UnreasonableParameters,
    #[error("incorrect passphrase, or the key file has been modified")]
    WrongPassphrase,
    #[error("passphrase must be at least {0} characters")]
    PassphraseTooShort(usize),
    #[error("this is a {found} key, but a {expected} key is required")]
    WrongPurpose {
        expected: KeyPurpose,
        found: KeyPurpose,
    },
    #[error("cryptographic operation failed: {0}")]
    Crypto(String),
}

/// What a sealed seed is for. Stored in the file so the wrong key cannot be
/// used silently against the right command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyPurpose {
    /// A master seed from which both the encryption and signing keys derive.
    Identity,
    /// A bare recipient seed, as written by v0.4.0 and earlier.
    Encryption,
}

impl KeyPurpose {
    fn tag(self) -> u8 {
        match self {
            Self::Identity => 1,
            Self::Encryption => 2,
        }
    }

    fn from_tag(tag: u8) -> Option<Self> {
        match tag {
            1 => Some(Self::Identity),
            2 => Some(Self::Encryption),
            _ => None,
        }
    }
}

impl core::fmt::Display for KeyPurpose {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter.write_str(match self {
            Self::Identity => "HIDE identity",
            Self::Encryption => "encryption-only",
        })
    }
}

impl From<CryptoError> for KeyringError {
    fn from(error: CryptoError) -> Self {
        Self::Crypto(error.to_string())
    }
}

pub const MIN_PASSPHRASE_LEN: usize = 8;

/// The passphrase exactly as a writer feeds it to Argon2: Unicode NFC.
///
/// Before this, the raw UTF-8 was used, so "é" typed as U+00E9 on one system
/// and as "e" + U+0301 on another derived different keys (spec §15.5).
pub fn normalize_passphrase(passphrase: &str) -> Zeroizing<String> {
    use unicode_normalization::UnicodeNormalization as _;
    Zeroizing::new(passphrase.nfc().collect())
}

/// Every spelling a reader tries, in order: NFC (what writers emit now), then
/// the raw input and NFD (what an older writer may have hashed). Duplicates are
/// dropped, so an ASCII passphrase costs exactly one Argon2 pass; only a wrong
/// non-ASCII passphrase pays for up to three.
pub(crate) fn passphrase_candidates(passphrase: &str) -> Vec<Zeroizing<String>> {
    use unicode_normalization::UnicodeNormalization as _;
    let mut out: Vec<Zeroizing<String>> = Vec::with_capacity(3);
    for candidate in [
        normalize_passphrase(passphrase),
        Zeroizing::new(passphrase.to_owned()),
        Zeroizing::new(passphrase.nfd().collect()),
    ] {
        if !out.iter().any(|seen| **seen == *candidate) {
            out.push(candidate);
        }
    }
    out
}

/// Whether a stored key needs a passphrase, so a caller can prompt only when needed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyFormat {
    Protected,
    Raw,
}

pub fn inspect(bytes: &[u8]) -> KeyFormat {
    if bytes.starts_with(MAGIC) {
        KeyFormat::Protected
    } else {
        KeyFormat::Raw
    }
}

/// Seals `secret` under `passphrase` as an encryption-only key.
pub fn protect(secret: &RecipientSecret, passphrase: &str) -> Result<Vec<u8>, KeyringError> {
    protect_seed(
        secret.expose_seed_for_sealing(),
        passphrase,
        KeyPurpose::Encryption,
    )
}

/// Seals a master identity seed, from which both keys derive.
pub fn protect_identity(seed: &[u8; SEED_LEN], passphrase: &str) -> Result<Vec<u8>, KeyringError> {
    protect_seed(seed, passphrase, KeyPurpose::Identity)
}

fn protect_seed(
    seed: &[u8],
    passphrase: &str,
    purpose: KeyPurpose,
) -> Result<Vec<u8>, KeyringError> {
    let passphrase = normalize_passphrase(passphrase);
    if passphrase.chars().count() < MIN_PASSPHRASE_LEN {
        return Err(KeyringError::PassphraseTooShort(MIN_PASSPHRASE_LEN));
    }
    if seed.len() != SEED_LEN {
        return Err(KeyringError::Malformed);
    }

    let mut salt = [0u8; SALT_LEN];
    let mut nonce = [0u8; NONCE_LEN];
    getrandom::fill(&mut salt).map_err(|error| KeyringError::Crypto(error.to_string()))?;
    getrandom::fill(&mut nonce).map_err(|error| KeyringError::Crypto(error.to_string()))?;

    let mut header = Vec::with_capacity(SEALED_LEN);
    header.extend_from_slice(MAGIC);
    header.push(FORMAT_VERSION);
    header.extend_from_slice(&Argon2Params::WRITER.encode());
    header.extend_from_slice(&salt);
    header.extend_from_slice(&nonce);
    header.push(purpose.tag());
    debug_assert_eq!(header.len(), HEADER_LEN);

    let wrapping = Argon2Params::WRITER.derive(&passphrase, &salt)?;
    let cipher = ChaCha20Poly1305::new((&*wrapping).into());
    let sealed = cipher
        .encrypt(
            (&nonce).into(),
            Payload {
                msg: seed,
                aad: &header,
            },
        )
        .map_err(|_| CryptoError::Authentication)?;

    let mut output = header;
    output.extend_from_slice(&sealed);
    Ok(output)
}

/// Opens a key file and returns the encryption key, whatever shape the file is.
///
/// Every surface must read a key file the same way. A raw file is a master
/// seed, exactly as the CLI writes it, so the encryption key is derived rather
/// than being the file's bytes; reading those bytes directly yields a
/// different key and silently breaks interoperability.
pub fn open(bytes: &[u8], passphrase: Option<&str>) -> Result<RecipientSecret, KeyringError> {
    match inspect(bytes) {
        KeyFormat::Raw => {
            let mut seed = Zeroizing::new([0_u8; SEED_LEN]);
            if bytes.len() != SEED_LEN {
                return Err(KeyringError::Malformed);
            }
            seed.copy_from_slice(bytes);
            Identity::from_seed(seed).recipient_secret()
        }
        KeyFormat::Protected => {
            let passphrase = passphrase.ok_or(KeyringError::WrongPassphrase)?;
            let (seed, purpose) = unprotect_seed(bytes, passphrase)?;
            match purpose {
                // An identity holds both keys; asking for the encryption one is
                // not a purpose mismatch.
                KeyPurpose::Identity => Identity::from_seed(seed).recipient_secret(),
                KeyPurpose::Encryption => Ok(RecipientSecret::from_bytes(&seed[..])?),
            }
        }
    }
}

/// A master seed, and the two independent keys derived from it.
///
/// Derivation is one-way and domain-separated, so recovering the signing key
/// from the encryption key (or the reverse) is not possible without the master.
pub struct Identity {
    seed: Zeroizing<[u8; SEED_LEN]>,
}

const ENCRYPTION_INFO: &[u8] = b"HIDE/0.5 identity encryption";
const SIGNING_INFO: &[u8] = b"HIDE/0.5 identity signing";

impl Identity {
    pub fn generate() -> Result<Self, KeyringError> {
        let mut seed = Zeroizing::new([0u8; SEED_LEN]);
        getrandom::fill(&mut *seed).map_err(|error| KeyringError::Crypto(error.to_string()))?;
        Ok(Self { seed })
    }

    pub fn from_seed(seed: Zeroizing<[u8; SEED_LEN]>) -> Self {
        Self { seed }
    }

    pub fn expose_seed_for_sealing(&self) -> &[u8; SEED_LEN] {
        &self.seed
    }

    pub fn recipient_secret(&self) -> Result<RecipientSecret, KeyringError> {
        let seed = self.derive(ENCRYPTION_INFO);
        Ok(RecipientSecret::from_bytes(&seed[..])?)
    }

    pub fn signing_seed(&self) -> Zeroizing<[u8; SEED_LEN]> {
        self.derive(SIGNING_INFO)
    }

    fn derive(&self, info: &[u8]) -> Zeroizing<[u8; SEED_LEN]> {
        let mut out = Zeroizing::new([0u8; SEED_LEN]);
        Hkdf::<Sha256>::from_prk(&*self.seed)
            .expect("32 bytes is a valid PRK for SHA-256")
            .expand(info, &mut *out)
            .expect("32 bytes is a valid HKDF output length");
        out
    }
}

pub fn unprotect(bytes: &[u8], passphrase: &str) -> Result<RecipientSecret, KeyringError> {
    let (seed, purpose) = unprotect_seed(bytes, passphrase)?;
    // A v1 file has no purpose byte and predates signing, so it is encryption-only.
    if purpose != KeyPurpose::Encryption {
        return Err(KeyringError::WrongPurpose {
            expected: KeyPurpose::Encryption,
            found: purpose,
        });
    }
    Ok(RecipientSecret::from_bytes(&seed[..])?)
}

/// Opens a sealed seed and reports what it is for, so a caller can refuse a key
/// of the wrong purpose with a message that names the mismatch.
pub fn unprotect_seed(
    bytes: &[u8],
    passphrase: &str,
) -> Result<(Zeroizing<[u8; SEED_LEN]>, KeyPurpose), KeyringError> {
    if !bytes.starts_with(MAGIC) {
        return Err(KeyringError::NotAKeyFile);
    }
    let version = *bytes.get(8).ok_or(KeyringError::Malformed)?;
    let (header_len, expected_len) = match version {
        FORMAT_VERSION => (HEADER_LEN, SEALED_LEN),
        LEGACY_VERSION => (LEGACY_HEADER_LEN, LEGACY_SEALED_LEN),
        other => return Err(KeyringError::UnsupportedVersion(other)),
    };
    if bytes.len() != expected_len {
        return Err(KeyringError::Malformed);
    }

    let params = Argon2Params::parse(&bytes[9..9 + PARAMS_LEN])?;

    let purpose = if version == LEGACY_VERSION {
        KeyPurpose::Encryption
    } else {
        KeyPurpose::from_tag(bytes[LEGACY_HEADER_LEN]).ok_or(KeyringError::Malformed)?
    };

    let salt = &bytes[18..18 + SALT_LEN];
    let nonce = &bytes[18 + SALT_LEN..18 + SALT_LEN + NONCE_LEN];
    let header = &bytes[..header_len];
    let nonce: [u8; NONCE_LEN] = nonce.try_into().map_err(|_| KeyringError::Malformed)?;

    for candidate in passphrase_candidates(passphrase) {
        let wrapping = params.derive(&candidate, salt)?;
        let cipher = ChaCha20Poly1305::new((&*wrapping).into());
        if let Ok(seed) = cipher.decrypt(
            (&nonce).into(),
            Payload {
                msg: &bytes[header_len..],
                aad: header,
            },
        ) {
            let mut out = Zeroizing::new([0u8; SEED_LEN]);
            out.copy_from_slice(&Zeroizing::new(seed)[..]);
            return Ok((out, purpose));
        }
    }
    Err(KeyringError::WrongPassphrase)
}

/// Base64 wrapper so a public key can be pasted into a message or a chat.
pub fn encode_public(bytes: &[u8]) -> String {
    let body = STANDARD.encode(bytes);
    let mut out = String::from("hide-public-key:");
    for (index, chunk) in body.as_bytes().chunks(64).enumerate() {
        out.push('\n');
        let _ = index;
        out.push_str(std::str::from_utf8(chunk).unwrap_or_default());
    }
    out.push('\n');
    out
}

pub fn decode_public(text: &str) -> Result<Vec<u8>, KeyringError> {
    let body: String = text
        .lines()
        .filter(|line| !line.trim().is_empty() && !line.starts_with("hide-public-key:"))
        .collect();
    STANDARD
        .decode(body.trim())
        .map_err(|_| KeyringError::Malformed)
}

fn derive(
    passphrase: &str,
    salt: &[u8],
    memory: u32,
    iterations: u32,
    parallelism: u32,
) -> Result<Zeroizing<[u8; 32]>, KeyringError> {
    // Under the fuzzer every structurally valid header pays a real Argon2
    // pass, which is 8 MiB and milliseconds per input: the keyring target did
    // half a million executions in four hours while its siblings did billions.
    // The parameters have already been bounds-checked by the caller, so the
    // fuzz build derives at the floor and spends its time on the parsing and
    // AEAD paths instead. cargo-fuzz sets `cfg(fuzzing)`; nothing else does.
    #[cfg(fuzzing)]
    let (memory, iterations) = {
        let _ = (memory, iterations);
        (MIN_MEMORY_KIB, 1)
    };
    let params = Params::new(memory, iterations, parallelism, Some(32))
        .map_err(|_| KeyringError::UnreasonableParameters)?;
    let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
    let mut key = Zeroizing::new([0u8; 32]);
    argon
        .hash_password_into(passphrase.as_bytes(), salt, &mut *key)
        .map_err(|_| KeyringError::UnreasonableParameters)?;
    Ok(key)
}

/// Silences an unused-import warning when the AEAD trait bounds change upstream.
const _: fn() = || {
    fn assert_aead<T: AeadCore>() {}
    assert_aead::<ChaCha20Poly1305>();
};

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

    fn secret() -> RecipientSecret {
        RecipientSecret::from_bytes(&[0x42; 32]).expect("seed")
    }

    /// Secrets deliberately do not implement `Debug`, so `unwrap_err` cannot be
    /// used on a `Result` carrying one.
    fn error_of<T>(result: Result<T, KeyringError>) -> KeyringError {
        match result {
            Ok(_) => panic!("expected an error"),
            Err(error) => error,
        }
    }

    #[test]
    fn round_trips_under_the_correct_passphrase() -> Result<(), KeyringError> {
        let sealed = protect(&secret(), "correct horse battery")?;
        assert_eq!(inspect(&sealed), KeyFormat::Protected);
        assert_eq!(
            unprotect(&sealed, "correct horse battery")?.expose_seed_for_sealing(),
            secret().expose_seed_for_sealing()
        );
        Ok(())
    }

    #[test]
    fn wrong_passphrase_and_tampering_both_fail() -> Result<(), KeyringError> {
        let sealed = protect(&secret(), "correct horse battery")?;
        assert_eq!(
            error_of(unprotect(&sealed, "wrong horse battery")),
            KeyringError::WrongPassphrase
        );

        // Every byte is authenticated, including the Argon2 parameters.
        for index in 0..sealed.len() {
            let mut damaged = sealed.clone();
            damaged[index] ^= 0x01;
            assert!(
                unprotect(&damaged, "correct horse battery").is_err(),
                "accepted a mutation at byte {index}"
            );
        }
        Ok(())
    }

    #[test]
    fn each_file_is_unique_and_length_is_fixed() -> Result<(), KeyringError> {
        let first = protect(&secret(), "correct horse battery")?;
        let second = protect(&secret(), "correct horse battery")?;
        assert_ne!(first, second, "salt or nonce was reused");
        assert_eq!(first.len(), SEALED_LEN);
        assert_eq!(second.len(), SEALED_LEN);
        Ok(())
    }

    const NFC: &str = "parol\u{0103} \u{00e9}t\u{00e9} sigur\u{0103}";
    const NFD: &str = "parola\u{0306} e\u{0301}te\u{0301} sigura\u{0306}";

    /// A key file sealed by 0.9.0 and earlier, which hashed the raw UTF-8.
    fn seal_raw_like_0_9(seed: &[u8; SEED_LEN], passphrase: &str) -> Vec<u8> {
        let salt = [0x11u8; SALT_LEN];
        let nonce = [0x22u8; NONCE_LEN];
        let mut header = Vec::new();
        header.extend_from_slice(MAGIC);
        header.push(FORMAT_VERSION);
        header.extend_from_slice(&Argon2Params::WRITER.encode());
        header.extend_from_slice(&salt);
        header.extend_from_slice(&nonce);
        header.push(KeyPurpose::Identity.tag());
        let key = Argon2Params::WRITER.derive(passphrase, &salt).expect("kek");
        let sealed = ChaCha20Poly1305::new((&*key).into())
            .encrypt(
                (&nonce).into(),
                Payload {
                    msg: seed,
                    aad: &header,
                },
            )
            .expect("seal");
        [header, sealed].concat()
    }

    /// §15.5: the same passphrase typed in NFC or NFD opens the same file.
    #[test]
    fn nfc_and_nfd_spellings_open_the_same_file() -> Result<(), KeyringError> {
        assert_ne!(NFC, NFD);
        assert_eq!(&*normalize_passphrase(NFD), NFC);
        let sealed = protect_identity(&[7; SEED_LEN], NFD)?;
        for typed in [NFC, NFD] {
            let (seed, _) = unprotect_seed(&sealed, typed)?;
            assert_eq!(*seed, [7; SEED_LEN], "{typed:?} did not open it");
        }
        Ok(())
    }

    /// Files written before normalisation keep opening, whichever form the
    /// passphrase is typed in now.
    #[test]
    fn files_sealed_under_a_raw_passphrase_still_open() -> Result<(), KeyringError> {
        for raw in [NFC, NFD] {
            let legacy = seal_raw_like_0_9(&[9; SEED_LEN], raw);
            for typed in [NFC, NFD] {
                let (seed, _) = unprotect_seed(&legacy, typed)?;
                assert_eq!(*seed, [9; SEED_LEN], "sealed {raw:?}, typed {typed:?}");
            }
            assert_eq!(
                error_of(unprotect_seed(&legacy, "parola ete sigura")),
                KeyringError::WrongPassphrase
            );
        }
        Ok(())
    }

    /// Writers hash NFC: pinned by opening with the NFC bytes through the
    /// single-candidate primitive, not through the fallback reader.
    #[test]
    fn writers_hash_the_nfc_form() -> Result<(), KeyringError> {
        let sealed = protect_identity(&[5; SEED_LEN], NFD)?;
        let params = Argon2Params::parse(&sealed[9..9 + PARAMS_LEN])?;
        let key = params.derive(NFC, &sealed[18..18 + SALT_LEN])?;
        let nonce: [u8; NONCE_LEN] = sealed[34..46].try_into().expect("12 bytes");
        assert!(
            ChaCha20Poly1305::new((&*key).into())
                .decrypt(
                    (&nonce).into(),
                    Payload {
                        msg: &sealed[HEADER_LEN..],
                        aad: &sealed[..HEADER_LEN]
                    },
                )
                .is_ok(),
            "the writer did not hash the NFC form"
        );
        Ok(())
    }

    #[test]
    fn an_ascii_passphrase_has_one_candidate() {
        assert_eq!(passphrase_candidates("correct horse battery").len(), 1);
        // A fully normalised input in either form collapses to {NFC, NFD};
        // only a mixed one needs a third attempt.
        assert_eq!(passphrase_candidates(NFD).len(), 2);
        assert_eq!(passphrase_candidates(NFC).len(), 2);
        assert_eq!(passphrase_candidates("\u{00e9}e\u{0301}xxxxxx").len(), 3);
    }

    /// The 8-character minimum counts the normalised form, so "e" + U+0301 is
    /// one character, as a user would count it.
    #[test]
    fn the_minimum_length_counts_normalised_characters() {
        let seven = "e\u{0301}e\u{0301}e\u{0301}e\u{0301}e\u{0301}e\u{0301}e\u{0301}";
        assert_eq!(seven.chars().count(), 14);
        assert_eq!(
            protect(&secret(), seven).unwrap_err(),
            KeyringError::PassphraseTooShort(MIN_PASSPHRASE_LEN)
        );
    }

    #[test]
    fn rejects_short_passphrases_and_foreign_files() {
        assert_eq!(
            protect(&secret(), "short").unwrap_err(),
            KeyringError::PassphraseTooShort(MIN_PASSPHRASE_LEN)
        );
        assert_eq!(
            error_of(unprotect(b"not a key file", "whatever")),
            KeyringError::NotAKeyFile
        );
        assert_eq!(
            error_of(unprotect(MAGIC, "whatever")),
            KeyringError::Malformed
        );
    }

    #[test]
    fn refuses_a_file_demanding_absurd_memory() -> Result<(), KeyringError> {
        let mut sealed = protect(&secret(), "correct horse battery")?;
        sealed[10..14].copy_from_slice(&u32::MAX.to_be_bytes());
        assert_eq!(
            error_of(unprotect(&sealed, "correct horse battery")),
            KeyringError::UnreasonableParameters
        );
        Ok(())
    }

    // Issue #6: the nightly fuzzer produced this file, which the old 4 GiB
    // ceiling accepted and which then asked the allocator for 2.37 GiB
    // (p_cost = 83, m_cost = 2 490 368 KiB). Pinned byte-for-byte so the fix
    // is measured against the real input, not a hand-made approximation.
    #[test]
    fn refuses_the_fuzzer_reproducer_before_allocating() {
        const REPRODUCER: [u8; SEALED_LEN] = [
            0x48, 0x49, 0x44, 0x45, 0x2d, 0x4b, 0x45, 0x59, 0x02, 0x53, 0x00, 0x26, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x01, 0x2b, 0x2b, 0x55, 0x55, 0x55, 0x55, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x55, 0x00, 0x01, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x01, 0x2b, 0x2b, 0x55, 0x55, 0x55, 0x55, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0x01, 0x06, 0xff, 0xff, 0xdf, 0xff, 0xff, 0xff, 0xff, 0x03, 0xff, 0xff,
            0xff, 0xff, 0xbf, 0xff, 0xff, 0xfd, 0xff, 0xff, 0xff, 0xff, 0x55,
        ];
        assert_eq!(
            error_of(unprotect(&REPRODUCER, "correct horse battery")),
            KeyringError::UnreasonableParameters
        );
    }

    #[test]
    fn refuses_a_file_demanding_absurd_parallelism() -> Result<(), KeyringError> {
        let mut sealed = protect(&secret(), "correct horse battery")?;
        sealed[9] = 0xff;
        assert_eq!(
            error_of(unprotect(&sealed, "correct horse battery")),
            KeyringError::UnreasonableParameters
        );
        Ok(())
    }

    // The header is authenticated, so an honest file cannot be downgraded; this
    // catches a file that was WRITTEN weak, which would otherwise open silently.
    #[test]
    fn refuses_a_file_written_with_too_little_memory() -> Result<(), KeyringError> {
        let mut sealed = protect(&secret(), "correct horse battery")?;
        sealed[10..14].copy_from_slice(&(MIN_MEMORY_KIB - 1).to_be_bytes());
        assert_eq!(
            error_of(unprotect(&sealed, "correct horse battery")),
            KeyringError::UnreasonableParameters
        );
        Ok(())
    }

    #[test]
    fn raw_keys_still_open_without_a_passphrase() -> Result<(), KeyringError> {
        let raw = secret().expose_seed_for_sealing().to_vec();
        let mut seed = Zeroizing::new([0_u8; SEED_LEN]);
        seed.copy_from_slice(&raw);
        let expected = Identity::from_seed(seed).recipient_secret()?;
        assert_eq!(inspect(&raw), KeyFormat::Raw);
        // A raw file is a master seed, so the encryption key is derived from
        // it. Reading the bytes as the key itself is what broke CLI/SDK
        // interoperability: every surface must agree with the CLI here.
        assert_eq!(
            open(&raw, None)?.public_key()?.to_bytes(),
            expected.public_key()?.to_bytes()
        );
        assert_ne!(open(&raw, None)?.expose_seed_for_sealing(), raw);
        assert_eq!(
            error_of(open(&protect(&secret(), "correct horse battery")?, None)),
            KeyringError::WrongPassphrase
        );
        Ok(())
    }

    /// A key file written by v0.4.0 has no purpose byte. It must still open, or
    /// every existing user loses access to their encrypted data.
    #[test]
    fn v1_key_files_still_open_and_read_as_encryption_only() -> Result<(), KeyringError> {
        // Rebuild a v1 file exactly as the previous release wrote it.
        let seed = [0x31; SEED_LEN];
        let salt = [0x32; SALT_LEN];
        let nonce = [0x33; NONCE_LEN];
        let mut header = Vec::new();
        header.extend_from_slice(MAGIC);
        header.push(LEGACY_VERSION);
        header.push(PARALLELISM as u8);
        header.extend_from_slice(&MEMORY_KIB.to_be_bytes());
        header.extend_from_slice(&ITERATIONS.to_be_bytes());
        header.extend_from_slice(&salt);
        header.extend_from_slice(&nonce);
        assert_eq!(header.len(), LEGACY_HEADER_LEN);

        let wrapping = derive(
            "correct horse battery",
            &salt,
            MEMORY_KIB,
            ITERATIONS,
            PARALLELISM,
        )?;
        let sealed = ChaCha20Poly1305::new((&*wrapping).into())
            .encrypt(
                (&nonce).into(),
                Payload {
                    msg: &seed,
                    aad: &header,
                },
            )
            .map_err(|_| CryptoError::Authentication)?;
        let mut file = header;
        file.extend_from_slice(&sealed);
        assert_eq!(file.len(), LEGACY_SEALED_LEN);

        let (opened, purpose) = unprotect_seed(&file, "correct horse battery")?;
        assert_eq!(&opened[..], &seed);
        assert_eq!(purpose, KeyPurpose::Encryption);
        // And through the typed path that predates this change.
        unprotect(&file, "correct horse battery")?;
        Ok(())
    }

    #[test]
    fn an_identity_key_is_refused_where_an_encryption_key_is_required() -> Result<(), KeyringError>
    {
        let identity = Identity::generate()?;
        let file = protect_identity(identity.expose_seed_for_sealing(), "correct horse battery")?;
        assert_eq!(
            error_of(unprotect(&file, "correct horse battery")),
            KeyringError::WrongPurpose {
                expected: KeyPurpose::Encryption,
                found: KeyPurpose::Identity,
            }
        );
        Ok(())
    }

    #[test]
    fn an_identity_round_trips_and_derives_stable_keys() -> Result<(), KeyringError> {
        let identity = Identity::generate()?;
        let file = protect_identity(identity.expose_seed_for_sealing(), "correct horse battery")?;
        let (seed, purpose) = unprotect_seed(&file, "correct horse battery")?;
        assert_eq!(purpose, KeyPurpose::Identity);

        let reopened = Identity::from_seed(seed);
        assert_eq!(
            reopened.recipient_secret()?.public_key()?.to_bytes(),
            identity.recipient_secret()?.public_key()?.to_bytes()
        );
        assert_eq!(&*reopened.signing_seed(), &*identity.signing_seed());
        Ok(())
    }

    /// The point of deriving both from one master: neither derived key may equal
    /// the master, or each other, or the whole separation is decorative.
    #[test]
    fn the_two_derived_keys_are_independent_of_each_other_and_the_master()
    -> Result<(), KeyringError> {
        let identity = Identity::generate()?;
        let master = *identity.expose_seed_for_sealing();
        let signing = identity.signing_seed();
        let encryption = identity.derive(ENCRYPTION_INFO);

        assert_ne!(&*signing, &master);
        assert_ne!(&*encryption, &master);
        assert_ne!(&*signing, &*encryption);
        Ok(())
    }

    #[test]
    fn public_key_armor_round_trips() -> Result<(), KeyringError> {
        let public = secret().public_key()?.to_bytes();
        let armored = encode_public(&public);
        assert!(armored.starts_with("hide-public-key:"));
        assert!(armored.lines().skip(1).all(|line| line.len() <= 64));
        assert_eq!(decode_public(&armored)?, public);
        assert!(decode_public("hide-public-key:\n!!!not base64!!!").is_err());
        Ok(())
    }
}