Skip to main content

hide_keyring/
lib.rs

1//! Password-protected storage for HIDE secret keys.
2//!
3//! `hide-crypto` deliberately knows nothing about files or passwords. This crate
4//! adds the at-rest layer: Argon2id stretches a passphrase into a wrapping key,
5//! which seals the 32-byte recipient seed with ChaCha20-Poly1305.
6//!
7//! This protects a key file at rest. It is not a hardware-backed vault: while a
8//! key is in use it lives in ordinary process memory.
9
10use argon2::{Algorithm, Argon2, Params, Version};
11use base64::{Engine, engine::general_purpose::STANDARD};
12use chacha20poly1305::{
13    AeadCore, ChaCha20Poly1305, KeyInit,
14    aead::{Aead, Payload},
15};
16use hide_crypto::{CryptoError, RecipientSecret};
17use hkdf::Hkdf;
18use sha2::Sha256;
19use thiserror::Error;
20use zeroize::Zeroizing;
21
22pub mod epoch_store;
23
24pub use epoch_store::EpochStore;
25
26const MAGIC: &[u8] = b"HIDE-KEY";
27/// Version 1 sealed a bare recipient seed. Version 2 adds a purpose byte, so a
28/// signing key and an encryption key are no longer byte-indistinguishable.
29const FORMAT_VERSION: u8 = 2;
30const LEGACY_VERSION: u8 = 1;
31const SALT_LEN: usize = 16;
32const NONCE_LEN: usize = 12;
33const SEED_LEN: usize = 32;
34const TAG_LEN: usize = 16;
35const LEGACY_HEADER_LEN: usize = 8 + 1 + 1 + 4 + 4 + SALT_LEN + NONCE_LEN;
36const HEADER_LEN: usize = LEGACY_HEADER_LEN + 1;
37const SEALED_LEN: usize = HEADER_LEN + SEED_LEN + TAG_LEN;
38const LEGACY_SEALED_LEN: usize = LEGACY_HEADER_LEN + SEED_LEN + TAG_LEN;
39
40/// OWASP's 2024 baseline for Argon2id. Stored per file so raising these later
41/// does not orphan existing keys.
42const MEMORY_KIB: u32 = 19 * 1024;
43const ITERATIONS: u32 = 2;
44const PARALLELISM: u32 = 1;
45
46/// A key file is untrusted input, and Argon2 allocates exactly what the header
47/// asks for, so this ceiling is the only thing standing between a 95-byte file
48/// and a multi-gigabyte allocation (issue #6: a 4 GiB ceiling let a fuzzer
49/// reproducer request 2.37 GiB and pass). Writers only ever emit `MEMORY_KIB`,
50/// so a bound they never approach costs nothing; 256 MiB leaves room for a
51/// future raise of the baseline while staying well under what a machine
52/// opening a key can be expected to have free.
53const MAX_MEMORY_KIB: u32 = 256 * 1024;
54const MAX_ITERATIONS: u32 = 64;
55/// Each lane costs work and, in Argon2's threaded configuration, a thread;
56/// writers emit `PARALLELISM`, so anything past a small multiple is hostile.
57const MAX_PARALLELISM: u32 = 4;
58/// And refuse parameters so weak the passphrase is effectively unprotected. The
59/// header is authenticated, so this cannot be a downgrade of an honest file;
60/// it stops a file written by a careless or hostile implementation from
61/// opening without complaint. 8 MiB is the Argon2 RFC 9106 second recommended
62/// configuration's floor for memory-constrained environments.
63pub const MIN_MEMORY_KIB: u32 = 8 * 1024;
64pub const MIN_ITERATIONS: u32 = 1;
65
66/// The Argon2 parameters as a key file's v2 header stores them:
67/// `parallelism u8 || memory_kib u32be || iterations u32be`. Shared with the
68/// epoch store so both files are bounded by exactly the same code.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub(crate) struct Argon2Params {
71    pub(crate) parallelism: u8,
72    pub(crate) memory: u32,
73    pub(crate) iterations: u32,
74}
75
76pub(crate) const PARAMS_LEN: usize = 9;
77
78impl Argon2Params {
79    /// What every writer emits.
80    pub(crate) const WRITER: Self = Self {
81        parallelism: PARALLELISM as u8,
82        memory: MEMORY_KIB,
83        iterations: ITERATIONS,
84    };
85
86    pub(crate) fn encode(self) -> [u8; PARAMS_LEN] {
87        let mut out = [0u8; PARAMS_LEN];
88        out[0] = self.parallelism;
89        out[1..5].copy_from_slice(&self.memory.to_be_bytes());
90        out[5..9].copy_from_slice(&self.iterations.to_be_bytes());
91        out
92    }
93
94    /// Reads and bounds-checks the parameters. Runs before anything is
95    /// allocated for Argon2, so a hostile header costs nothing.
96    pub(crate) fn parse(bytes: &[u8]) -> Result<Self, KeyringError> {
97        let bytes: &[u8; PARAMS_LEN] = bytes.try_into().map_err(|_| KeyringError::Malformed)?;
98        let parallelism = bytes[0];
99        let memory = u32::from_be_bytes([bytes[1], bytes[2], bytes[3], bytes[4]]);
100        let iterations = u32::from_be_bytes([bytes[5], bytes[6], bytes[7], bytes[8]]);
101        let lanes = u32::from(parallelism);
102        // `memory / 8 < parallelism` is Argon2's minimum of 8 blocks per lane; it
103        // is checked here so the failure is attributable to our bound instead of
104        // surfacing later from `Params::new`.
105        if lanes == 0
106            || lanes > MAX_PARALLELISM
107            || !(MIN_MEMORY_KIB..=MAX_MEMORY_KIB).contains(&memory)
108            || !(MIN_ITERATIONS..=MAX_ITERATIONS).contains(&iterations)
109            || memory / 8 < lanes
110        {
111            return Err(KeyringError::UnreasonableParameters);
112        }
113        Ok(Self {
114            parallelism,
115            memory,
116            iterations,
117        })
118    }
119
120    pub(crate) fn derive(
121        self,
122        passphrase: &str,
123        salt: &[u8],
124    ) -> Result<Zeroizing<[u8; 32]>, KeyringError> {
125        derive(
126            passphrase,
127            salt,
128            self.memory,
129            self.iterations,
130            u32::from(self.parallelism),
131        )
132    }
133}
134
135#[derive(Debug, Error, PartialEq, Eq)]
136pub enum KeyringError {
137    #[error("not a HIDE key file")]
138    NotAKeyFile,
139    #[error("not a HIDE epoch store")]
140    NotAnEpochStore,
141    #[error("epoch store holds more than {0} entries")]
142    TooManyEntries(usize),
143    #[error("unsupported key file version {0}")]
144    UnsupportedVersion(u8),
145    #[error("key file is malformed")]
146    Malformed,
147    #[error("key file requests unreasonable Argon2 parameters")]
148    UnreasonableParameters,
149    #[error("incorrect passphrase, or the key file has been modified")]
150    WrongPassphrase,
151    #[error("passphrase must be at least {0} characters")]
152    PassphraseTooShort(usize),
153    #[error("this is a {found} key, but a {expected} key is required")]
154    WrongPurpose {
155        expected: KeyPurpose,
156        found: KeyPurpose,
157    },
158    #[error("cryptographic operation failed: {0}")]
159    Crypto(String),
160}
161
162/// What a sealed seed is for. Stored in the file so the wrong key cannot be
163/// used silently against the right command.
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165pub enum KeyPurpose {
166    /// A master seed from which both the encryption and signing keys derive.
167    Identity,
168    /// A bare recipient seed, as written by v0.4.0 and earlier.
169    Encryption,
170}
171
172impl KeyPurpose {
173    fn tag(self) -> u8 {
174        match self {
175            Self::Identity => 1,
176            Self::Encryption => 2,
177        }
178    }
179
180    fn from_tag(tag: u8) -> Option<Self> {
181        match tag {
182            1 => Some(Self::Identity),
183            2 => Some(Self::Encryption),
184            _ => None,
185        }
186    }
187}
188
189impl core::fmt::Display for KeyPurpose {
190    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
191        formatter.write_str(match self {
192            Self::Identity => "HIDE identity",
193            Self::Encryption => "encryption-only",
194        })
195    }
196}
197
198impl From<CryptoError> for KeyringError {
199    fn from(error: CryptoError) -> Self {
200        Self::Crypto(error.to_string())
201    }
202}
203
204pub const MIN_PASSPHRASE_LEN: usize = 8;
205
206/// The passphrase exactly as a writer feeds it to Argon2: Unicode NFC.
207///
208/// Before this, the raw UTF-8 was used, so "é" typed as U+00E9 on one system
209/// and as "e" + U+0301 on another derived different keys (spec §15.5).
210pub fn normalize_passphrase(passphrase: &str) -> Zeroizing<String> {
211    use unicode_normalization::UnicodeNormalization as _;
212    Zeroizing::new(passphrase.nfc().collect())
213}
214
215/// Every spelling a reader tries, in order: NFC (what writers emit now), then
216/// the raw input and NFD (what an older writer may have hashed). Duplicates are
217/// dropped, so an ASCII passphrase costs exactly one Argon2 pass; only a wrong
218/// non-ASCII passphrase pays for up to three.
219pub(crate) fn passphrase_candidates(passphrase: &str) -> Vec<Zeroizing<String>> {
220    use unicode_normalization::UnicodeNormalization as _;
221    let mut out: Vec<Zeroizing<String>> = Vec::with_capacity(3);
222    for candidate in [
223        normalize_passphrase(passphrase),
224        Zeroizing::new(passphrase.to_owned()),
225        Zeroizing::new(passphrase.nfd().collect()),
226    ] {
227        if !out.iter().any(|seen| **seen == *candidate) {
228            out.push(candidate);
229        }
230    }
231    out
232}
233
234/// Whether a stored key needs a passphrase, so a caller can prompt only when needed.
235#[derive(Debug, Clone, Copy, PartialEq, Eq)]
236pub enum KeyFormat {
237    Protected,
238    Raw,
239}
240
241pub fn inspect(bytes: &[u8]) -> KeyFormat {
242    if bytes.starts_with(MAGIC) {
243        KeyFormat::Protected
244    } else {
245        KeyFormat::Raw
246    }
247}
248
249/// Seals `secret` under `passphrase` as an encryption-only key.
250pub fn protect(secret: &RecipientSecret, passphrase: &str) -> Result<Vec<u8>, KeyringError> {
251    protect_seed(
252        secret.expose_seed_for_sealing(),
253        passphrase,
254        KeyPurpose::Encryption,
255    )
256}
257
258/// Seals a master identity seed, from which both keys derive.
259pub fn protect_identity(seed: &[u8; SEED_LEN], passphrase: &str) -> Result<Vec<u8>, KeyringError> {
260    protect_seed(seed, passphrase, KeyPurpose::Identity)
261}
262
263fn protect_seed(
264    seed: &[u8],
265    passphrase: &str,
266    purpose: KeyPurpose,
267) -> Result<Vec<u8>, KeyringError> {
268    let passphrase = normalize_passphrase(passphrase);
269    if passphrase.chars().count() < MIN_PASSPHRASE_LEN {
270        return Err(KeyringError::PassphraseTooShort(MIN_PASSPHRASE_LEN));
271    }
272    if seed.len() != SEED_LEN {
273        return Err(KeyringError::Malformed);
274    }
275
276    let mut salt = [0u8; SALT_LEN];
277    let mut nonce = [0u8; NONCE_LEN];
278    getrandom::fill(&mut salt).map_err(|error| KeyringError::Crypto(error.to_string()))?;
279    getrandom::fill(&mut nonce).map_err(|error| KeyringError::Crypto(error.to_string()))?;
280
281    let mut header = Vec::with_capacity(SEALED_LEN);
282    header.extend_from_slice(MAGIC);
283    header.push(FORMAT_VERSION);
284    header.extend_from_slice(&Argon2Params::WRITER.encode());
285    header.extend_from_slice(&salt);
286    header.extend_from_slice(&nonce);
287    header.push(purpose.tag());
288    debug_assert_eq!(header.len(), HEADER_LEN);
289
290    let wrapping = Argon2Params::WRITER.derive(&passphrase, &salt)?;
291    let cipher = ChaCha20Poly1305::new((&*wrapping).into());
292    let sealed = cipher
293        .encrypt(
294            (&nonce).into(),
295            Payload {
296                msg: seed,
297                aad: &header,
298            },
299        )
300        .map_err(|_| CryptoError::Authentication)?;
301
302    let mut output = header;
303    output.extend_from_slice(&sealed);
304    Ok(output)
305}
306
307/// Opens a key file and returns the encryption key, whatever shape the file is.
308///
309/// Every surface must read a key file the same way. A raw file is a master
310/// seed, exactly as the CLI writes it, so the encryption key is derived rather
311/// than being the file's bytes; reading those bytes directly yields a
312/// different key and silently breaks interoperability.
313pub fn open(bytes: &[u8], passphrase: Option<&str>) -> Result<RecipientSecret, KeyringError> {
314    match inspect(bytes) {
315        KeyFormat::Raw => {
316            let mut seed = Zeroizing::new([0_u8; SEED_LEN]);
317            if bytes.len() != SEED_LEN {
318                return Err(KeyringError::Malformed);
319            }
320            seed.copy_from_slice(bytes);
321            Identity::from_seed(seed).recipient_secret()
322        }
323        KeyFormat::Protected => {
324            let passphrase = passphrase.ok_or(KeyringError::WrongPassphrase)?;
325            let (seed, purpose) = unprotect_seed(bytes, passphrase)?;
326            match purpose {
327                // An identity holds both keys; asking for the encryption one is
328                // not a purpose mismatch.
329                KeyPurpose::Identity => Identity::from_seed(seed).recipient_secret(),
330                KeyPurpose::Encryption => Ok(RecipientSecret::from_bytes(&seed[..])?),
331            }
332        }
333    }
334}
335
336/// A master seed, and the two independent keys derived from it.
337///
338/// Derivation is one-way and domain-separated, so recovering the signing key
339/// from the encryption key (or the reverse) is not possible without the master.
340pub struct Identity {
341    seed: Zeroizing<[u8; SEED_LEN]>,
342}
343
344const ENCRYPTION_INFO: &[u8] = b"HIDE/0.5 identity encryption";
345const SIGNING_INFO: &[u8] = b"HIDE/0.5 identity signing";
346
347impl Identity {
348    pub fn generate() -> Result<Self, KeyringError> {
349        let mut seed = Zeroizing::new([0u8; SEED_LEN]);
350        getrandom::fill(&mut *seed).map_err(|error| KeyringError::Crypto(error.to_string()))?;
351        Ok(Self { seed })
352    }
353
354    pub fn from_seed(seed: Zeroizing<[u8; SEED_LEN]>) -> Self {
355        Self { seed }
356    }
357
358    pub fn expose_seed_for_sealing(&self) -> &[u8; SEED_LEN] {
359        &self.seed
360    }
361
362    pub fn recipient_secret(&self) -> Result<RecipientSecret, KeyringError> {
363        let seed = self.derive(ENCRYPTION_INFO);
364        Ok(RecipientSecret::from_bytes(&seed[..])?)
365    }
366
367    pub fn signing_seed(&self) -> Zeroizing<[u8; SEED_LEN]> {
368        self.derive(SIGNING_INFO)
369    }
370
371    fn derive(&self, info: &[u8]) -> Zeroizing<[u8; SEED_LEN]> {
372        let mut out = Zeroizing::new([0u8; SEED_LEN]);
373        Hkdf::<Sha256>::from_prk(&*self.seed)
374            .expect("32 bytes is a valid PRK for SHA-256")
375            .expand(info, &mut *out)
376            .expect("32 bytes is a valid HKDF output length");
377        out
378    }
379}
380
381pub fn unprotect(bytes: &[u8], passphrase: &str) -> Result<RecipientSecret, KeyringError> {
382    let (seed, purpose) = unprotect_seed(bytes, passphrase)?;
383    // A v1 file has no purpose byte and predates signing, so it is encryption-only.
384    if purpose != KeyPurpose::Encryption {
385        return Err(KeyringError::WrongPurpose {
386            expected: KeyPurpose::Encryption,
387            found: purpose,
388        });
389    }
390    Ok(RecipientSecret::from_bytes(&seed[..])?)
391}
392
393/// Opens a sealed seed and reports what it is for, so a caller can refuse a key
394/// of the wrong purpose with a message that names the mismatch.
395pub fn unprotect_seed(
396    bytes: &[u8],
397    passphrase: &str,
398) -> Result<(Zeroizing<[u8; SEED_LEN]>, KeyPurpose), KeyringError> {
399    if !bytes.starts_with(MAGIC) {
400        return Err(KeyringError::NotAKeyFile);
401    }
402    let version = *bytes.get(8).ok_or(KeyringError::Malformed)?;
403    let (header_len, expected_len) = match version {
404        FORMAT_VERSION => (HEADER_LEN, SEALED_LEN),
405        LEGACY_VERSION => (LEGACY_HEADER_LEN, LEGACY_SEALED_LEN),
406        other => return Err(KeyringError::UnsupportedVersion(other)),
407    };
408    if bytes.len() != expected_len {
409        return Err(KeyringError::Malformed);
410    }
411
412    let params = Argon2Params::parse(&bytes[9..9 + PARAMS_LEN])?;
413
414    let purpose = if version == LEGACY_VERSION {
415        KeyPurpose::Encryption
416    } else {
417        KeyPurpose::from_tag(bytes[LEGACY_HEADER_LEN]).ok_or(KeyringError::Malformed)?
418    };
419
420    let salt = &bytes[18..18 + SALT_LEN];
421    let nonce = &bytes[18 + SALT_LEN..18 + SALT_LEN + NONCE_LEN];
422    let header = &bytes[..header_len];
423    let nonce: [u8; NONCE_LEN] = nonce.try_into().map_err(|_| KeyringError::Malformed)?;
424
425    for candidate in passphrase_candidates(passphrase) {
426        let wrapping = params.derive(&candidate, salt)?;
427        let cipher = ChaCha20Poly1305::new((&*wrapping).into());
428        if let Ok(seed) = cipher.decrypt(
429            (&nonce).into(),
430            Payload {
431                msg: &bytes[header_len..],
432                aad: header,
433            },
434        ) {
435            let mut out = Zeroizing::new([0u8; SEED_LEN]);
436            out.copy_from_slice(&Zeroizing::new(seed)[..]);
437            return Ok((out, purpose));
438        }
439    }
440    Err(KeyringError::WrongPassphrase)
441}
442
443/// Base64 wrapper so a public key can be pasted into a message or a chat.
444pub fn encode_public(bytes: &[u8]) -> String {
445    let body = STANDARD.encode(bytes);
446    let mut out = String::from("hide-public-key:");
447    for (index, chunk) in body.as_bytes().chunks(64).enumerate() {
448        out.push('\n');
449        let _ = index;
450        out.push_str(std::str::from_utf8(chunk).unwrap_or_default());
451    }
452    out.push('\n');
453    out
454}
455
456pub fn decode_public(text: &str) -> Result<Vec<u8>, KeyringError> {
457    let body: String = text
458        .lines()
459        .filter(|line| !line.trim().is_empty() && !line.starts_with("hide-public-key:"))
460        .collect();
461    STANDARD
462        .decode(body.trim())
463        .map_err(|_| KeyringError::Malformed)
464}
465
466fn derive(
467    passphrase: &str,
468    salt: &[u8],
469    memory: u32,
470    iterations: u32,
471    parallelism: u32,
472) -> Result<Zeroizing<[u8; 32]>, KeyringError> {
473    // Under the fuzzer every structurally valid header pays a real Argon2
474    // pass, which is 8 MiB and milliseconds per input: the keyring target did
475    // half a million executions in four hours while its siblings did billions.
476    // The parameters have already been bounds-checked by the caller, so the
477    // fuzz build derives at the floor and spends its time on the parsing and
478    // AEAD paths instead. cargo-fuzz sets `cfg(fuzzing)`; nothing else does.
479    #[cfg(fuzzing)]
480    let (memory, iterations) = {
481        let _ = (memory, iterations);
482        (MIN_MEMORY_KIB, 1)
483    };
484    let params = Params::new(memory, iterations, parallelism, Some(32))
485        .map_err(|_| KeyringError::UnreasonableParameters)?;
486    let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
487    let mut key = Zeroizing::new([0u8; 32]);
488    argon
489        .hash_password_into(passphrase.as_bytes(), salt, &mut *key)
490        .map_err(|_| KeyringError::UnreasonableParameters)?;
491    Ok(key)
492}
493
494/// Silences an unused-import warning when the AEAD trait bounds change upstream.
495const _: fn() = || {
496    fn assert_aead<T: AeadCore>() {}
497    assert_aead::<ChaCha20Poly1305>();
498};
499
500#[cfg(test)]
501mod tests {
502    use super::*;
503
504    fn secret() -> RecipientSecret {
505        RecipientSecret::from_bytes(&[0x42; 32]).expect("seed")
506    }
507
508    /// Secrets deliberately do not implement `Debug`, so `unwrap_err` cannot be
509    /// used on a `Result` carrying one.
510    fn error_of<T>(result: Result<T, KeyringError>) -> KeyringError {
511        match result {
512            Ok(_) => panic!("expected an error"),
513            Err(error) => error,
514        }
515    }
516
517    #[test]
518    fn round_trips_under_the_correct_passphrase() -> Result<(), KeyringError> {
519        let sealed = protect(&secret(), "correct horse battery")?;
520        assert_eq!(inspect(&sealed), KeyFormat::Protected);
521        assert_eq!(
522            unprotect(&sealed, "correct horse battery")?.expose_seed_for_sealing(),
523            secret().expose_seed_for_sealing()
524        );
525        Ok(())
526    }
527
528    #[test]
529    fn wrong_passphrase_and_tampering_both_fail() -> Result<(), KeyringError> {
530        let sealed = protect(&secret(), "correct horse battery")?;
531        assert_eq!(
532            error_of(unprotect(&sealed, "wrong horse battery")),
533            KeyringError::WrongPassphrase
534        );
535
536        // Every byte is authenticated, including the Argon2 parameters.
537        for index in 0..sealed.len() {
538            let mut damaged = sealed.clone();
539            damaged[index] ^= 0x01;
540            assert!(
541                unprotect(&damaged, "correct horse battery").is_err(),
542                "accepted a mutation at byte {index}"
543            );
544        }
545        Ok(())
546    }
547
548    #[test]
549    fn each_file_is_unique_and_length_is_fixed() -> Result<(), KeyringError> {
550        let first = protect(&secret(), "correct horse battery")?;
551        let second = protect(&secret(), "correct horse battery")?;
552        assert_ne!(first, second, "salt or nonce was reused");
553        assert_eq!(first.len(), SEALED_LEN);
554        assert_eq!(second.len(), SEALED_LEN);
555        Ok(())
556    }
557
558    const NFC: &str = "parol\u{0103} \u{00e9}t\u{00e9} sigur\u{0103}";
559    const NFD: &str = "parola\u{0306} e\u{0301}te\u{0301} sigura\u{0306}";
560
561    /// A key file sealed by 0.9.0 and earlier, which hashed the raw UTF-8.
562    fn seal_raw_like_0_9(seed: &[u8; SEED_LEN], passphrase: &str) -> Vec<u8> {
563        let salt = [0x11u8; SALT_LEN];
564        let nonce = [0x22u8; NONCE_LEN];
565        let mut header = Vec::new();
566        header.extend_from_slice(MAGIC);
567        header.push(FORMAT_VERSION);
568        header.extend_from_slice(&Argon2Params::WRITER.encode());
569        header.extend_from_slice(&salt);
570        header.extend_from_slice(&nonce);
571        header.push(KeyPurpose::Identity.tag());
572        let key = Argon2Params::WRITER.derive(passphrase, &salt).expect("kek");
573        let sealed = ChaCha20Poly1305::new((&*key).into())
574            .encrypt(
575                (&nonce).into(),
576                Payload {
577                    msg: seed,
578                    aad: &header,
579                },
580            )
581            .expect("seal");
582        [header, sealed].concat()
583    }
584
585    /// §15.5: the same passphrase typed in NFC or NFD opens the same file.
586    #[test]
587    fn nfc_and_nfd_spellings_open_the_same_file() -> Result<(), KeyringError> {
588        assert_ne!(NFC, NFD);
589        assert_eq!(&*normalize_passphrase(NFD), NFC);
590        let sealed = protect_identity(&[7; SEED_LEN], NFD)?;
591        for typed in [NFC, NFD] {
592            let (seed, _) = unprotect_seed(&sealed, typed)?;
593            assert_eq!(*seed, [7; SEED_LEN], "{typed:?} did not open it");
594        }
595        Ok(())
596    }
597
598    /// Files written before normalisation keep opening, whichever form the
599    /// passphrase is typed in now.
600    #[test]
601    fn files_sealed_under_a_raw_passphrase_still_open() -> Result<(), KeyringError> {
602        for raw in [NFC, NFD] {
603            let legacy = seal_raw_like_0_9(&[9; SEED_LEN], raw);
604            for typed in [NFC, NFD] {
605                let (seed, _) = unprotect_seed(&legacy, typed)?;
606                assert_eq!(*seed, [9; SEED_LEN], "sealed {raw:?}, typed {typed:?}");
607            }
608            assert_eq!(
609                error_of(unprotect_seed(&legacy, "parola ete sigura")),
610                KeyringError::WrongPassphrase
611            );
612        }
613        Ok(())
614    }
615
616    /// Writers hash NFC: pinned by opening with the NFC bytes through the
617    /// single-candidate primitive, not through the fallback reader.
618    #[test]
619    fn writers_hash_the_nfc_form() -> Result<(), KeyringError> {
620        let sealed = protect_identity(&[5; SEED_LEN], NFD)?;
621        let params = Argon2Params::parse(&sealed[9..9 + PARAMS_LEN])?;
622        let key = params.derive(NFC, &sealed[18..18 + SALT_LEN])?;
623        let nonce: [u8; NONCE_LEN] = sealed[34..46].try_into().expect("12 bytes");
624        assert!(
625            ChaCha20Poly1305::new((&*key).into())
626                .decrypt(
627                    (&nonce).into(),
628                    Payload {
629                        msg: &sealed[HEADER_LEN..],
630                        aad: &sealed[..HEADER_LEN]
631                    },
632                )
633                .is_ok(),
634            "the writer did not hash the NFC form"
635        );
636        Ok(())
637    }
638
639    #[test]
640    fn an_ascii_passphrase_has_one_candidate() {
641        assert_eq!(passphrase_candidates("correct horse battery").len(), 1);
642        // A fully normalised input in either form collapses to {NFC, NFD};
643        // only a mixed one needs a third attempt.
644        assert_eq!(passphrase_candidates(NFD).len(), 2);
645        assert_eq!(passphrase_candidates(NFC).len(), 2);
646        assert_eq!(passphrase_candidates("\u{00e9}e\u{0301}xxxxxx").len(), 3);
647    }
648
649    /// The 8-character minimum counts the normalised form, so "e" + U+0301 is
650    /// one character, as a user would count it.
651    #[test]
652    fn the_minimum_length_counts_normalised_characters() {
653        let seven = "e\u{0301}e\u{0301}e\u{0301}e\u{0301}e\u{0301}e\u{0301}e\u{0301}";
654        assert_eq!(seven.chars().count(), 14);
655        assert_eq!(
656            protect(&secret(), seven).unwrap_err(),
657            KeyringError::PassphraseTooShort(MIN_PASSPHRASE_LEN)
658        );
659    }
660
661    #[test]
662    fn rejects_short_passphrases_and_foreign_files() {
663        assert_eq!(
664            protect(&secret(), "short").unwrap_err(),
665            KeyringError::PassphraseTooShort(MIN_PASSPHRASE_LEN)
666        );
667        assert_eq!(
668            error_of(unprotect(b"not a key file", "whatever")),
669            KeyringError::NotAKeyFile
670        );
671        assert_eq!(
672            error_of(unprotect(MAGIC, "whatever")),
673            KeyringError::Malformed
674        );
675    }
676
677    #[test]
678    fn refuses_a_file_demanding_absurd_memory() -> Result<(), KeyringError> {
679        let mut sealed = protect(&secret(), "correct horse battery")?;
680        sealed[10..14].copy_from_slice(&u32::MAX.to_be_bytes());
681        assert_eq!(
682            error_of(unprotect(&sealed, "correct horse battery")),
683            KeyringError::UnreasonableParameters
684        );
685        Ok(())
686    }
687
688    // Issue #6: the nightly fuzzer produced this file, which the old 4 GiB
689    // ceiling accepted and which then asked the allocator for 2.37 GiB
690    // (p_cost = 83, m_cost = 2 490 368 KiB). Pinned byte-for-byte so the fix
691    // is measured against the real input, not a hand-made approximation.
692    #[test]
693    fn refuses_the_fuzzer_reproducer_before_allocating() {
694        const REPRODUCER: [u8; SEALED_LEN] = [
695            0x48, 0x49, 0x44, 0x45, 0x2d, 0x4b, 0x45, 0x59, 0x02, 0x53, 0x00, 0x26, 0x00, 0x00,
696            0x00, 0x00, 0x00, 0x01, 0x2b, 0x2b, 0x55, 0x55, 0x55, 0x55, 0xff, 0xff, 0xff, 0xff,
697            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x55, 0x00, 0x01, 0x00,
698            0x00, 0x00, 0x00, 0x00, 0x01, 0x2b, 0x2b, 0x55, 0x55, 0x55, 0x55, 0xff, 0xff, 0xff,
699            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
700            0xff, 0xff, 0x01, 0x06, 0xff, 0xff, 0xdf, 0xff, 0xff, 0xff, 0xff, 0x03, 0xff, 0xff,
701            0xff, 0xff, 0xbf, 0xff, 0xff, 0xfd, 0xff, 0xff, 0xff, 0xff, 0x55,
702        ];
703        assert_eq!(
704            error_of(unprotect(&REPRODUCER, "correct horse battery")),
705            KeyringError::UnreasonableParameters
706        );
707    }
708
709    #[test]
710    fn refuses_a_file_demanding_absurd_parallelism() -> Result<(), KeyringError> {
711        let mut sealed = protect(&secret(), "correct horse battery")?;
712        sealed[9] = 0xff;
713        assert_eq!(
714            error_of(unprotect(&sealed, "correct horse battery")),
715            KeyringError::UnreasonableParameters
716        );
717        Ok(())
718    }
719
720    // The header is authenticated, so an honest file cannot be downgraded; this
721    // catches a file that was WRITTEN weak, which would otherwise open silently.
722    #[test]
723    fn refuses_a_file_written_with_too_little_memory() -> Result<(), KeyringError> {
724        let mut sealed = protect(&secret(), "correct horse battery")?;
725        sealed[10..14].copy_from_slice(&(MIN_MEMORY_KIB - 1).to_be_bytes());
726        assert_eq!(
727            error_of(unprotect(&sealed, "correct horse battery")),
728            KeyringError::UnreasonableParameters
729        );
730        Ok(())
731    }
732
733    #[test]
734    fn raw_keys_still_open_without_a_passphrase() -> Result<(), KeyringError> {
735        let raw = secret().expose_seed_for_sealing().to_vec();
736        let mut seed = Zeroizing::new([0_u8; SEED_LEN]);
737        seed.copy_from_slice(&raw);
738        let expected = Identity::from_seed(seed).recipient_secret()?;
739        assert_eq!(inspect(&raw), KeyFormat::Raw);
740        // A raw file is a master seed, so the encryption key is derived from
741        // it. Reading the bytes as the key itself is what broke CLI/SDK
742        // interoperability: every surface must agree with the CLI here.
743        assert_eq!(
744            open(&raw, None)?.public_key()?.to_bytes(),
745            expected.public_key()?.to_bytes()
746        );
747        assert_ne!(open(&raw, None)?.expose_seed_for_sealing(), raw);
748        assert_eq!(
749            error_of(open(&protect(&secret(), "correct horse battery")?, None)),
750            KeyringError::WrongPassphrase
751        );
752        Ok(())
753    }
754
755    /// A key file written by v0.4.0 has no purpose byte. It must still open, or
756    /// every existing user loses access to their encrypted data.
757    #[test]
758    fn v1_key_files_still_open_and_read_as_encryption_only() -> Result<(), KeyringError> {
759        // Rebuild a v1 file exactly as the previous release wrote it.
760        let seed = [0x31; SEED_LEN];
761        let salt = [0x32; SALT_LEN];
762        let nonce = [0x33; NONCE_LEN];
763        let mut header = Vec::new();
764        header.extend_from_slice(MAGIC);
765        header.push(LEGACY_VERSION);
766        header.push(PARALLELISM as u8);
767        header.extend_from_slice(&MEMORY_KIB.to_be_bytes());
768        header.extend_from_slice(&ITERATIONS.to_be_bytes());
769        header.extend_from_slice(&salt);
770        header.extend_from_slice(&nonce);
771        assert_eq!(header.len(), LEGACY_HEADER_LEN);
772
773        let wrapping = derive(
774            "correct horse battery",
775            &salt,
776            MEMORY_KIB,
777            ITERATIONS,
778            PARALLELISM,
779        )?;
780        let sealed = ChaCha20Poly1305::new((&*wrapping).into())
781            .encrypt(
782                (&nonce).into(),
783                Payload {
784                    msg: &seed,
785                    aad: &header,
786                },
787            )
788            .map_err(|_| CryptoError::Authentication)?;
789        let mut file = header;
790        file.extend_from_slice(&sealed);
791        assert_eq!(file.len(), LEGACY_SEALED_LEN);
792
793        let (opened, purpose) = unprotect_seed(&file, "correct horse battery")?;
794        assert_eq!(&opened[..], &seed);
795        assert_eq!(purpose, KeyPurpose::Encryption);
796        // And through the typed path that predates this change.
797        unprotect(&file, "correct horse battery")?;
798        Ok(())
799    }
800
801    #[test]
802    fn an_identity_key_is_refused_where_an_encryption_key_is_required() -> Result<(), KeyringError>
803    {
804        let identity = Identity::generate()?;
805        let file = protect_identity(identity.expose_seed_for_sealing(), "correct horse battery")?;
806        assert_eq!(
807            error_of(unprotect(&file, "correct horse battery")),
808            KeyringError::WrongPurpose {
809                expected: KeyPurpose::Encryption,
810                found: KeyPurpose::Identity,
811            }
812        );
813        Ok(())
814    }
815
816    #[test]
817    fn an_identity_round_trips_and_derives_stable_keys() -> Result<(), KeyringError> {
818        let identity = Identity::generate()?;
819        let file = protect_identity(identity.expose_seed_for_sealing(), "correct horse battery")?;
820        let (seed, purpose) = unprotect_seed(&file, "correct horse battery")?;
821        assert_eq!(purpose, KeyPurpose::Identity);
822
823        let reopened = Identity::from_seed(seed);
824        assert_eq!(
825            reopened.recipient_secret()?.public_key()?.to_bytes(),
826            identity.recipient_secret()?.public_key()?.to_bytes()
827        );
828        assert_eq!(&*reopened.signing_seed(), &*identity.signing_seed());
829        Ok(())
830    }
831
832    /// The point of deriving both from one master: neither derived key may equal
833    /// the master, or each other, or the whole separation is decorative.
834    #[test]
835    fn the_two_derived_keys_are_independent_of_each_other_and_the_master()
836    -> Result<(), KeyringError> {
837        let identity = Identity::generate()?;
838        let master = *identity.expose_seed_for_sealing();
839        let signing = identity.signing_seed();
840        let encryption = identity.derive(ENCRYPTION_INFO);
841
842        assert_ne!(&*signing, &master);
843        assert_ne!(&*encryption, &master);
844        assert_ne!(&*signing, &*encryption);
845        Ok(())
846    }
847
848    #[test]
849    fn public_key_armor_round_trips() -> Result<(), KeyringError> {
850        let public = secret().public_key()?.to_bytes();
851        let armored = encode_public(&public);
852        assert!(armored.starts_with("hide-public-key:"));
853        assert!(armored.lines().skip(1).all(|line| line.len() <= 64));
854        assert_eq!(decode_public(&armored)?, public);
855        assert!(decode_public("hide-public-key:\n!!!not base64!!!").is_err());
856        Ok(())
857    }
858}