1use std::collections::HashMap;
75use std::path::{Path, PathBuf};
76use std::sync::atomic::{AtomicBool, Ordering};
77use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, PoisonError};
78use std::time::Duration;
79
80use keyring_core::Entry;
81use zeroize::Zeroizing;
82
83pub const SERVICE: &str = "agentmux";
85
86const TIMEOUT: Duration = Duration::from_secs(15);
92
93#[derive(Debug, PartialEq)]
99enum RunOutcome {
100 TimedOut,
103 WorkerPanicked,
106}
107
108type ReadResult = Result<Option<Zeroizing<String>>, String>;
110
111struct SharedReads {
123 in_flight: Arc<Mutex<HashMap<String, Arc<PendingRead>>>>,
124}
125
126#[derive(Default)]
127struct PendingRead {
128 result: Mutex<Option<Result<ReadResult, ()>>>,
130 done: Condvar,
131}
132
133impl SharedReads {
134 fn new() -> Self {
135 Self { in_flight: Arc::new(Mutex::new(HashMap::new())) }
136 }
137
138 fn read(
143 &self,
144 account_id: &str,
145 timeout: Duration,
146 read: impl FnOnce() -> ReadResult + Send + 'static,
147 ) -> Result<ReadResult, RunOutcome> {
148 let spawn = |work: Box<dyn FnOnce() + Send>| {
149 std::thread::Builder::new().name("keychain-read".into()).spawn(work).map(drop)
150 };
151 self.read_with(account_id, timeout, read, spawn)
152 }
153
154 fn read_with(
157 &self,
158 account_id: &str,
159 timeout: Duration,
160 read: impl FnOnce() -> ReadResult + Send + 'static,
161 spawn: impl FnOnce(Box<dyn FnOnce() + Send>) -> std::io::Result<()>,
162 ) -> Result<ReadResult, RunOutcome> {
163 let pending = {
164 let mut in_flight = lock(&self.in_flight);
165 match in_flight.get(account_id) {
166 Some(pending) => pending.clone(),
167 None => {
168 let pending = Arc::new(PendingRead::default());
169 in_flight.insert(account_id.to_string(), pending.clone());
170 let (worker, map, id) = (pending.clone(), self.in_flight.clone(), account_id.to_string());
171 let started = spawn(Box::new(move || {
172 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(read)).map_err(|_| ());
173 let mut in_flight = lock(&map);
177 if in_flight.get(&id).is_some_and(|p| Arc::ptr_eq(p, &worker)) {
178 in_flight.remove(&id);
179 }
180 drop(in_flight);
181 *lock(&worker.result) = Some(result);
182 worker.done.notify_all();
183 }));
184 if let Err(e) = started {
185 in_flight.remove(account_id);
188 return Ok(Err(format!("keychain read failed: could not start a thread: {e}")));
189 }
190 pending
191 }
192 }
193 };
194 let result = lock(&pending.result);
195 let (result, _) = pending
196 .done
197 .wait_timeout_while(result, timeout, |r| r.is_none())
198 .unwrap_or_else(PoisonError::into_inner);
199 match result.as_ref() {
200 None => Err(RunOutcome::TimedOut),
201 Some(Err(())) => Err(RunOutcome::WorkerPanicked),
202 Some(Ok(answer)) => Ok(answer.clone()),
203 }
204 }
205
206 fn forget(&self, account_id: &str) {
210 lock(&self.in_flight).remove(account_id);
211 }
212
213 fn after_write<T>(&self, account_id: &str, written: Result<T, String>) -> Result<T, String> {
218 if written.is_ok() {
219 self.forget(account_id);
220 }
221 written
222 }
223}
224
225fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
226 m.lock().unwrap_or_else(PoisonError::into_inner)
227}
228
229fn shared_reads() -> &'static SharedReads {
230 static READS: OnceLock<SharedReads> = OnceLock::new();
231 READS.get_or_init(SharedReads::new)
232}
233
234fn credential_store() -> Result<(), String> {
246 static INSTALLED: AtomicBool = AtomicBool::new(false);
247 if INSTALLED.load(Ordering::Acquire) && !cfg!(target_os = "linux") {
248 return Ok(());
249 }
250 #[cfg(target_os = "macos")]
251 let store = apple_native_keyring_store::keychain::Store::new();
252 #[cfg(windows)]
253 let store = windows_native_keyring_store::Store::new();
254 #[cfg(target_os = "linux")]
255 let store = zbus_secret_service_keyring_store::Store::new();
256 #[cfg(any(target_os = "macos", windows, target_os = "linux"))]
257 {
258 keyring_core::set_default_store(store.map_err(|e| format!("keychain unavailable: {e}"))?);
259 INSTALLED.store(true, Ordering::Release);
260 Ok(())
261 }
262 #[cfg(not(any(target_os = "macos", windows, target_os = "linux")))]
263 Err("keychain unavailable: no OS credential store on this platform".to_string())
264}
265
266fn entry(account_id: &str) -> Result<Entry, String> {
267 keychain_without_dialogs()?;
268 credential_store()?;
269 Entry::new(SERVICE, &account_key(account_id))
270 .map_err(|e| format!("keychain entry init failed: {e}"))
271}
272
273pub const NEEDS_CONSENT: &str = "keychain: this entry was saved by an older AgentMux build, which macOS won't let this one \
276 read without asking; save it again (sign in again, or re-enter the key) and this build keeps it from then on";
277
278pub fn is_needs_consent(err: &str) -> bool {
282 err.contains(NEEDS_CONSENT)
283}
284
285fn keychain_without_dialogs() -> Result<(), String> {
292 #[cfg(target_os = "macos")]
293 {
294 static OFF: OnceLock<()> = OnceLock::new();
295 if OFF.get().is_none() {
296 let lock = security_framework::os::macos::keychain::SecKeychain::disable_user_interaction()
297 .map_err(|e| format!("keychain unavailable: couldn't turn off its dialogs: {e}"))?;
298 std::mem::forget(lock);
300 let _ = OFF.set(());
301 }
302 }
303 Ok(())
304}
305
306fn keychain_error(op: &str, e: &keyring_core::Error) -> String {
309 match keychain_status(e) {
310 Some(ERR_SEC_AUTH_FAILED) => NEEDS_CONSENT.to_string(),
311 Some(ERR_SEC_INTERACTION_NOT_ALLOWED) => format!("keychain {op} failed: the keychain is locked ({e})"),
312 _ => format!("keychain {op} failed: {e}"),
313 }
314}
315
316const ERR_SEC_AUTH_FAILED: i32 = -25293;
318const ERR_SEC_INTERACTION_NOT_ALLOWED: i32 = -25308;
320const ERR_SEC_DUPLICATE_ITEM: i32 = -25299;
323const ERR_SEC_INVALID_OWNER_EDIT: i32 = -25244;
327
328#[cfg(target_os = "macos")]
333fn delete_without_reading(account: &str) -> Result<bool, String> {
334 use security_framework::item::{ItemClass, ItemSearchOptions, Reference, SearchResult};
335 let find = || {
336 ItemSearchOptions::new()
337 .class(ItemClass::generic_password())
338 .service(SERVICE)
339 .account(account)
340 .load_refs(true)
341 .search()
342 };
343 let items = match find() {
344 Ok(items) => items,
345 Err(e) if e.code() == -25300 => return Ok(false), Err(e) => return Err(format!("keychain delete failed: {e}")),
347 };
348 for found in items {
349 if let SearchResult::Ref(Reference::KeychainItem(item)) = found {
350 item.delete();
351 }
352 }
353 match find() {
354 Err(e) if e.code() == -25300 => Ok(true),
355 Ok(_) => Err("keychain delete failed: the entry is still there".to_string()),
356 Err(e) => Err(format!("keychain delete failed: {e}")),
357 }
358}
359
360fn untrusted_item(e: &keyring_core::Error) -> bool {
364 matches!(keychain_status(e), Some(ERR_SEC_AUTH_FAILED | ERR_SEC_DUPLICATE_ITEM | ERR_SEC_INVALID_OWNER_EDIT))
365}
366
367fn delete_untrusted(account_id: &str) -> Result<(), keyring_core::Error> {
369 #[cfg(target_os = "macos")]
370 {
371 delete_without_reading(&account_key(account_id))
372 .map(|_| ())
373 .map_err(|e| keyring_core::Error::PlatformFailure(Box::new(std::io::Error::other(e))))
374 }
375 #[cfg(not(target_os = "macos"))]
376 {
377 let _ = account_id;
378 Err(keyring_core::Error::NoEntry)
379 }
380}
381
382fn keychain_status(e: &keyring_core::Error) -> Option<i32> {
384 #[cfg(target_os = "macos")]
385 if let keyring_core::Error::PlatformFailure(inner) | keyring_core::Error::NoStorageAccess(inner) = e {
386 return inner.downcast_ref::<security_framework::base::Error>().map(|se| se.code());
387 }
388 let _ = e;
389 None
390}
391
392fn replace_untrusted<E>(
396 set: impl Fn() -> Result<(), E>,
397 delete: impl Fn() -> Result<(), E>,
398 needs_consent: impl Fn(&E) -> bool,
399 missing: impl Fn(&E) -> bool,
400) -> Result<(), E> {
401 match set() {
402 Err(e) if needs_consent(&e) => match delete() {
403 Ok(()) => set(),
404 Err(d) if missing(&d) => set(),
405 Err(d) => Err(d),
406 },
407 other => other,
408 }
409}
410
411pub fn account_key(account_id: &str) -> String {
413 format!("acct:{account_id}")
414}
415
416static FILE_STORE: OnceLock<PathBuf> = OnceLock::new();
418
419pub fn use_file_store(dir: PathBuf) -> Result<(), String> {
423 file::prepare_dir(&dir)?;
424 FILE_STORE
425 .set(dir)
426 .map_err(|_| "the secret store was already chosen".to_string())
427}
428
429fn isolated_secrets_dir(home_override: Option<&std::ffi::OsStr>, store: Option<&str>, shared_dir: Option<PathBuf>) -> Option<PathBuf> {
433 let home = home_override.filter(|h| !h.is_empty())?;
434 if store.is_some_and(|s| s.trim().eq_ignore_ascii_case("keychain")) {
435 return None;
436 }
437 let shared = shared_dir.unwrap_or_else(|| PathBuf::from(home).join("shared"));
440 Some(shared.join("secrets"))
441}
442
443pub fn isolate_for_home_override() -> Result<bool, String> {
449 let shared = agentmux_common::DataPaths::from_env().map(|p| p.shared_dir);
450 let home = std::env::var_os("AGENTMUX_HOME_OVERRIDE");
451 let store = std::env::var("AGENTMUX_SECRET_STORE").ok();
452 match isolated_secrets_dir(home.as_deref(), store.as_deref(), shared) {
453 Some(dir) if FILE_STORE.get().is_none() => use_file_store(dir).map(|()| true),
454 _ => Ok(false),
455 }
456}
457
458#[derive(Debug, Clone, PartialEq, Eq)]
460pub enum KeychainProbe {
461 Works,
463 Absent(String),
465 NoAnswer,
467 RoundTripFailed(String),
469}
470
471pub fn probe_keychain(wait: Duration) -> KeychainProbe {
475 let (tx, rx) = std::sync::mpsc::channel();
476 std::thread::spawn(move || {
477 let _ = tx.send(probe_now());
478 });
479 rx.recv_timeout(wait).unwrap_or(KeychainProbe::NoAnswer)
480}
481
482fn probe_now() -> KeychainProbe {
483 const SECRET: &str = "probe";
484 if let Err(e) = credential_store() {
485 return KeychainProbe::Absent(e);
486 }
487 let id = format!("keychain-probe-{}", std::process::id());
488 if let Err(e) = put(&id, SECRET) {
489 return KeychainProbe::RoundTripFailed(format!("write: {e}"));
490 }
491 let read = get_optional(&id);
492 let deleted = delete(&id);
493 match read {
494 Ok(Some(v)) if v.as_str() == SECRET => match deleted {
495 Ok(()) => KeychainProbe::Works,
496 Err(e) => KeychainProbe::RoundTripFailed(format!("delete: {e}")),
497 },
498 Ok(_) => KeychainProbe::RoundTripFailed("read back: not what was stored".to_string()),
499 Err(e) => KeychainProbe::RoundTripFailed(format!("read back: {e}")),
500 }
501}
502
503pub fn backend_name() -> &'static str {
505 if FILE_STORE.get().is_some() {
506 "file"
507 } else {
508 "keychain"
509 }
510}
511
512pub fn put(account_id: &str, secret: &str) -> Result<(), String> {
519 crate::backend::transcript::withhold_sources::keychain(account_id, secret);
521 if let Some(dir) = FILE_STORE.get() {
522 return file::put(dir, &account_key(account_id), secret);
523 }
524 let e = entry(account_id)?;
525 let written = replace_untrusted(
528 || e.set_password(secret),
529 || delete_untrusted(account_id),
530 untrusted_item,
531 |err| matches!(err, keyring_core::Error::NoEntry),
532 )
533 .map_err(|err| keychain_error("write", &err));
534 shared_reads().after_write(account_id, written)
535}
536
537pub fn get(account_id: &str) -> Result<Zeroizing<String>, String> {
540 if FILE_STORE.get().is_some() {
541 return get_optional(account_id)?.ok_or_else(|| "secret store read failed: no entry for this account".to_string());
542 }
543 get_optional(account_id)?
544 .ok_or_else(|| format!("keychain read failed: {}", keyring_core::Error::NoEntry))
545}
546
547pub fn get_optional(account_id: &str) -> Result<Option<Zeroizing<String>>, String> {
557 let read = read_optional(account_id)?;
558 if let Some(secret) = &read {
559 crate::backend::transcript::withhold_sources::keychain(account_id, secret);
560 }
561 Ok(read)
562}
563
564fn read_optional(account_id: &str) -> Result<Option<Zeroizing<String>>, String> {
565 if let Some(dir) = FILE_STORE.get() {
566 return file::get_optional(dir, &account_key(account_id));
567 }
568 let id = account_id.to_string();
569 match shared_reads().read(account_id, TIMEOUT, move || get_optional_now(&id)) {
570 Ok(result) => result,
571 Err(outcome) => Err(run_outcome_message("read", outcome)),
572 }
573}
574
575pub fn get_optional_if_trusted(account_id: &str) -> Result<Option<Zeroizing<String>>, String> {
581 match get_optional(account_id) {
582 Err(e) if is_needs_consent(&e) => {
583 tracing::warn!(account = %account_key(account_id), "secret store: {e}; treating it as absent");
584 Ok(None)
585 }
586 other => other,
587 }
588}
589
590fn get_optional_now(account_id: &str) -> Result<Option<Zeroizing<String>>, String> {
591 match entry(account_id)?.get_password() {
592 Ok(pw) => Ok(Some(Zeroizing::new(pw))),
593 Err(keyring_core::Error::NoEntry) => Ok(None),
594 Err(e) => Err(keychain_error("read", &e)),
595 }
596}
597
598pub fn delete(account_id: &str) -> Result<(), String> {
604 if let Some(dir) = FILE_STORE.get() {
605 return file::delete(dir, &account_key(account_id));
606 }
607 let deleted = match entry(account_id)?.delete_credential() {
608 Ok(()) => Ok(()),
609 Err(keyring_core::Error::NoEntry) => Ok(()),
610 Err(e) if untrusted_item(&e) => delete_untrusted(account_id).map_err(|e| keychain_error("delete", &e)),
612 Err(e) => Err(keychain_error("delete", &e)),
613 };
614 shared_reads().after_write(account_id, deleted)
615}
616
617fn run_outcome_message(op: &str, outcome: RunOutcome) -> String {
618 match outcome {
619 RunOutcome::TimedOut => format!(
620 "keychain {op} timed out after {TIMEOUT:?} — likely an unanswered OS access-consent \
621 prompt (see docs/retro/retro-macos-muxbus-keychain-prompt-storm-2026-08-19.md §5)"
622 ),
623 RunOutcome::WorkerPanicked => {
624 format!("keychain {op} failed: the background thread performing it panicked")
625 }
626 }
627}
628
629pub mod file {
634 use super::*;
635 use sha2::{Digest, Sha256};
636 use std::io::Write;
637
638 pub(super) fn path_for(dir: &Path, key: &str) -> PathBuf {
639 let digest = Sha256::digest(key.as_bytes());
640 dir.join(digest.iter().map(|b| format!("{b:02x}")).collect::<String>())
641 }
642
643 pub(super) fn prepare_dir(dir: &Path) -> Result<(), String> {
646 let mut builder = std::fs::DirBuilder::new();
647 builder.recursive(true);
648 #[cfg(unix)]
649 {
650 use std::os::unix::fs::DirBuilderExt;
651 builder.mode(0o700);
652 }
653 builder
654 .create(dir)
655 .map_err(|e| format!("secret store: cannot create {}: {e}", dir.display()))?;
656 #[cfg(unix)]
657 {
658 use std::os::unix::fs::PermissionsExt;
659 std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
660 .map_err(|e| format!("secret store: cannot restrict {}: {e}", dir.display()))?;
661 }
662 Ok(())
663 }
664
665 pub(super) fn put(dir: &Path, key: &str, secret: &str) -> Result<(), String> {
668 let path = path_for(dir, key);
669 let tmp = dir.join(format!(".tmp-{}", uuid::Uuid::new_v4().simple()));
670 let mut opts = std::fs::OpenOptions::new();
671 opts.write(true).create_new(true);
672 #[cfg(unix)]
673 {
674 use std::os::unix::fs::OpenOptionsExt;
675 opts.mode(0o600);
676 }
677 let written = opts
678 .open(&tmp)
679 .and_then(|mut f| f.write_all(secret.as_bytes()).and_then(|()| f.sync_all()))
680 .and_then(|()| std::fs::rename(&tmp, &path));
681 written.map_err(|e| {
682 let _ = std::fs::remove_file(&tmp);
683 format!("secret store write failed: {e}")
684 })
685 }
686
687 pub(super) fn get_optional(dir: &Path, key: &str) -> Result<Option<Zeroizing<String>>, String> {
688 match std::fs::read(path_for(dir, key)) {
689 Ok(bytes) => String::from_utf8(bytes)
690 .map(|s| Some(Zeroizing::new(s)))
691 .map_err(|_| "secret store read failed: the entry is not valid UTF-8".to_string()),
692 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
693 Err(e) => Err(format!("secret store read failed: {e}")),
694 }
695 }
696
697 pub(super) fn delete(dir: &Path, key: &str) -> Result<(), String> {
698 match std::fs::remove_file(path_for(dir, key)) {
699 Ok(()) => Ok(()),
700 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
701 Err(e) => Err(format!("secret store delete failed: {e}")),
702 }
703 }
704}
705
706#[cfg(test)]
707mod tests {
708 use super::*;
709
710 #[test]
711 fn a_write_over_an_entry_that_does_not_trust_this_build_replaces_it() {
712 use std::cell::RefCell;
713 let run = |sets: Vec<Result<(), &'static str>>, del: Result<(), &'static str>| {
715 let calls = RefCell::new(Vec::new());
716 let sets = RefCell::new(sets.into_iter());
717 let out = replace_untrusted(
718 || {
719 calls.borrow_mut().push("set");
720 sets.borrow_mut().next().unwrap()
721 },
722 || {
723 calls.borrow_mut().push("delete");
724 del
725 },
726 |e| *e == "consent",
727 |e| *e == "missing",
728 );
729 (out, calls.into_inner())
730 };
731 assert_eq!(run(vec![Ok(())], Ok(())), (Ok(()), vec!["set"]));
732 assert_eq!(run(vec![Err("consent"), Ok(())], Ok(())), (Ok(()), vec!["set", "delete", "set"]));
733 assert_eq!(run(vec![Err("consent"), Ok(())], Err("missing")), (Ok(()), vec!["set", "delete", "set"]));
734 assert_eq!(run(vec![Err("consent")], Err("locked")), (Err("locked"), vec!["set", "delete"]));
735 assert_eq!(run(vec![Err("locked")], Ok(())), (Err("locked"), vec!["set"]));
737 }
738
739 #[test]
740 fn needs_consent_is_told_apart_from_other_failures() {
741 assert!(is_needs_consent(NEEDS_CONSENT));
742 assert!(is_needs_consent(&format!("muxbus: keychain read failed: {NEEDS_CONSENT}")));
743 assert!(!is_needs_consent("keychain read failed: the keychain is locked"));
744 }
745
746 #[cfg(target_os = "macos")]
747 #[test]
748 fn macos_codes_map_to_needs_consent_or_locked() {
749 let err = |code| keyring_core::Error::PlatformFailure(Box::new(security_framework::base::Error::from_code(code)));
750 assert_eq!(keychain_error("read", &err(ERR_SEC_AUTH_FAILED)), NEEDS_CONSENT);
751 assert!(keychain_error("read", &err(ERR_SEC_INTERACTION_NOT_ALLOWED)).contains("locked"));
752 assert!(!is_needs_consent(&keychain_error("read", &err(-25299))));
753 assert!(untrusted_item(&err(ERR_SEC_INVALID_OWNER_EDIT)));
756 assert!(!untrusted_item(&err(ERR_SEC_INTERACTION_NOT_ALLOWED)));
757 assert!(!is_needs_consent(&keychain_error("read", &keyring_core::Error::NoEntry)));
758 }
759
760 #[cfg(target_os = "macos")]
765 #[test]
766 #[ignore = "uses the real login keychain"]
767 fn needs_consent_live_against_the_login_keychain() {
768 let id = format!("test-needs-consent-{}", uuid::Uuid::new_v4().simple());
769 let account = account_key(&id);
770 let added = std::process::Command::new("/usr/bin/security")
771 .args(["add-generic-password", "-s", SERVICE, "-a", &account, "-w", "old", "-T", ""])
772 .status()
773 .unwrap();
774 assert!(added.success());
775 let started = std::time::Instant::now();
776 let read = get_optional(&id).map(|v| v.map(|z| z.to_string()));
777 let fast = started.elapsed() < std::time::Duration::from_secs(2);
778 let lenient = get_optional_if_trusted(&id).map(|v| v.map(|z| z.to_string()));
779 let replaced = put(&id, "new");
780 let after = get_optional(&id).map(|v| v.map(|z| z.to_string()));
781 let _ = delete(&id);
782 assert!(matches!(&read, Err(e) if is_needs_consent(e)), "{read:?}");
783 assert!(fast, "no dialog was waited on");
784 assert_eq!(lenient, Ok(None), "an entry this build may not read counts as absent");
785 assert_eq!(replaced, Ok(()));
786 assert_eq!(after, Ok(Some("new".to_string())));
787 }
788
789 #[test]
790 fn file_store_round_trips_overwrites_and_deletes() {
791 let tmp = tempfile::tempdir().unwrap();
792 let dir = tmp.path().join("secrets");
793 file::prepare_dir(&dir).unwrap();
794 let key = account_key("abc");
795 assert!(file::get_optional(&dir, &key).unwrap().is_none());
796 file::put(&dir, &key, "first").unwrap();
797 assert_eq!(file::get_optional(&dir, &key).unwrap().as_deref().map(String::as_str), Some("first"));
798 file::put(&dir, &key, "second").unwrap();
799 assert_eq!(file::get_optional(&dir, &key).unwrap().as_deref().map(String::as_str), Some("second"));
800 file::delete(&dir, &key).unwrap();
801 assert!(file::get_optional(&dir, &key).unwrap().is_none());
802 file::delete(&dir, &key).unwrap();
804 file::put(&dir, &key, "x").unwrap();
806 let names: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name()).collect();
807 assert_eq!(names.len(), 1, "{names:?}");
808 }
809
810 #[test]
811 fn file_store_entries_are_separate_and_named_by_hash() {
812 let tmp = tempfile::tempdir().unwrap();
813 let dir = tmp.path().to_path_buf();
814 let (a, b) = ("muxbus:global", "browser-auth:id:../../etc/passwd");
816 file::put(&dir, a, "A").unwrap();
817 file::put(&dir, b, "B").unwrap();
818 assert_eq!(file::get_optional(&dir, a).unwrap().as_deref().map(String::as_str), Some("A"));
819 assert_eq!(file::get_optional(&dir, b).unwrap().as_deref().map(String::as_str), Some("B"));
820 for key in [a, b] {
821 let p = file::path_for(&dir, key);
822 assert_eq!(p.parent(), Some(dir.as_path()));
823 let name = p.file_name().unwrap().to_str().unwrap().to_string();
824 assert_eq!(name.len(), 64);
825 assert!(name.bytes().all(|c| c.is_ascii_hexdigit()));
826 }
827 }
828
829 #[cfg(unix)]
830 #[test]
831 fn file_store_is_owner_only() {
832 use std::os::unix::fs::PermissionsExt;
833 let tmp = tempfile::tempdir().unwrap();
834 let dir = tmp.path().join("secrets");
835 std::fs::create_dir(&dir).unwrap();
836 std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
837 file::prepare_dir(&dir).unwrap();
839 let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
840 assert_eq!(mode(&dir), 0o700);
841 file::put(&dir, "k", "v").unwrap();
842 assert_eq!(mode(&file::path_for(&dir, "k")), 0o600);
843 }
844
845 #[test]
846 fn an_isolated_home_keeps_its_secrets_in_files_unless_the_keychain_is_asked_for() {
847 use std::ffi::OsStr;
848 let shared = Some(PathBuf::from("/iso/shared"));
849 let over = Some(OsStr::new("/iso"));
850 assert_eq!(isolated_secrets_dir(over, None, shared.clone()), Some(PathBuf::from("/iso/shared/secrets")));
851 assert_eq!(isolated_secrets_dir(over, Some("file"), shared.clone()), Some(PathBuf::from("/iso/shared/secrets")));
852 assert_eq!(isolated_secrets_dir(over, Some(" Keychain "), shared.clone()), None, "a test of the keychain asks for it");
853 assert_eq!(isolated_secrets_dir(None, None, shared.clone()), None, "the person's own instance keeps the keychain");
854 assert_eq!(isolated_secrets_dir(Some(OsStr::new("")), None, shared.clone()), None, "an empty override is none");
855 assert_eq!(isolated_secrets_dir(over, None, None), Some(PathBuf::from("/iso").join("shared").join("secrets")), "started with only the override: its own shared folder");
856 }
857
858 #[test]
859 fn account_key_is_namespaced() {
860 assert_eq!(account_key("abc123"), "acct:abc123");
861 }
862
863 const SHORT: Duration = Duration::from_millis(50);
864 const LONG: Duration = Duration::from_secs(10);
865
866 struct Gate {
869 calls: std::sync::atomic::AtomicUsize,
870 open: Mutex<bool>,
871 opened: Condvar,
872 }
873
874 impl Gate {
875 fn new() -> Arc<Self> {
876 Arc::new(Self { calls: Default::default(), open: Mutex::new(false), opened: Condvar::new() })
877 }
878 fn read(self: &Arc<Self>, value: &'static str) -> impl FnOnce() -> ReadResult + Send + 'static {
879 let gate = self.clone();
880 move || {
881 gate.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
882 drop(gate.opened.wait_while(lock(&gate.open), |open| !*open).unwrap());
883 Ok(Some(Zeroizing::new(value.to_string())))
884 }
885 }
886 fn open(&self) {
887 *lock(&self.open) = true;
888 self.opened.notify_all();
889 }
890 fn calls(&self) -> usize {
891 self.calls.load(std::sync::atomic::Ordering::SeqCst)
892 }
893 }
894
895 fn secret(value: &str) -> ReadResult {
896 Ok(Some(Zeroizing::new(value.to_string())))
897 }
898
899 #[test]
900 fn a_read_that_finishes_in_time_returns_its_value() {
901 let reads = SharedReads::new();
902 assert_eq!(reads.read("a", LONG, || secret("v")), Ok(secret("v")));
903 assert_eq!(reads.read("b", LONG, || Ok(None)), Ok(Ok(None)));
904 }
905
906 #[test]
907 fn retries_behind_an_unanswered_read_share_it_instead_of_queueing_more() {
908 let reads = SharedReads::new();
911 let gate = Gate::new();
912 for _ in 0..5 {
913 assert_eq!(reads.read("muxbus", SHORT, gate.read("v")), Err(RunOutcome::TimedOut));
914 }
915 std::thread::sleep(SHORT);
916 assert_eq!(gate.calls(), 1, "each retry started its own platform read");
917 gate.open();
918 }
919
920 #[test]
921 fn callers_that_join_a_read_all_get_its_answer() {
922 let reads = Arc::new(SharedReads::new());
923 let gate = Gate::new();
924 let waiters: Vec<_> = (0..3)
925 .map(|_| {
926 let (reads, read) = (reads.clone(), gate.read("secret"));
927 std::thread::spawn(move || reads.read("acct", LONG, read))
928 })
929 .collect();
930 std::thread::sleep(Duration::from_millis(300)); gate.open();
932 for waiter in waiters {
933 assert_eq!(waiter.join().unwrap(), Ok(secret("secret")));
934 }
935 assert_eq!(gate.calls(), 1);
936 }
937
938 #[test]
939 fn a_read_after_the_answer_reads_again() {
940 let reads = SharedReads::new();
942 let gate = Gate::new();
943 gate.open();
944 assert_eq!(reads.read("acct", LONG, gate.read("v")), Ok(secret("v")));
945 assert_eq!(reads.read("acct", LONG, gate.read("v")), Ok(secret("v")));
946 assert_eq!(gate.calls(), 2);
947 }
948
949 #[test]
950 fn accounts_are_read_separately() {
951 let reads = SharedReads::new();
952 let gate = Gate::new();
953 assert_eq!(reads.read("a", SHORT, gate.read("v")), Err(RunOutcome::TimedOut));
954 assert_eq!(reads.read("b", SHORT, gate.read("v")), Err(RunOutcome::TimedOut));
955 std::thread::sleep(SHORT);
956 assert_eq!(gate.calls(), 2);
957 gate.open();
958 }
959
960 #[test]
961 fn after_forget_the_next_read_starts_its_own_and_later_ones_share_that() {
962 let reads = SharedReads::new();
963 let (old, new) = (Gate::new(), Gate::new());
964 assert_eq!(reads.read("acct", SHORT, old.read("before")), Err(RunOutcome::TimedOut));
965 reads.forget("acct"); assert_eq!(reads.read("acct", SHORT, new.read("after")), Err(RunOutcome::TimedOut));
967 old.open();
969 std::thread::sleep(SHORT);
970 assert_eq!(reads.read("acct", SHORT, new.read("after")), Err(RunOutcome::TimedOut));
971 std::thread::sleep(SHORT);
972 assert_eq!((old.calls(), new.calls()), (1, 1));
973 new.open();
974 }
975
976 #[test]
977 fn only_a_write_that_succeeded_stops_sharing_the_waiting_read() {
978 let reads = SharedReads::new();
979 let gate = Gate::new();
980 assert_eq!(reads.read("acct", SHORT, gate.read("v")), Err(RunOutcome::TimedOut));
981 let _ = reads.after_write("acct", Err::<(), _>("keychain write failed".to_string()));
983 assert_eq!(reads.read("acct", SHORT, gate.read("v")), Err(RunOutcome::TimedOut));
984 std::thread::sleep(SHORT);
985 assert_eq!(gate.calls(), 1, "a failed write let a retry start a second read");
986 let _ = reads.after_write("acct", Ok(()));
988 assert_eq!(reads.read("acct", SHORT, gate.read("v")), Err(RunOutcome::TimedOut));
989 std::thread::sleep(SHORT);
990 assert_eq!(gate.calls(), 2);
991 gate.open();
992 }
993
994 #[test]
995 fn a_read_whose_thread_cannot_start_fails_and_does_not_block_the_next() {
996 let reads = SharedReads::new();
997 let refuse = |_: Box<dyn FnOnce() + Send>| Err(std::io::Error::other("no threads left"));
998 let failed = reads.read_with("acct", LONG, || Ok(None), refuse).unwrap();
999 assert!(failed.unwrap_err().contains("no threads left"));
1000 assert_eq!(reads.read("acct", LONG, || secret("v")), Ok(secret("v")));
1002 }
1003
1004 #[test]
1005 fn a_panicking_read_is_reported_as_such_and_the_next_read_tries_again() {
1006 let reads = SharedReads::new();
1009 assert_eq!(
1010 reads.read("acct", LONG, || panic!("simulated worker panic")),
1011 Err(RunOutcome::WorkerPanicked)
1012 );
1013 assert_eq!(reads.read("acct", LONG, || Ok(None)), Ok(Ok(None)));
1014 }
1015
1016 #[test]
1017 fn run_outcome_message_distinguishes_timeout_from_panic() {
1018 assert!(run_outcome_message("read", RunOutcome::TimedOut).contains("timed out"));
1019 assert!(run_outcome_message("read", RunOutcome::WorkerPanicked).contains("panicked"));
1020 }
1021}