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        // A keychain that keeps a reader waiting (an open permission
211        // dialog), for KEYCHAIN-REPROMPT's note.
212        if let Some(ms) = std::env::var("MNEMO_DEV_KEYSTORE_DELAY_MS")
213            .ok()
214            .and_then(|v| v.parse::<u64>().ok())
215        {
216            std::thread::sleep(Duration::from_millis(ms));
217        }
218        match std::fs::read_to_string(self.entry(salt)) {
219            Ok(text) => StoredSecret::decode(Zeroizing::new(text).trim_end()).map(Some),
220            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
221            Err(e) => Err(MnemoError::Io(std::io::Error::other(format!(
222                "{} (reading): {e}",
223                self.describe()
224            )))),
225        }
226    }
227
228    fn put(&self, salt: &[u8; SALT_LEN], secret: &StoredSecret, _label: &str) -> Result<()> {
229        use std::io::Write;
230        let path = self.entry(salt);
231        let tmp = self.dir.join(format!("{}.tmp", hex(salt)));
232        let mut o = std::fs::OpenOptions::new();
233        o.write(true).create(true).truncate(true);
234        #[cfg(unix)]
235        std::os::unix::fs::OpenOptionsExt::mode(&mut o, 0o600);
236        let mut f = o.open(&tmp)?;
237        f.write_all(secret.encode().as_bytes())?;
238        f.sync_all()?;
239        std::fs::rename(&tmp, &path)?;
240        Ok(())
241    }
242
243    fn delete(&self, salt: &[u8; SALT_LEN]) -> Result<()> {
244        match std::fs::remove_file(self.entry(salt)) {
245            Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e.into()),
246            _ => Ok(()),
247        }
248    }
249
250    /// Each entry is written to a temp file, synced and renamed. A test can
251    /// make it say otherwise with `MNEMO_DEV_KEYSTORE_NOT_DURABLE`, to stand
252    /// in for an OS store.
253    fn durable(&self) -> bool {
254        std::env::var_os("MNEMO_DEV_KEYSTORE_NOT_DURABLE").is_none()
255    }
256}
257
258/// The key store this build uses, if it has one: in a `dev-hooks` build,
259/// the directory `MNEMO_DEV_KEYSTORE` names when it's set; otherwise the OS
260/// keychain when the `keychain` feature is on (macOS, Windows, Linux).
261/// `None` otherwise. Making one asks nothing of the store: whether it can be
262/// used shows at the first lookup, or through
263/// [`KeyStore::check_available`].
264pub fn default_store() -> Option<Box<dyn KeyStore>> {
265    #[cfg(feature = "dev-hooks")]
266    {
267        if let Some(dir) = std::env::var_os("MNEMO_DEV_KEYSTORE").filter(|d| !d.is_empty()) {
268            return Some(Box::new(DirKeyStore::new(PathBuf::from(dir))));
269        }
270        // A test that wants no store at all, in a `keychain` build, so it
271        // never reaches the real keychain of whoever runs it.
272        if std::env::var_os("MNEMO_DEV_NO_KEYCHAIN").is_some() {
273            return None;
274        }
275    }
276    #[cfg(all(
277        feature = "keychain",
278        any(target_os = "macos", target_os = "windows", target_os = "linux")
279    ))]
280    return Some(Box::new(os_store::OsKeyStore));
281    #[allow(unreachable_code)]
282    None
283}
284
285/// The keychain's service name for every brain's entry; the account is the
286/// brain's salt in lower-case hex (the keys note, section 4).
287pub const KEYCHAIN_SERVICE: &str = "io.github.toarchkumar.mnemo.brain";
288
289/// Store `secret` under `salt`, then read it back. A store that doesn't
290/// give back what it was given has its entry removed, and the call fails.
291pub fn store_and_check(
292    store: &dyn KeyStore,
293    salt: &[u8; SALT_LEN],
294    secret: &StoredSecret,
295    label: &str,
296) -> Result<()> {
297    store.put(salt, secret, label)?;
298    match store.get(salt) {
299        Ok(Some(back)) if back.same_as(secret) => Ok(()),
300        other => {
301            let _ = store.delete(salt);
302            Err(MnemoError::Invalid(format!(
303                "{} didn't give back the entry it was just given{}; nothing was changed",
304                store.describe(),
305                match other {
306                    Err(e) => format!(" ({e})"),
307                    _ => String::new(),
308                }
309            )))
310        }
311    }
312}
313
314// --- Keys as text, key files, the key command --------------------------------
315
316fn parse_hex_key(h: &str) -> Option<Zeroizing<[u8; 32]>> {
317    let h = h.trim();
318    if h.len() != 64 || !h.bytes().all(|b| b.is_ascii_hexdigit()) {
319        return None;
320    }
321    let mut k = Zeroizing::new([0u8; 32]);
322    for (i, byte) in k.iter_mut().enumerate() {
323        *byte = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).ok()?;
324    }
325    Some(k)
326}
327
328/// A key written as text: 64 hex digits, or a recovery code. `what` names
329/// where it came from, for the error.
330pub fn parse_key_text(text: &str, what: &str) -> Result<Zeroizing<[u8; 32]>> {
331    if let Some(k) = parse_hex_key(text) {
332        return Ok(k);
333    }
334    if recovery::looks_like_code(text) {
335        return recovery::parse(text).map_err(|e| MnemoError::Invalid(format!("{what}: {e}")));
336    }
337    Err(MnemoError::Invalid(format!(
338        "{what} holds neither 64 hex digits nor a recovery code"
339    )))
340}
341
342/// Read a key file: 32 raw bytes, 64 hex digits, or a recovery code. On
343/// Unix it must be a regular file this user owns, with no access for group
344/// or others, as `ssh` asks of a private key (the keys note, section 6).
345pub fn read_key_file(path: impl AsRef<Path>) -> Result<Zeroizing<[u8; 32]>> {
346    let path = path.as_ref();
347    let meta = std::fs::metadata(path).map_err(|e| {
348        MnemoError::Invalid(format!("reading the key file {}: {e}", path.display()))
349    })?;
350    if !meta.is_file() {
351        return Err(MnemoError::Invalid(format!(
352            "the key file {} isn't a regular file",
353            path.display()
354        )));
355    }
356    #[cfg(unix)]
357    {
358        use std::os::unix::fs::MetadataExt;
359        if meta.uid() != rustix::process::geteuid().as_raw() {
360            return Err(MnemoError::Invalid(format!(
361                "refusing the key file {}: another user owns it; give it to this user, then \
362                 `chmod 600 {}`",
363                path.display(),
364                path.display()
365            )));
366        }
367        let mode = meta.mode() & 0o777;
368        if mode & 0o077 != 0 {
369            return Err(MnemoError::Invalid(format!(
370                "refusing the key file {}: group or others can read it (mode {mode:o}); run \
371                 `chmod 600 {}`",
372                path.display(),
373                path.display()
374            )));
375        }
376    }
377    let bytes = Zeroizing::new(std::fs::read(path).map_err(|e| {
378        MnemoError::Invalid(format!("reading the key file {}: {e}", path.display()))
379    })?);
380    if bytes.len() == 32 {
381        let mut k = Zeroizing::new([0u8; 32]);
382        k.copy_from_slice(&bytes);
383        return Ok(k);
384    }
385    let text = Zeroizing::new(String::from_utf8_lossy(&bytes).into_owned());
386    if let Some(k) = parse_hex_key(&text) {
387        return Ok(k);
388    }
389    if recovery::looks_like_code(&text) {
390        // A code's own error names the group that's wrong.
391        return parse_key_text(&text, &format!("the key file {}", path.display()));
392    }
393    Err(MnemoError::Invalid(format!(
394        "{}: a key file holds 32 raw bytes, 64 hex digits or a recovery code",
395        path.display()
396    )))
397}
398
399/// Write a new key file: created new (never over an existing name, a
400/// symlink included) with mode 0600, holding the key's 64 hex digits.
401pub fn write_new_key_file(path: impl AsRef<Path>, key: &[u8; 32]) -> Result<()> {
402    use std::io::Write;
403    let path = path.as_ref();
404    let mut o = std::fs::OpenOptions::new();
405    o.write(true).create_new(true);
406    #[cfg(unix)]
407    std::os::unix::fs::OpenOptionsExt::mode(&mut o, 0o600);
408    let mut f = o.open(path).map_err(|e| {
409        MnemoError::Invalid(format!("creating the key file {}: {e}", path.display()))
410    })?;
411    let text = Zeroizing::new(format!("{}\n", hex(key)));
412    f.write_all(text.as_bytes())?;
413    f.sync_all()?;
414    Ok(())
415}
416
417/// The most a key command may print.
418const COMMAND_OUTPUT_CAP: usize = 4096;
419
420/// The environment variables that carry a brain's secret. The embed command
421/// and the key command start with them removed from their environment: they
422/// need the text to embed or their own credentials, never the brain's.
423pub(crate) const SECRET_ENV_VARS: [&str; 4] = [
424    "MNEMO_PASSPHRASE",
425    "MNEMO_KEY",
426    "MNEMO_KEY_FILE",
427    "MNEMO_KEY_COMMAND",
428];
429
430/// Run `cmd` (split as `--embed-cmd` is, no shell) and read a key from the
431/// first line of its output (the keys note, section 6): stdin closed,
432/// stderr passed through, stdout capped at 4 KiB, its exit status checked,
433/// and killed after `timeout`.
434pub fn run_key_command(cmd: &str, timeout: Duration) -> Result<Zeroizing<[u8; 32]>> {
435    use std::process::{Command, Stdio};
436    let argv = crate::embed_cmd::shlex_split(cmd)
437        .filter(|a| !a.is_empty())
438        .ok_or_else(|| MnemoError::Invalid("MNEMO_KEY_COMMAND is empty or badly quoted".into()))?;
439    let mut command = Command::new(&argv[0]);
440    for var in SECRET_ENV_VARS {
441        command.env_remove(var);
442    }
443    let mut child = command
444        .args(&argv[1..])
445        .stdin(Stdio::null())
446        .stdout(Stdio::piped())
447        .stderr(Stdio::inherit())
448        .spawn()
449        .map_err(|e| MnemoError::Invalid(format!("the key command didn't start: {e}")))?;
450    let mut out = child.stdout.take().expect("piped stdout");
451    let (tx, rx) = std::sync::mpsc::channel();
452    std::thread::spawn(move || {
453        let mut buf = Zeroizing::new(Vec::new());
454        let r = (&mut out)
455            .take(COMMAND_OUTPUT_CAP as u64 + 1)
456            .read_to_end(&mut buf);
457        let _ = tx.send((r, buf));
458    });
459    let start = std::time::Instant::now();
460    let fail = |child: &mut std::process::Child, msg: String| {
461        let _ = child.kill();
462        let _ = child.wait();
463        Err(MnemoError::Invalid(msg))
464    };
465    let buf = match rx.recv_timeout(timeout) {
466        Ok((Ok(_), buf)) => buf,
467        Ok((Err(e), _)) => {
468            return fail(&mut child, format!("reading the key command's output: {e}"))
469        }
470        Err(_) => {
471            return fail(
472                &mut child,
473                format!(
474                    "the key command didn't answer within {} s",
475                    timeout.as_secs()
476                ),
477            )
478        }
479    };
480    if buf.len() > COMMAND_OUTPUT_CAP {
481        return fail(
482            &mut child,
483            "the key command printed more than 4 KiB".to_string(),
484        );
485    }
486    let status = loop {
487        match child.try_wait()? {
488            Some(s) => break s,
489            None if start.elapsed() >= timeout => {
490                return fail(
491                    &mut child,
492                    format!(
493                        "the key command didn't answer within {} s",
494                        timeout.as_secs()
495                    ),
496                )
497            }
498            None => std::thread::sleep(Duration::from_millis(10)),
499        }
500    };
501    if !status.success() {
502        return Err(MnemoError::Invalid(format!(
503            "the key command failed ({status})"
504        )));
505    }
506    let text = Zeroizing::new(String::from_utf8_lossy(&buf).into_owned());
507    let line = text.lines().next().unwrap_or("").trim();
508    if line.is_empty() {
509        return Err(MnemoError::Invalid(
510            "the key command printed nothing".into(),
511        ));
512    }
513    parse_key_text(line, "the key command's output")
514}
515
516// --- The chain ---------------------------------------------------------------
517
518/// The key command's timeout in the CLI.
519pub const CLI_COMMAND_TIMEOUT: Duration = Duration::from_secs(60);
520/// The key command's timeout in the MCP server, which has no terminal.
521pub const SERVER_COMMAND_TIMEOUT: Duration = Duration::from_secs(10);
522
523/// What to do when the keychain held the key back (KEYCHAIN-REPROMPT): macOS
524/// ties a keychain item to the program that reads it, so the first read by
525/// a new mnemo (after each upgrade) asks, and a hook or server can't answer.
526pub const KEYCHAIN_ALLOW_HINT: &str = "if the keychain asked whether this mnemo may use the \
527     brain's key, run `mnemo info` in a terminal and choose Always Allow (macOS asks once after \
528     each upgrade)";
529
530/// Whether an error from [`resolve`] came from the key store itself (a
531/// refusal or a failure, never a missing entry, which is
532/// [`Resolution::NoSource`]).
533pub fn is_store_error(e: &MnemoError) -> bool {
534    let t = e.to_string();
535    t.contains(" (reading): ")
536        || t.contains(" (opening it): ")
537        || t.contains(" (opening an entry): ")
538}
539
540/// A note on stderr when the key store hasn't answered within `after`: a
541/// keychain asking whether this program may read the key blocks until
542/// someone answers it (KEYCHAIN-REPROMPT). Dropping the guard cancels it.
543pub struct SlowStoreNote {
544    done: std::sync::Arc<std::sync::atomic::AtomicBool>,
545}
546
547impl SlowStoreNote {
548    /// Print `prefix` and the waiting note after `after`, unless dropped
549    /// first.
550    pub fn after(after: Duration, prefix: &str) -> SlowStoreNote {
551        use std::sync::atomic::{AtomicBool, Ordering};
552        let done = std::sync::Arc::new(AtomicBool::new(false));
553        let seen = done.clone();
554        let prefix = prefix.to_string();
555        // A sleeping thread doesn't keep the process alive.
556        let _ = std::thread::Builder::new()
557            .name("mnemo-keychain-note".into())
558            .spawn(move || {
559                std::thread::sleep(after);
560                if !seen.load(Ordering::SeqCst) {
561                    eprintln!("{prefix}still waiting for the keychain: {KEYCHAIN_ALLOW_HINT}");
562                }
563            });
564        SlowStoreNote { done }
565    }
566}
567
568impl Drop for SlowStoreNote {
569    fn drop(&mut self) {
570        self.done.store(true, std::sync::atomic::Ordering::SeqCst);
571    }
572}
573
574/// How long a hook or server waits for the key store before saying so.
575pub const SLOW_STORE_NOTE_AFTER: Duration = Duration::from_secs(3);
576
577/// Where a secret came from.
578#[derive(Clone, Debug, PartialEq, Eq)]
579pub enum Source {
580    /// `MNEMO_PASSPHRASE`.
581    EnvPassphrase,
582    /// `MNEMO_KEY`.
583    EnvKey,
584    /// `MNEMO_KEY_FILE`.
585    KeyFile(PathBuf),
586    /// `MNEMO_KEY_COMMAND`.
587    KeyCommand,
588    /// A key-store entry; the text describes the store.
589    Store(String),
590}
591
592impl std::fmt::Display for Source {
593    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
594        match self {
595            Source::EnvPassphrase => f.write_str("MNEMO_PASSPHRASE"),
596            Source::EnvKey => f.write_str("MNEMO_KEY"),
597            Source::KeyFile(p) => write!(f, "MNEMO_KEY_FILE ({})", p.display()),
598            Source::KeyCommand => f.write_str("MNEMO_KEY_COMMAND"),
599            Source::Store(s) => write!(f, "this brain's entry in {s}"),
600        }
601    }
602}
603
604/// What [`resolve`] found.
605pub struct Resolved {
606    /// The secret.
607    pub secret: Secret,
608    /// Where it came from.
609    pub source: Source,
610    /// The next source of the same kind, for the error when this one
611    /// doesn't open the file: the next environment source that's present,
612    /// or the key store, which isn't looked up (it may have no entry).
613    pub next: Option<Source>,
614    /// Sources that were skipped, and why, to show the user.
615    pub notes: Vec<String>,
616}
617
618/// The chain's answer.
619pub enum Resolution {
620    /// A source was present and gave a secret.
621    Found(Resolved),
622    /// No source was present. `kind` is the file's kind (the CLI then
623    /// prompts for a passphrase file, at a terminal).
624    NoSource {
625        /// The file's kind.
626        kind: SecretKind,
627        /// Sources that were skipped, to show the user.
628        notes: Vec<String>,
629    },
630}
631
632fn env_set(name: &str) -> Option<String> {
633    std::env::var(name).ok().filter(|v| !v.is_empty())
634}
635
636fn kind_word(k: SecretKind) -> &'static str {
637    match k {
638        SecretKind::Key => "a key",
639        SecretKind::Passphrase => "a passphrase",
640    }
641}
642
643/// Find the secret for the brain at `path` (the keys note, section 6).
644///
645/// It reads the file's KDF parameters first, with no key: raw-key
646/// parameters make it a key file, anything else a passphrase file. It takes
647/// the first present source of that kind: `MNEMO_KEY`, `MNEMO_KEY_FILE`,
648/// `MNEMO_KEY_COMMAND`, the key store, for a key; `MNEMO_PASSPHRASE`, a
649/// passphrase entry in the key store, for a passphrase. A present source of
650/// the other kind is named in [`Resolved::notes`] as skipped. With no source
651/// of the file's kind, the first present source of the other kind is used,
652/// once (for a key file, only a passphrase source). Nothing is tried: the
653/// caller opens with what comes back.
654///
655/// **The key store is looked up last, and only when it's needed** (step
656/// 2): when no earlier source of the file's kind is present, or for the one
657/// try of the other kind. So a keychain that would ask the user something,
658/// or can't be reached at all, is never touched when `MNEMO_KEY` answers. A
659/// store error is a note when another source answers, and the error only
660/// when the store was the one left.
661///
662/// **When page 0 doesn't parse,** the salts and the kind come from the
663/// header frames in the file's write-ahead log (newest first), and the
664/// store is looked up under each in turn; the open that follows heals the
665/// header. With neither, the kind is unknown: the first environment source
666/// present is used.
667pub fn resolve(
668    path: impl AsRef<Path>,
669    store: Option<&dyn KeyStore>,
670    command_timeout: Duration,
671) -> Result<Resolution> {
672    let path = path.as_ref();
673    let file_name = path.display().to_string();
674    let mut notes = Vec::new();
675    let (kind, salts) = match file_info(path) {
676        Ok(i) => (Some(i.kind), vec![i.salt]),
677        Err(_) => match crate::store::wal_header_salts(path) {
678            Ok(c) if !c.is_empty() => {
679                notes.push(format!(
680                    "{file_name}'s header couldn't be read; its write-ahead log names {} salt(s) \
681                     to look up",
682                    c.len()
683                ));
684                (
685                    Some(kind_of_kdf(c[0].1)),
686                    c.iter().map(|(s, _)| *s).collect(),
687                )
688            }
689            _ => (None, Vec::new()),
690        },
691    };
692    let env = env_sources();
693    let Some(kind) = kind else {
694        // The kind is unknown, and there's no salt to look up.
695        let Some((src, _)) = env.first().cloned() else {
696            return Ok(Resolution::NoSource {
697                kind: SecretKind::Passphrase,
698                notes,
699            });
700        };
701        notes.push(format!(
702            "{file_name}'s header couldn't be read, so its kind of secret is unknown"
703        ));
704        let secret = fetch(&src, None, command_timeout)?;
705        return Ok(Resolution::Found(Resolved {
706            secret,
707            source: src,
708            next: None,
709            notes,
710        }));
711    };
712    let mine: Vec<&(Source, SecretKind)> = env.iter().filter(|(_, k)| *k == kind).collect();
713    let other: Vec<&(Source, SecretKind)> = env.iter().filter(|(_, k)| *k != kind).collect();
714    let skipped = |notes: &mut Vec<String>, using: &Source| {
715        for (s, k) in &other {
716            notes.push(format!(
717                "{s} holds {}, but {file_name} uses {}; skipped it, using {using}",
718                kind_word(*k),
719                kind_word(kind)
720            ));
721        }
722    };
723    // An environment source of the file's kind: the store isn't touched.
724    if let Some(first) = mine.first() {
725        skipped(&mut notes, &first.0);
726        let secret = fetch(&first.0, None, command_timeout)?;
727        return Ok(Resolution::Found(Resolved {
728            secret,
729            source: first.0.clone(),
730            // The next source of this kind: the next environment one, else
731            // the store, which isn't looked up now (it may have no entry).
732            next: mine
733                .get(1)
734                .map(|(s, _)| s.clone())
735                .or_else(|| store.map(|st| Source::Store(st.describe()))),
736            notes,
737        }));
738    }
739    // The store, last.
740    let looked = match store {
741        None => Ok(None),
742        // Section 8: a store that can't be used here at all (no Secret
743        // Service on the session bus, no access) is no store, and the chain
744        // goes on without it. Any other error is the store's own.
745        Some(st) => match lookup_salts(st, &salts) {
746            Ok(e) => Ok(e.map(|e| (st.describe(), e))),
747            Err(_) if st.check_available().is_err() => Ok(None),
748            Err(e) => Err(e),
749        },
750    };
751    let (store_other, store_error) = match looked {
752        Ok(Some((desc, e))) if stored_kind(&e) == kind => {
753            let src = Source::Store(desc);
754            skipped(&mut notes, &src);
755            return Ok(Resolution::Found(Resolved {
756                secret: e.into_secret(),
757                source: src,
758                next: None,
759                notes,
760            }));
761        }
762        Ok(found) => (found, None),
763        Err(e) => (None, Some(e)),
764    };
765    // No source of the file's kind: the first of the other kind, once.
766    if let Some(first) = other.first() {
767        if let (Some(e), Some(st)) = (&store_error, store) {
768            notes.push(format!("{} couldn't be read ({e})", st.describe()));
769        }
770        notes.push(format!(
771            "{file_name} uses {}, and no source of that kind is set; trying {} once",
772            kind_word(kind),
773            first.0
774        ));
775        let secret = fetch(&first.0, None, command_timeout)?;
776        return Ok(Resolution::Found(Resolved {
777            secret,
778            source: first.0.clone(),
779            next: None,
780            notes,
781        }));
782    }
783    if let Some(e) = store_error {
784        return Err(e);
785    }
786    if let Some((desc, e)) = store_other {
787        let src = Source::Store(desc);
788        notes.push(format!(
789            "{file_name} uses {}, and no source of that kind is set; trying {src} once",
790            kind_word(kind)
791        ));
792        return Ok(Resolution::Found(Resolved {
793            secret: e.into_secret(),
794            source: src,
795            next: None,
796            notes,
797        }));
798    }
799    Ok(Resolution::NoSource { kind, notes })
800}
801
802/// The environment's sources that are present, in the table's order.
803fn env_sources() -> Vec<(Source, SecretKind)> {
804    let mut present = Vec::new();
805    if env_set("MNEMO_PASSPHRASE").is_some() {
806        present.push((Source::EnvPassphrase, SecretKind::Passphrase));
807    }
808    if env_set("MNEMO_KEY").is_some() {
809        present.push((Source::EnvKey, SecretKind::Key));
810    }
811    if let Some(f) = env_set("MNEMO_KEY_FILE") {
812        present.push((Source::KeyFile(PathBuf::from(f)), SecretKind::Key));
813    }
814    if env_set("MNEMO_KEY_COMMAND").is_some() {
815        present.push((Source::KeyCommand, SecretKind::Key));
816    }
817    present
818}
819
820/// The first entry `store` has under any of `salts`, in order.
821fn lookup_salts(store: &dyn KeyStore, salts: &[[u8; SALT_LEN]]) -> Result<Option<StoredSecret>> {
822    for salt in salts {
823        if let Some(e) = store.get(salt)? {
824            return Ok(Some(e));
825        }
826    }
827    Ok(None)
828}
829
830fn stored_kind(e: &StoredSecret) -> SecretKind {
831    match e {
832        StoredSecret::Key(_) => SecretKind::Key,
833        StoredSecret::Passphrase(_) => SecretKind::Passphrase,
834    }
835}
836
837fn kind_of_kdf(kdf: KdfParams) -> SecretKind {
838    if kdf.below_passphrase_floor() {
839        SecretKind::Key
840    } else {
841        SecretKind::Passphrase
842    }
843}
844
845/// Read the secret out of a present source.
846fn fetch(src: &Source, entry: Option<StoredSecret>, timeout: Duration) -> Result<Secret> {
847    Ok(match src {
848        Source::EnvPassphrase => Secret::Passphrase(Zeroizing::new(
849            env_set("MNEMO_PASSPHRASE").unwrap_or_default(),
850        )),
851        Source::EnvKey => {
852            let text = Zeroizing::new(env_set("MNEMO_KEY").unwrap_or_default());
853            Secret::Key(parse_key_text(&text, "MNEMO_KEY")?)
854        }
855        Source::KeyFile(p) => Secret::Key(read_key_file(p)?),
856        Source::KeyCommand => {
857            let cmd = env_set("MNEMO_KEY_COMMAND").unwrap_or_default();
858            Secret::Key(run_key_command(&cmd, timeout)?)
859        }
860        Source::Store(_) => entry
861            .ok_or_else(|| MnemoError::Invalid("the key-store entry went away".into()))?
862            .into_secret(),
863    })
864}
865
866// --- The orders ------------------------------------------------------------
867
868/// [`create_generated`]'s `persist`: keep the key, given the brain's salt.
869pub type Persist<'a> = dyn FnMut(&[u8; SALT_LEN], &[u8; 32]) -> Result<()> + 'a;
870
871/// Create a brain at `path` under a freshly generated key (the keys note,
872/// section 1). In this order, so there's never a brain at `path` whose key
873/// is only in memory:
874/// 1. the key is drawn, and the brain is created under a temp name next to
875///    `path` with the raw-key parameters;
876/// 2. `prepare` runs on it (the CLI writes its manifest), and it's closed;
877/// 3. `persist` keeps the key, given the brain's salt (a key store's
878///    [`store_and_check`], or a new key file);
879/// 4. the temp file takes `path`'s name.
880///
881/// `path` must not exist. Dead `init` temps next to it are removed first.
882/// On an error the temp file is removed.
883pub fn create_generated(
884    path: impl AsRef<Path>,
885    config: MnemoConfig,
886    prepare: &mut dyn FnMut(&mut Mnemo) -> Result<()>,
887    persist: &mut Persist<'_>,
888) -> Result<Zeroizing<[u8; 32]>> {
889    let path = path.as_ref();
890    if std::fs::symlink_metadata(path).is_ok() {
891        return Err(MnemoError::Invalid(format!(
892            "{} already exists; nothing was changed",
893            path.display()
894        )));
895    }
896    crate::store::remove_dead_temps(path, "init");
897    let key = Zeroizing::new(Mnemo::generate_key());
898    let config = MnemoConfig {
899        kdf: KdfParams::raw_key(),
900        ..config
901    };
902    let (tmp, mut db) =
903        crate::store::create_temp(path, "init", &key[..], SecretKind::Key, config, None)?;
904    let result = (|| {
905        prepare(&mut db)?;
906        let salt = db.header_salt();
907        db.close()?;
908        persist(&salt, &key)?;
909        #[cfg(feature = "dev-hooks")]
910        if std::env::var_os("MNEMO_DEV_ABORT_INIT_BEFORE_RENAME").is_some() {
911            std::process::abort();
912        }
913        if std::fs::symlink_metadata(path).is_ok() {
914            return Err(MnemoError::Invalid(format!(
915                "{} appeared while it was being created; nothing was changed there",
916                path.display()
917            )));
918        }
919        std::fs::rename(&tmp, path)?;
920        Ok(())
921    })();
922    match result {
923        Ok(()) => Ok(key),
924        Err(e) => {
925            let _ = std::fs::remove_file(&tmp);
926            Err(e)
927        }
928    }
929}
930
931/// A rekey through [`rekey_stored`] failed. `entries` says what became of
932/// the key-store entries.
933#[derive(Debug)]
934pub struct StoredRekeyError {
935    /// The rekey's error.
936    pub error: MnemoError,
937    /// What became of the entries.
938    pub entries: String,
939    /// Whether the new secret is certainly not in force (the old salt is
940    /// still on disk), so anything written for it can go.
941    pub new_secret_dropped: bool,
942}
943
944impl std::fmt::Display for StoredRekeyError {
945    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
946        write!(f, "{}; {}", self.error, self.entries)
947    }
948}
949
950impl std::error::Error for StoredRekeyError {}
951
952/// Rekey `db` to `new`, keeping it in `store` under the new salt (the keys
953/// note, section 4). The order:
954/// 1. the new salt is drawn;
955/// 2. `new` is stored under it and read back ([`store_and_check`]);
956/// 3. `before_commit` runs (the CLI shows a new key's recovery code here);
957/// 4. the rekey commits;
958/// 5. after an error, page 0 is read again: the new entry is deleted only
959///    if the old salt is still there, and both are kept otherwise.
960///
961/// The old entry is kept: copies of the file made before still use it.
962/// A key gets [`KdfParams::raw_key`]; a passphrase gets
963/// [`KdfParams::for_passphrase`] of the file's parameters. Returns a note
964/// for the user.
965pub fn rekey_stored(
966    db: &mut Mnemo,
967    new: &Secret,
968    store: &dyn KeyStore,
969    label: &str,
970    before_commit: &mut dyn FnMut() -> Result<()>,
971) -> std::result::Result<String, StoredRekeyError> {
972    let old_salt = db.header_salt();
973    let kdf = match new.kind() {
974        SecretKind::Key => KdfParams::raw_key(),
975        SecretKind::Passphrase => db.kdf_params().for_passphrase(),
976    };
977    let stored = StoredSecret::from_secret(new);
978    let mut new_salt: Option<[u8; SALT_LEN]> = None;
979    let r = db.rekey_staged(new.bytes(), new.kind(), kdf, &mut |salt| {
980        store_and_check(store, salt, &stored, label)?;
981        new_salt = Some(*salt);
982        before_commit()
983    });
984    match r {
985        Ok(()) => Ok(format!(
986            "the new secret is in {}; the old entry is still there, for copies of the file \
987             made before this rekey",
988            store.describe()
989        )),
990        Err(error) => {
991            let Some(ns) = new_salt else {
992                return Err(StoredRekeyError {
993                    error,
994                    entries: "the key store wasn't changed".into(),
995                    new_secret_dropped: true,
996                });
997            };
998            // REKEY-1's one exception: page 0 may or may not have landed,
999            // whatever it reads now, so both entries stay.
1000            if Mnemo::rekey_left_either_secret(&error) {
1001                return Err(StoredRekeyError {
1002                    error,
1003                    entries: "both entries are kept, since the file may open with either \
1004                              secret"
1005                        .into(),
1006                    new_secret_dropped: false,
1007                });
1008            }
1009            let (entries, new_secret_dropped) = match db.disk_salt() {
1010                Ok(s) if s == old_salt => match store.delete(&ns) {
1011                    Ok(()) => (
1012                        "the old secret is still in force, and the new entry was removed"
1013                            .to_string(),
1014                        true,
1015                    ),
1016                    Err(e) => (
1017                        format!(
1018                            "the old secret is still in force; removing the new entry failed ({e})"
1019                        ),
1020                        true,
1021                    ),
1022                },
1023                Ok(s) if s == ns => (
1024                    "the file may now open only with the new secret, so both entries are kept"
1025                        .to_string(),
1026                    false,
1027                ),
1028                _ => (
1029                    "the file's header couldn't be read back, so both entries are kept".to_string(),
1030                    false,
1031                ),
1032            };
1033            Err(StoredRekeyError {
1034                error,
1035                entries,
1036                new_secret_dropped,
1037            })
1038        }
1039    }
1040}
1041
1042/// The text `mnemo info` shows for a file's KDF parameters, when they need
1043/// a word: raw-key parameters with a passphrase, or test-grade ones.
1044pub fn kdf_grade_note(kdf: KdfParams, kind: SecretKind) -> Option<String> {
1045    if kind == SecretKind::Passphrase && kdf.below_passphrase_floor() {
1046        return Some(
1047            "below the passphrase floor: a passphrase on raw-key KDF parameters; `mnemo rekey` \
1048             or `mnemo compact` raises them"
1049                .into(),
1050        );
1051    }
1052    if kdf.is_test_grade() {
1053        return Some("test-grade KDF parameters".into());
1054    }
1055    None
1056}