Skip to main content

mnemo_engine/keys/
mod.rs

1//! 12.3: keys (`docs/design/12.3-keys.md`).
2//!
3//! The parts `mnemo init`, `recovery-code`, `rekey` and, later, `onboard`,
4//! `unlock` and the MCP server are made of:
5//! - [`recovery`]: the recovery code's encoder and parser;
6//! - [`KeyStore`]: where a brain's secret is kept, found by its salt;
7//! - [`resolve`]: the chain of key sources, picked by the file's kind;
8//! - [`create_generated`] and [`rekey_stored`]: the orders that keep a
9//!   secret that opens the file at every step;
10//! - [`display`]: the rule for showing a recovery code.
11//!
12//! The OS keychain store arrives in step 2. Until then
13//! [`default_store`] is `None` in a release build.
14
15pub mod display;
16#[cfg(all(
17    feature = "keychain",
18    any(target_os = "macos", target_os = "windows", target_os = "linux")
19))]
20mod os_store;
21pub mod recovery;
22
23use std::io::Read;
24use std::path::{Path, PathBuf};
25use std::time::Duration;
26
27use zeroize::Zeroizing;
28
29pub use crate::crypto::SecretKind;
30use crate::crypto::{KdfParams, SALT_LEN};
31use crate::error::{MnemoError, Result};
32use crate::format::{Header, PAGE_SIZE};
33use crate::store::{Mnemo, MnemoConfig};
34
35/// A secret that opens a brain.
36pub enum Secret {
37    /// A passphrase a person chose.
38    Passphrase(Zeroizing<String>),
39    /// A raw 256-bit key.
40    Key(Zeroizing<[u8; 32]>),
41}
42
43impl Secret {
44    /// Which kind it is.
45    pub fn kind(&self) -> SecretKind {
46        match self {
47            Secret::Passphrase(_) => SecretKind::Passphrase,
48            Secret::Key(_) => SecretKind::Key,
49        }
50    }
51
52    fn bytes(&self) -> &[u8] {
53        match self {
54            Secret::Passphrase(p) => p.as_bytes(),
55            Secret::Key(k) => &k[..],
56        }
57    }
58}
59
60/// What a brain's page 0 says about its key, read without the key.
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub struct FileKeyInfo {
63    /// The salt, which names the brain's keychain entry.
64    pub salt: [u8; SALT_LEN],
65    /// The KDF parameters.
66    pub kdf: KdfParams,
67    /// The kind of secret the parameters say it takes: raw-key parameters
68    /// mean a key, anything else a passphrase.
69    pub kind: SecretKind,
70}
71
72/// Read the salt and KDF parameters from `path`'s page 0, with no key and
73/// no lock. A torn page 0 is an error here (step 2 adds the salts from the
74/// WAL's header frames).
75pub fn file_info(path: impl AsRef<Path>) -> Result<FileKeyInfo> {
76    let mut file = std::fs::File::open(path.as_ref())?;
77    let mut page = [0u8; PAGE_SIZE];
78    file.read_exact(&mut page)?;
79    let h = Header::from_page(&page)?;
80    let kdf = KdfParams {
81        m_cost: h.m_cost,
82        t_cost: h.t_cost,
83        p_cost: h.p_cost,
84    };
85    Ok(FileKeyInfo {
86        salt: h.salt,
87        kdf,
88        kind: if kdf.below_passphrase_floor() {
89            SecretKind::Key
90        } else {
91            SecretKind::Passphrase
92        },
93    })
94}
95
96/// The lower-case hex of `bytes`.
97pub fn hex(bytes: &[u8]) -> String {
98    bytes.iter().map(|b| format!("{b:02x}")).collect()
99}
100
101// --- The key store ----------------------------------------------------------
102
103/// A secret as a key store keeps it, typed so an entry is never guessed.
104pub enum StoredSecret {
105    /// A key: `key:` and 64 hex digits.
106    Key(Zeroizing<[u8; 32]>),
107    /// A passphrase: `passphrase:` and the passphrase.
108    Passphrase(Zeroizing<String>),
109}
110
111impl StoredSecret {
112    /// The entry's text.
113    pub fn encode(&self) -> Zeroizing<String> {
114        match self {
115            StoredSecret::Key(k) => Zeroizing::new(format!("key:{}", hex(&k[..]))),
116            StoredSecret::Passphrase(p) => Zeroizing::new(format!("passphrase:{}", p.as_str())),
117        }
118    }
119
120    /// Read an entry's text back.
121    pub fn decode(text: &str) -> Result<StoredSecret> {
122        if let Some(h) = text.strip_prefix("key:") {
123            return parse_hex_key(h)
124                .map(StoredSecret::Key)
125                .ok_or_else(|| MnemoError::Invalid("a key entry that isn't 64 hex digits".into()));
126        }
127        if let Some(p) = text.strip_prefix("passphrase:") {
128            return Ok(StoredSecret::Passphrase(Zeroizing::new(p.to_string())));
129        }
130        Err(MnemoError::Invalid(
131            "a key-store entry of an unknown type".into(),
132        ))
133    }
134
135    fn same_as(&self, other: &StoredSecret) -> bool {
136        self.encode() == other.encode()
137    }
138
139    /// As a [`Secret`].
140    pub fn into_secret(self) -> Secret {
141        match self {
142            StoredSecret::Key(k) => Secret::Key(k),
143            StoredSecret::Passphrase(p) => Secret::Passphrase(p),
144        }
145    }
146
147    fn from_secret(s: &Secret) -> StoredSecret {
148        match s {
149            Secret::Key(k) => StoredSecret::Key(k.clone()),
150            Secret::Passphrase(p) => StoredSecret::Passphrase(p.clone()),
151        }
152    }
153}
154
155/// Where brains' secrets are kept, each found by its brain's salt: the OS
156/// keychain (the `keychain` feature), or the test store.
157pub trait KeyStore {
158    /// How to name it to a person ("the test key store at …").
159    fn describe(&self) -> String;
160    /// The entry for `salt`, if there is one.
161    fn get(&self, salt: &[u8; SALT_LEN]) -> Result<Option<StoredSecret>>;
162    /// Store `secret` under `salt`, replacing any entry. `label` is for a
163    /// person browsing the store (the brain's path); nothing looks it up.
164    fn put(&self, salt: &[u8; SALT_LEN], secret: &StoredSecret, label: &str) -> Result<()>;
165    /// Remove the entry for `salt`, if there is one.
166    fn delete(&self, salt: &[u8; SALT_LEN]) -> Result<()>;
167    /// Whether an entry is known to be on disk when [`KeyStore::put`]
168    /// returns. None of the OS stores documents it, so the default is
169    /// `false`, and the keys note's section 4 rule applies: a new key the
170    /// display rule can't show isn't left in the store alone.
171    fn durable(&self) -> bool {
172        false
173    }
174    /// Whether the store can be used here at all: an error says why not
175    /// (no Secret Service on the session bus, no access). It reads one
176    /// entry that never exists, so it asks nothing of the user.
177    fn check_available(&self) -> Result<()> {
178        Ok(())
179    }
180}
181
182/// **Tests only.** A key store in a directory, one 0600 file per salt.
183/// [`default_store`] uses it when `MNEMO_DEV_KEYSTORE` names a directory,
184/// which only a `dev-hooks` build reads. Never in a release build.
185#[cfg(feature = "dev-hooks")]
186#[doc(hidden)]
187pub struct DirKeyStore {
188    dir: PathBuf,
189}
190
191#[cfg(feature = "dev-hooks")]
192impl DirKeyStore {
193    /// A store in `dir`, which must exist.
194    pub fn new(dir: impl Into<PathBuf>) -> DirKeyStore {
195        DirKeyStore { dir: dir.into() }
196    }
197
198    fn entry(&self, salt: &[u8; SALT_LEN]) -> PathBuf {
199        self.dir.join(hex(salt))
200    }
201}
202
203#[cfg(feature = "dev-hooks")]
204impl KeyStore for DirKeyStore {
205    fn describe(&self) -> String {
206        format!("the test key store at {}", self.dir.display())
207    }
208
209    fn get(&self, salt: &[u8; SALT_LEN]) -> Result<Option<StoredSecret>> {
210        match std::fs::read_to_string(self.entry(salt)) {
211            Ok(text) => StoredSecret::decode(Zeroizing::new(text).trim_end()).map(Some),
212            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
213            Err(e) => Err(MnemoError::Io(std::io::Error::other(format!(
214                "{} (reading): {e}",
215                self.describe()
216            )))),
217        }
218    }
219
220    fn put(&self, salt: &[u8; SALT_LEN], secret: &StoredSecret, _label: &str) -> Result<()> {
221        use std::io::Write;
222        let path = self.entry(salt);
223        let tmp = self.dir.join(format!("{}.tmp", hex(salt)));
224        let mut o = std::fs::OpenOptions::new();
225        o.write(true).create(true).truncate(true);
226        #[cfg(unix)]
227        std::os::unix::fs::OpenOptionsExt::mode(&mut o, 0o600);
228        let mut f = o.open(&tmp)?;
229        f.write_all(secret.encode().as_bytes())?;
230        f.sync_all()?;
231        std::fs::rename(&tmp, &path)?;
232        Ok(())
233    }
234
235    fn delete(&self, salt: &[u8; SALT_LEN]) -> Result<()> {
236        match std::fs::remove_file(self.entry(salt)) {
237            Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e.into()),
238            _ => Ok(()),
239        }
240    }
241
242    /// Each entry is written to a temp file, synced and renamed. A test can
243    /// make it say otherwise with `MNEMO_DEV_KEYSTORE_NOT_DURABLE`, to stand
244    /// in for an OS store.
245    fn durable(&self) -> bool {
246        std::env::var_os("MNEMO_DEV_KEYSTORE_NOT_DURABLE").is_none()
247    }
248}
249
250/// The key store this build uses, if it has one: in a `dev-hooks` build,
251/// the directory `MNEMO_DEV_KEYSTORE` names when it's set; otherwise the OS
252/// keychain when the `keychain` feature is on (macOS, Windows, Linux).
253/// `None` otherwise. Making one asks nothing of the store: whether it can be
254/// used shows at the first lookup, or through
255/// [`KeyStore::check_available`].
256pub fn default_store() -> Option<Box<dyn KeyStore>> {
257    #[cfg(feature = "dev-hooks")]
258    {
259        if let Some(dir) = std::env::var_os("MNEMO_DEV_KEYSTORE").filter(|d| !d.is_empty()) {
260            return Some(Box::new(DirKeyStore::new(PathBuf::from(dir))));
261        }
262        // A test that wants no store at all, in a `keychain` build, so it
263        // never reaches the real keychain of whoever runs it.
264        if std::env::var_os("MNEMO_DEV_NO_KEYCHAIN").is_some() {
265            return None;
266        }
267    }
268    #[cfg(all(
269        feature = "keychain",
270        any(target_os = "macos", target_os = "windows", target_os = "linux")
271    ))]
272    return Some(Box::new(os_store::OsKeyStore));
273    #[allow(unreachable_code)]
274    None
275}
276
277/// The keychain's service name for every brain's entry; the account is the
278/// brain's salt in lower-case hex (the keys note, section 4).
279pub const KEYCHAIN_SERVICE: &str = "io.github.toarchkumar.mnemo.brain";
280
281/// Store `secret` under `salt`, then read it back. A store that doesn't
282/// give back what it was given has its entry removed, and the call fails.
283pub fn store_and_check(
284    store: &dyn KeyStore,
285    salt: &[u8; SALT_LEN],
286    secret: &StoredSecret,
287    label: &str,
288) -> Result<()> {
289    store.put(salt, secret, label)?;
290    match store.get(salt) {
291        Ok(Some(back)) if back.same_as(secret) => Ok(()),
292        other => {
293            let _ = store.delete(salt);
294            Err(MnemoError::Invalid(format!(
295                "{} didn't give back the entry it was just given{}; nothing was changed",
296                store.describe(),
297                match other {
298                    Err(e) => format!(" ({e})"),
299                    _ => String::new(),
300                }
301            )))
302        }
303    }
304}
305
306// --- Keys as text, key files, the key command --------------------------------
307
308fn parse_hex_key(h: &str) -> Option<Zeroizing<[u8; 32]>> {
309    let h = h.trim();
310    if h.len() != 64 || !h.bytes().all(|b| b.is_ascii_hexdigit()) {
311        return None;
312    }
313    let mut k = Zeroizing::new([0u8; 32]);
314    for (i, byte) in k.iter_mut().enumerate() {
315        *byte = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).ok()?;
316    }
317    Some(k)
318}
319
320/// A key written as text: 64 hex digits, or a recovery code. `what` names
321/// where it came from, for the error.
322pub fn parse_key_text(text: &str, what: &str) -> Result<Zeroizing<[u8; 32]>> {
323    if let Some(k) = parse_hex_key(text) {
324        return Ok(k);
325    }
326    if recovery::looks_like_code(text) {
327        return recovery::parse(text).map_err(|e| MnemoError::Invalid(format!("{what}: {e}")));
328    }
329    Err(MnemoError::Invalid(format!(
330        "{what} holds neither 64 hex digits nor a recovery code"
331    )))
332}
333
334/// Read a key file: 32 raw bytes, 64 hex digits, or a recovery code. On
335/// Unix it must be a regular file this user owns, with no access for group
336/// or others, as `ssh` asks of a private key (the keys note, section 6).
337pub fn read_key_file(path: impl AsRef<Path>) -> Result<Zeroizing<[u8; 32]>> {
338    let path = path.as_ref();
339    let meta = std::fs::metadata(path).map_err(|e| {
340        MnemoError::Invalid(format!("reading the key file {}: {e}", path.display()))
341    })?;
342    if !meta.is_file() {
343        return Err(MnemoError::Invalid(format!(
344            "the key file {} isn't a regular file",
345            path.display()
346        )));
347    }
348    #[cfg(unix)]
349    {
350        use std::os::unix::fs::MetadataExt;
351        if meta.uid() != rustix::process::geteuid().as_raw() {
352            return Err(MnemoError::Invalid(format!(
353                "refusing the key file {}: another user owns it; give it to this user, then \
354                 `chmod 600 {}`",
355                path.display(),
356                path.display()
357            )));
358        }
359        let mode = meta.mode() & 0o777;
360        if mode & 0o077 != 0 {
361            return Err(MnemoError::Invalid(format!(
362                "refusing the key file {}: group or others can read it (mode {mode:o}); run \
363                 `chmod 600 {}`",
364                path.display(),
365                path.display()
366            )));
367        }
368    }
369    let bytes = Zeroizing::new(std::fs::read(path).map_err(|e| {
370        MnemoError::Invalid(format!("reading the key file {}: {e}", path.display()))
371    })?);
372    if bytes.len() == 32 {
373        let mut k = Zeroizing::new([0u8; 32]);
374        k.copy_from_slice(&bytes);
375        return Ok(k);
376    }
377    let text = Zeroizing::new(String::from_utf8_lossy(&bytes).into_owned());
378    if let Some(k) = parse_hex_key(&text) {
379        return Ok(k);
380    }
381    if recovery::looks_like_code(&text) {
382        // A code's own error names the group that's wrong.
383        return parse_key_text(&text, &format!("the key file {}", path.display()));
384    }
385    Err(MnemoError::Invalid(format!(
386        "{}: a key file holds 32 raw bytes, 64 hex digits or a recovery code",
387        path.display()
388    )))
389}
390
391/// Write a new key file: created new (never over an existing name, a
392/// symlink included) with mode 0600, holding the key's 64 hex digits.
393pub fn write_new_key_file(path: impl AsRef<Path>, key: &[u8; 32]) -> Result<()> {
394    use std::io::Write;
395    let path = path.as_ref();
396    let mut o = std::fs::OpenOptions::new();
397    o.write(true).create_new(true);
398    #[cfg(unix)]
399    std::os::unix::fs::OpenOptionsExt::mode(&mut o, 0o600);
400    let mut f = o.open(path).map_err(|e| {
401        MnemoError::Invalid(format!("creating the key file {}: {e}", path.display()))
402    })?;
403    let text = Zeroizing::new(format!("{}\n", hex(key)));
404    f.write_all(text.as_bytes())?;
405    f.sync_all()?;
406    Ok(())
407}
408
409/// The most a key command may print.
410const COMMAND_OUTPUT_CAP: usize = 4096;
411
412/// The environment variables that carry a brain's secret. The embed command
413/// and the key command start with them removed from their environment: they
414/// need the text to embed or their own credentials, never the brain's.
415pub(crate) const SECRET_ENV_VARS: [&str; 4] = [
416    "MNEMO_PASSPHRASE",
417    "MNEMO_KEY",
418    "MNEMO_KEY_FILE",
419    "MNEMO_KEY_COMMAND",
420];
421
422/// Run `cmd` (split as `--embed-cmd` is, no shell) and read a key from the
423/// first line of its output (the keys note, section 6): stdin closed,
424/// stderr passed through, stdout capped at 4 KiB, its exit status checked,
425/// and killed after `timeout`.
426pub fn run_key_command(cmd: &str, timeout: Duration) -> Result<Zeroizing<[u8; 32]>> {
427    use std::process::{Command, Stdio};
428    let argv = crate::embed_cmd::shlex_split(cmd)
429        .filter(|a| !a.is_empty())
430        .ok_or_else(|| MnemoError::Invalid("MNEMO_KEY_COMMAND is empty or badly quoted".into()))?;
431    let mut command = Command::new(&argv[0]);
432    for var in SECRET_ENV_VARS {
433        command.env_remove(var);
434    }
435    let mut child = command
436        .args(&argv[1..])
437        .stdin(Stdio::null())
438        .stdout(Stdio::piped())
439        .stderr(Stdio::inherit())
440        .spawn()
441        .map_err(|e| MnemoError::Invalid(format!("the key command didn't start: {e}")))?;
442    let mut out = child.stdout.take().expect("piped stdout");
443    let (tx, rx) = std::sync::mpsc::channel();
444    std::thread::spawn(move || {
445        let mut buf = Zeroizing::new(Vec::new());
446        let r = (&mut out)
447            .take(COMMAND_OUTPUT_CAP as u64 + 1)
448            .read_to_end(&mut buf);
449        let _ = tx.send((r, buf));
450    });
451    let start = std::time::Instant::now();
452    let fail = |child: &mut std::process::Child, msg: String| {
453        let _ = child.kill();
454        let _ = child.wait();
455        Err(MnemoError::Invalid(msg))
456    };
457    let buf = match rx.recv_timeout(timeout) {
458        Ok((Ok(_), buf)) => buf,
459        Ok((Err(e), _)) => {
460            return fail(&mut child, format!("reading the key command's output: {e}"))
461        }
462        Err(_) => {
463            return fail(
464                &mut child,
465                format!(
466                    "the key command didn't answer within {} s",
467                    timeout.as_secs()
468                ),
469            )
470        }
471    };
472    if buf.len() > COMMAND_OUTPUT_CAP {
473        return fail(
474            &mut child,
475            "the key command printed more than 4 KiB".to_string(),
476        );
477    }
478    let status = loop {
479        match child.try_wait()? {
480            Some(s) => break s,
481            None if start.elapsed() >= timeout => {
482                return fail(
483                    &mut child,
484                    format!(
485                        "the key command didn't answer within {} s",
486                        timeout.as_secs()
487                    ),
488                )
489            }
490            None => std::thread::sleep(Duration::from_millis(10)),
491        }
492    };
493    if !status.success() {
494        return Err(MnemoError::Invalid(format!(
495            "the key command failed ({status})"
496        )));
497    }
498    let text = Zeroizing::new(String::from_utf8_lossy(&buf).into_owned());
499    let line = text.lines().next().unwrap_or("").trim();
500    if line.is_empty() {
501        return Err(MnemoError::Invalid(
502            "the key command printed nothing".into(),
503        ));
504    }
505    parse_key_text(line, "the key command's output")
506}
507
508// --- The chain ---------------------------------------------------------------
509
510/// The key command's timeout in the CLI.
511pub const CLI_COMMAND_TIMEOUT: Duration = Duration::from_secs(60);
512/// The key command's timeout in the MCP server, which has no terminal.
513pub const SERVER_COMMAND_TIMEOUT: Duration = Duration::from_secs(10);
514
515/// Where a secret came from.
516#[derive(Clone, Debug, PartialEq, Eq)]
517pub enum Source {
518    /// `MNEMO_PASSPHRASE`.
519    EnvPassphrase,
520    /// `MNEMO_KEY`.
521    EnvKey,
522    /// `MNEMO_KEY_FILE`.
523    KeyFile(PathBuf),
524    /// `MNEMO_KEY_COMMAND`.
525    KeyCommand,
526    /// A key-store entry; the text describes the store.
527    Store(String),
528}
529
530impl std::fmt::Display for Source {
531    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
532        match self {
533            Source::EnvPassphrase => f.write_str("MNEMO_PASSPHRASE"),
534            Source::EnvKey => f.write_str("MNEMO_KEY"),
535            Source::KeyFile(p) => write!(f, "MNEMO_KEY_FILE ({})", p.display()),
536            Source::KeyCommand => f.write_str("MNEMO_KEY_COMMAND"),
537            Source::Store(s) => write!(f, "this brain's entry in {s}"),
538        }
539    }
540}
541
542/// What [`resolve`] found.
543pub struct Resolved {
544    /// The secret.
545    pub secret: Secret,
546    /// Where it came from.
547    pub source: Source,
548    /// The next source of the same kind, for the error when this one
549    /// doesn't open the file: the next environment source that's present,
550    /// or the key store, which isn't looked up (it may have no entry).
551    pub next: Option<Source>,
552    /// Sources that were skipped, and why, to show the user.
553    pub notes: Vec<String>,
554}
555
556/// The chain's answer.
557pub enum Resolution {
558    /// A source was present and gave a secret.
559    Found(Resolved),
560    /// No source was present. `kind` is the file's kind (the CLI then
561    /// prompts for a passphrase file, at a terminal).
562    NoSource {
563        /// The file's kind.
564        kind: SecretKind,
565        /// Sources that were skipped, to show the user.
566        notes: Vec<String>,
567    },
568}
569
570fn env_set(name: &str) -> Option<String> {
571    std::env::var(name).ok().filter(|v| !v.is_empty())
572}
573
574fn kind_word(k: SecretKind) -> &'static str {
575    match k {
576        SecretKind::Key => "a key",
577        SecretKind::Passphrase => "a passphrase",
578    }
579}
580
581/// Find the secret for the brain at `path` (the keys note, section 6).
582///
583/// It reads the file's KDF parameters first, with no key: raw-key
584/// parameters make it a key file, anything else a passphrase file. It takes
585/// the first present source of that kind: `MNEMO_KEY`, `MNEMO_KEY_FILE`,
586/// `MNEMO_KEY_COMMAND`, the key store, for a key; `MNEMO_PASSPHRASE`, a
587/// passphrase entry in the key store, for a passphrase. A present source of
588/// the other kind is named in [`Resolved::notes`] as skipped. With no source
589/// of the file's kind, the first present source of the other kind is used,
590/// once (for a key file, only a passphrase source). Nothing is tried: the
591/// caller opens with what comes back.
592///
593/// **The key store is looked up last, and only when it's needed** (step
594/// 2): when no earlier source of the file's kind is present, or for the one
595/// try of the other kind. So a keychain that would ask the user something,
596/// or can't be reached at all, is never touched when `MNEMO_KEY` answers. A
597/// store error is a note when another source answers, and the error only
598/// when the store was the one left.
599///
600/// **When page 0 doesn't parse,** the salts and the kind come from the
601/// header frames in the file's write-ahead log (newest first), and the
602/// store is looked up under each in turn; the open that follows heals the
603/// header. With neither, the kind is unknown: the first environment source
604/// present is used.
605pub fn resolve(
606    path: impl AsRef<Path>,
607    store: Option<&dyn KeyStore>,
608    command_timeout: Duration,
609) -> Result<Resolution> {
610    let path = path.as_ref();
611    let file_name = path.display().to_string();
612    let mut notes = Vec::new();
613    let (kind, salts) = match file_info(path) {
614        Ok(i) => (Some(i.kind), vec![i.salt]),
615        Err(_) => match crate::store::wal_header_salts(path) {
616            Ok(c) if !c.is_empty() => {
617                notes.push(format!(
618                    "{file_name}'s header couldn't be read; its write-ahead log names {} salt(s) \
619                     to look up",
620                    c.len()
621                ));
622                (
623                    Some(kind_of_kdf(c[0].1)),
624                    c.iter().map(|(s, _)| *s).collect(),
625                )
626            }
627            _ => (None, Vec::new()),
628        },
629    };
630    let env = env_sources();
631    let Some(kind) = kind else {
632        // The kind is unknown, and there's no salt to look up.
633        let Some((src, _)) = env.first().cloned() else {
634            return Ok(Resolution::NoSource {
635                kind: SecretKind::Passphrase,
636                notes,
637            });
638        };
639        notes.push(format!(
640            "{file_name}'s header couldn't be read, so its kind of secret is unknown"
641        ));
642        let secret = fetch(&src, None, command_timeout)?;
643        return Ok(Resolution::Found(Resolved {
644            secret,
645            source: src,
646            next: None,
647            notes,
648        }));
649    };
650    let mine: Vec<&(Source, SecretKind)> = env.iter().filter(|(_, k)| *k == kind).collect();
651    let other: Vec<&(Source, SecretKind)> = env.iter().filter(|(_, k)| *k != kind).collect();
652    let skipped = |notes: &mut Vec<String>, using: &Source| {
653        for (s, k) in &other {
654            notes.push(format!(
655                "{s} holds {}, but {file_name} uses {}; skipped it, using {using}",
656                kind_word(*k),
657                kind_word(kind)
658            ));
659        }
660    };
661    // An environment source of the file's kind: the store isn't touched.
662    if let Some(first) = mine.first() {
663        skipped(&mut notes, &first.0);
664        let secret = fetch(&first.0, None, command_timeout)?;
665        return Ok(Resolution::Found(Resolved {
666            secret,
667            source: first.0.clone(),
668            // The next source of this kind: the next environment one, else
669            // the store, which isn't looked up now (it may have no entry).
670            next: mine
671                .get(1)
672                .map(|(s, _)| s.clone())
673                .or_else(|| store.map(|st| Source::Store(st.describe()))),
674            notes,
675        }));
676    }
677    // The store, last.
678    let looked = match store {
679        None => Ok(None),
680        // Section 8: a store that can't be used here at all (no Secret
681        // Service on the session bus, no access) is no store, and the chain
682        // goes on without it. Any other error is the store's own.
683        Some(st) => match lookup_salts(st, &salts) {
684            Ok(e) => Ok(e.map(|e| (st.describe(), e))),
685            Err(_) if st.check_available().is_err() => Ok(None),
686            Err(e) => Err(e),
687        },
688    };
689    let (store_other, store_error) = match looked {
690        Ok(Some((desc, e))) if stored_kind(&e) == kind => {
691            let src = Source::Store(desc);
692            skipped(&mut notes, &src);
693            return Ok(Resolution::Found(Resolved {
694                secret: e.into_secret(),
695                source: src,
696                next: None,
697                notes,
698            }));
699        }
700        Ok(found) => (found, None),
701        Err(e) => (None, Some(e)),
702    };
703    // No source of the file's kind: the first of the other kind, once.
704    if let Some(first) = other.first() {
705        if let (Some(e), Some(st)) = (&store_error, store) {
706            notes.push(format!("{} couldn't be read ({e})", st.describe()));
707        }
708        notes.push(format!(
709            "{file_name} uses {}, and no source of that kind is set; trying {} once",
710            kind_word(kind),
711            first.0
712        ));
713        let secret = fetch(&first.0, None, command_timeout)?;
714        return Ok(Resolution::Found(Resolved {
715            secret,
716            source: first.0.clone(),
717            next: None,
718            notes,
719        }));
720    }
721    if let Some(e) = store_error {
722        return Err(e);
723    }
724    if let Some((desc, e)) = store_other {
725        let src = Source::Store(desc);
726        notes.push(format!(
727            "{file_name} uses {}, and no source of that kind is set; trying {src} once",
728            kind_word(kind)
729        ));
730        return Ok(Resolution::Found(Resolved {
731            secret: e.into_secret(),
732            source: src,
733            next: None,
734            notes,
735        }));
736    }
737    Ok(Resolution::NoSource { kind, notes })
738}
739
740/// The environment's sources that are present, in the table's order.
741fn env_sources() -> Vec<(Source, SecretKind)> {
742    let mut present = Vec::new();
743    if env_set("MNEMO_PASSPHRASE").is_some() {
744        present.push((Source::EnvPassphrase, SecretKind::Passphrase));
745    }
746    if env_set("MNEMO_KEY").is_some() {
747        present.push((Source::EnvKey, SecretKind::Key));
748    }
749    if let Some(f) = env_set("MNEMO_KEY_FILE") {
750        present.push((Source::KeyFile(PathBuf::from(f)), SecretKind::Key));
751    }
752    if env_set("MNEMO_KEY_COMMAND").is_some() {
753        present.push((Source::KeyCommand, SecretKind::Key));
754    }
755    present
756}
757
758/// The first entry `store` has under any of `salts`, in order.
759fn lookup_salts(store: &dyn KeyStore, salts: &[[u8; SALT_LEN]]) -> Result<Option<StoredSecret>> {
760    for salt in salts {
761        if let Some(e) = store.get(salt)? {
762            return Ok(Some(e));
763        }
764    }
765    Ok(None)
766}
767
768fn stored_kind(e: &StoredSecret) -> SecretKind {
769    match e {
770        StoredSecret::Key(_) => SecretKind::Key,
771        StoredSecret::Passphrase(_) => SecretKind::Passphrase,
772    }
773}
774
775fn kind_of_kdf(kdf: KdfParams) -> SecretKind {
776    if kdf.below_passphrase_floor() {
777        SecretKind::Key
778    } else {
779        SecretKind::Passphrase
780    }
781}
782
783/// Read the secret out of a present source.
784fn fetch(src: &Source, entry: Option<StoredSecret>, timeout: Duration) -> Result<Secret> {
785    Ok(match src {
786        Source::EnvPassphrase => Secret::Passphrase(Zeroizing::new(
787            env_set("MNEMO_PASSPHRASE").unwrap_or_default(),
788        )),
789        Source::EnvKey => {
790            let text = Zeroizing::new(env_set("MNEMO_KEY").unwrap_or_default());
791            Secret::Key(parse_key_text(&text, "MNEMO_KEY")?)
792        }
793        Source::KeyFile(p) => Secret::Key(read_key_file(p)?),
794        Source::KeyCommand => {
795            let cmd = env_set("MNEMO_KEY_COMMAND").unwrap_or_default();
796            Secret::Key(run_key_command(&cmd, timeout)?)
797        }
798        Source::Store(_) => entry
799            .ok_or_else(|| MnemoError::Invalid("the key-store entry went away".into()))?
800            .into_secret(),
801    })
802}
803
804// --- The orders ------------------------------------------------------------
805
806/// [`create_generated`]'s `persist`: keep the key, given the brain's salt.
807pub type Persist<'a> = dyn FnMut(&[u8; SALT_LEN], &[u8; 32]) -> Result<()> + 'a;
808
809/// Create a brain at `path` under a freshly generated key (the keys note,
810/// section 1). In this order, so there's never a brain at `path` whose key
811/// is only in memory:
812/// 1. the key is drawn, and the brain is created under a temp name next to
813///    `path` with the raw-key parameters;
814/// 2. `prepare` runs on it (the CLI writes its manifest), and it's closed;
815/// 3. `persist` keeps the key, given the brain's salt (a key store's
816///    [`store_and_check`], or a new key file);
817/// 4. the temp file takes `path`'s name.
818///
819/// `path` must not exist. Dead `init` temps next to it are removed first.
820/// On an error the temp file is removed.
821pub fn create_generated(
822    path: impl AsRef<Path>,
823    config: MnemoConfig,
824    prepare: &mut dyn FnMut(&mut Mnemo) -> Result<()>,
825    persist: &mut Persist<'_>,
826) -> Result<Zeroizing<[u8; 32]>> {
827    let path = path.as_ref();
828    if std::fs::symlink_metadata(path).is_ok() {
829        return Err(MnemoError::Invalid(format!(
830            "{} already exists; nothing was changed",
831            path.display()
832        )));
833    }
834    crate::store::remove_dead_temps(path, "init");
835    let key = Zeroizing::new(Mnemo::generate_key());
836    let config = MnemoConfig {
837        kdf: KdfParams::raw_key(),
838        ..config
839    };
840    let (tmp, mut db) =
841        crate::store::create_temp(path, "init", &key[..], SecretKind::Key, config, None)?;
842    let result = (|| {
843        prepare(&mut db)?;
844        let salt = db.header_salt();
845        db.close()?;
846        persist(&salt, &key)?;
847        #[cfg(feature = "dev-hooks")]
848        if std::env::var_os("MNEMO_DEV_ABORT_INIT_BEFORE_RENAME").is_some() {
849            std::process::abort();
850        }
851        if std::fs::symlink_metadata(path).is_ok() {
852            return Err(MnemoError::Invalid(format!(
853                "{} appeared while it was being created; nothing was changed there",
854                path.display()
855            )));
856        }
857        std::fs::rename(&tmp, path)?;
858        Ok(())
859    })();
860    match result {
861        Ok(()) => Ok(key),
862        Err(e) => {
863            let _ = std::fs::remove_file(&tmp);
864            Err(e)
865        }
866    }
867}
868
869/// A rekey through [`rekey_stored`] failed. `entries` says what became of
870/// the key-store entries.
871#[derive(Debug)]
872pub struct StoredRekeyError {
873    /// The rekey's error.
874    pub error: MnemoError,
875    /// What became of the entries.
876    pub entries: String,
877    /// Whether the new secret is certainly not in force (the old salt is
878    /// still on disk), so anything written for it can go.
879    pub new_secret_dropped: bool,
880}
881
882impl std::fmt::Display for StoredRekeyError {
883    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
884        write!(f, "{}; {}", self.error, self.entries)
885    }
886}
887
888impl std::error::Error for StoredRekeyError {}
889
890/// Rekey `db` to `new`, keeping it in `store` under the new salt (the keys
891/// note, section 4). The order:
892/// 1. the new salt is drawn;
893/// 2. `new` is stored under it and read back ([`store_and_check`]);
894/// 3. `before_commit` runs (the CLI shows a new key's recovery code here);
895/// 4. the rekey commits;
896/// 5. after an error, page 0 is read again: the new entry is deleted only
897///    if the old salt is still there, and both are kept otherwise.
898///
899/// The old entry is kept: copies of the file made before still use it.
900/// A key gets [`KdfParams::raw_key`]; a passphrase gets
901/// [`KdfParams::for_passphrase`] of the file's parameters. Returns a note
902/// for the user.
903pub fn rekey_stored(
904    db: &mut Mnemo,
905    new: &Secret,
906    store: &dyn KeyStore,
907    label: &str,
908    before_commit: &mut dyn FnMut() -> Result<()>,
909) -> std::result::Result<String, StoredRekeyError> {
910    let old_salt = db.header_salt();
911    let kdf = match new.kind() {
912        SecretKind::Key => KdfParams::raw_key(),
913        SecretKind::Passphrase => db.kdf_params().for_passphrase(),
914    };
915    let stored = StoredSecret::from_secret(new);
916    let mut new_salt: Option<[u8; SALT_LEN]> = None;
917    let r = db.rekey_staged(new.bytes(), new.kind(), kdf, &mut |salt| {
918        store_and_check(store, salt, &stored, label)?;
919        new_salt = Some(*salt);
920        before_commit()
921    });
922    match r {
923        Ok(()) => Ok(format!(
924            "the new secret is in {}; the old entry is still there, for copies of the file \
925             made before this rekey",
926            store.describe()
927        )),
928        Err(error) => {
929            let Some(ns) = new_salt else {
930                return Err(StoredRekeyError {
931                    error,
932                    entries: "the key store wasn't changed".into(),
933                    new_secret_dropped: true,
934                });
935            };
936            // REKEY-1's one exception: page 0 may or may not have landed,
937            // whatever it reads now, so both entries stay.
938            if Mnemo::rekey_left_either_secret(&error) {
939                return Err(StoredRekeyError {
940                    error,
941                    entries: "both entries are kept, since the file may open with either \
942                              secret"
943                        .into(),
944                    new_secret_dropped: false,
945                });
946            }
947            let (entries, new_secret_dropped) = match db.disk_salt() {
948                Ok(s) if s == old_salt => match store.delete(&ns) {
949                    Ok(()) => (
950                        "the old secret is still in force, and the new entry was removed"
951                            .to_string(),
952                        true,
953                    ),
954                    Err(e) => (
955                        format!(
956                            "the old secret is still in force; removing the new entry failed ({e})"
957                        ),
958                        true,
959                    ),
960                },
961                Ok(s) if s == ns => (
962                    "the file may now open only with the new secret, so both entries are kept"
963                        .to_string(),
964                    false,
965                ),
966                _ => (
967                    "the file's header couldn't be read back, so both entries are kept".to_string(),
968                    false,
969                ),
970            };
971            Err(StoredRekeyError {
972                error,
973                entries,
974                new_secret_dropped,
975            })
976        }
977    }
978}
979
980/// The text `mnemo info` shows for a file's KDF parameters, when they need
981/// a word: raw-key parameters with a passphrase, or test-grade ones.
982pub fn kdf_grade_note(kdf: KdfParams, kind: SecretKind) -> Option<String> {
983    if kind == SecretKind::Passphrase && kdf.below_passphrase_floor() {
984        return Some(
985            "below the passphrase floor: a passphrase on raw-key KDF parameters; `mnemo rekey` \
986             or `mnemo compact` raises them"
987                .into(),
988        );
989    }
990    if kdf.is_test_grade() {
991        return Some("test-grade KDF parameters".into());
992    }
993    None
994}