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 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 fn durable(&self) -> bool {
254 std::env::var_os("MNEMO_DEV_KEYSTORE_NOT_DURABLE").is_none()
255 }
256}
257
258pub 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 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
285pub const KEYCHAIN_SERVICE: &str = "io.github.toarchkumar.mnemo.brain";
288
289pub 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
314fn 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
328pub 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
342pub 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 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
399pub 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
417const COMMAND_OUTPUT_CAP: usize = 4096;
419
420pub(crate) const SECRET_ENV_VARS: [&str; 4] = [
424 "MNEMO_PASSPHRASE",
425 "MNEMO_KEY",
426 "MNEMO_KEY_FILE",
427 "MNEMO_KEY_COMMAND",
428];
429
430pub 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
516pub const CLI_COMMAND_TIMEOUT: Duration = Duration::from_secs(60);
520pub const SERVER_COMMAND_TIMEOUT: Duration = Duration::from_secs(10);
522
523pub 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
530pub 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
540pub struct SlowStoreNote {
544 done: std::sync::Arc<std::sync::atomic::AtomicBool>,
545}
546
547impl SlowStoreNote {
548 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 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
574pub const SLOW_STORE_NOTE_AFTER: Duration = Duration::from_secs(3);
576
577#[derive(Clone, Debug, PartialEq, Eq)]
579pub enum Source {
580 EnvPassphrase,
582 EnvKey,
584 KeyFile(PathBuf),
586 KeyCommand,
588 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
604pub struct Resolved {
606 pub secret: Secret,
608 pub source: Source,
610 pub next: Option<Source>,
614 pub notes: Vec<String>,
616}
617
618pub enum Resolution {
620 Found(Resolved),
622 NoSource {
625 kind: SecretKind,
627 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
643pub 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 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 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 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 let looked = match store {
741 None => Ok(None),
742 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 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
802fn 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
820fn 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
845fn 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
866pub type Persist<'a> = dyn FnMut(&[u8; SALT_LEN], &[u8; 32]) -> Result<()> + 'a;
870
871pub 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#[derive(Debug)]
934pub struct StoredRekeyError {
935 pub error: MnemoError,
937 pub entries: String,
939 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
952pub 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 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
1042pub 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}