1pub 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
35pub enum Secret {
37 Passphrase(Zeroizing<String>),
39 Key(Zeroizing<[u8; 32]>),
41}
42
43impl Secret {
44 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub struct FileKeyInfo {
63 pub salt: [u8; SALT_LEN],
65 pub kdf: KdfParams,
67 pub kind: SecretKind,
70}
71
72pub 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
96pub fn hex(bytes: &[u8]) -> String {
98 bytes.iter().map(|b| format!("{b:02x}")).collect()
99}
100
101pub enum StoredSecret {
105 Key(Zeroizing<[u8; 32]>),
107 Passphrase(Zeroizing<String>),
109}
110
111impl StoredSecret {
112 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 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 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
155pub trait KeyStore {
158 fn describe(&self) -> String;
160 fn get(&self, salt: &[u8; SALT_LEN]) -> Result<Option<StoredSecret>>;
162 fn put(&self, salt: &[u8; SALT_LEN], secret: &StoredSecret, label: &str) -> Result<()>;
165 fn delete(&self, salt: &[u8; SALT_LEN]) -> Result<()>;
167 fn durable(&self) -> bool {
172 false
173 }
174 fn check_available(&self) -> Result<()> {
178 Ok(())
179 }
180}
181
182#[cfg(feature = "dev-hooks")]
186#[doc(hidden)]
187pub struct DirKeyStore {
188 dir: PathBuf,
189}
190
191#[cfg(feature = "dev-hooks")]
192impl DirKeyStore {
193 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 fn durable(&self) -> bool {
246 std::env::var_os("MNEMO_DEV_KEYSTORE_NOT_DURABLE").is_none()
247 }
248}
249
250pub 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 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
277pub const KEYCHAIN_SERVICE: &str = "io.github.toarchkumar.mnemo.brain";
280
281pub 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
306fn 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
320pub 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
334pub 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 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
391pub 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
409const COMMAND_OUTPUT_CAP: usize = 4096;
411
412pub(crate) const SECRET_ENV_VARS: [&str; 4] = [
416 "MNEMO_PASSPHRASE",
417 "MNEMO_KEY",
418 "MNEMO_KEY_FILE",
419 "MNEMO_KEY_COMMAND",
420];
421
422pub 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
508pub const CLI_COMMAND_TIMEOUT: Duration = Duration::from_secs(60);
512pub const SERVER_COMMAND_TIMEOUT: Duration = Duration::from_secs(10);
514
515#[derive(Clone, Debug, PartialEq, Eq)]
517pub enum Source {
518 EnvPassphrase,
520 EnvKey,
522 KeyFile(PathBuf),
524 KeyCommand,
526 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
542pub struct Resolved {
544 pub secret: Secret,
546 pub source: Source,
548 pub next: Option<Source>,
552 pub notes: Vec<String>,
554}
555
556pub enum Resolution {
558 Found(Resolved),
560 NoSource {
563 kind: SecretKind,
565 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
581pub 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 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 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 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 let looked = match store {
679 None => Ok(None),
680 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 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
740fn 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
758fn 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
783fn 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
804pub type Persist<'a> = dyn FnMut(&[u8; SALT_LEN], &[u8; 32]) -> Result<()> + 'a;
808
809pub 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#[derive(Debug)]
872pub struct StoredRekeyError {
873 pub error: MnemoError,
875 pub entries: String,
877 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
890pub 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 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
980pub 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}