Skip to main content

agentmux_srv_core/identity/
secret_store.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! srv's secret storage: account API keys, OAuth accounts, MuxBus
5//! credentials, browser-pane logins.
6//!
7//! Backs `SecretRef::Keychain { service, account }`, which names an entry in
8//! *this store*, wherever it keeps secrets; the DB holds just the pointer plus
9//! non-secret metadata + a masked tail. Reads return a `Zeroizing<String>` so
10//! the plaintext is wiped from memory on drop.
11//!
12//! **Two backends**, chosen once at startup:
13//! - **The OS keychain** (macOS Keychain / Windows Credential Manager / Linux
14//!   Secret Service via the `keyring-core` crate). The default, and what the
15//!   desktop app always uses.
16//! - **A file store** ([`use_file_store`]): one `0600` file per entry in a
17//!   `0700` directory, for machines with no keychain — a container, a
18//!   server, CI. Headless srv uses it unless told otherwise
19//!   (docs/specs/SPEC_SRV_HEADLESS_MODE_2026_09_26.md §3.6). Secrets are
20//!   protected by file permissions (and the volume's own encryption), not
21//!   encrypted by srv: a key kept beside them would add nothing.
22//!
23//! There is no silent downgrade from one to the other: failures surface as
24//! errors. See docs/specs/archive/SPEC_TRUST_CENTER_2026_06_15.md §7 and §12.2.
25//!
26//! The rest of this comment is about the keychain backend.
27//!
28//! **macOS: srv never shows the keychain's consent dialog**
29//! ([`keychain_without_dialogs`]). A keychain item trusts the code identity
30//! that wrote it, plus any the person allowed. One written by a build with
31//! another identity (every srv before v0.59.16 had a versioned one; a
32//! `task dev` build changes identity on each rebuild) used to bring up "AgentMux
33//! Server wants to use your confidential information…" unasked, at startup,
34//! after an upgrade. Now such a read fails at once with [`NEEDS_CONSENT`],
35//! and each caller decides: the MuxBus sign-in counts as signed out
36//! ([`get_optional_if_trusted`]; signing in again writes a fresh entry), and
37//! everything else reports it. A write
38//! over such an item replaces it ([`put`]), so the new one trusts this build.
39//! docs/analysis/ANALYSIS_MACOS_KEYCHAIN_PROMPT_AFTER_UPGRADE_2026_10_21.md.
40//!
41//! **Reads are bounded by [`TIMEOUT`]; writes are not — see below.** Every
42//! operation here can require interactive OS consent ("App wants to access
43//! your confidential information...") the first time a given code
44//! signature touches a given entry, and that consent call has no
45//! cancellation mechanism: an unanswered prompt (headless process, dialog
46//! on another Space, no attached display session) blocks the underlying
47//! platform call indefinitely. Confirmed live — see
48//! `docs/retro/retro-macos-muxbus-keychain-prompt-storm-2026-08-19.md` §5.
49//!
50//! `get`/`get_optional` run the real platform call on a detached thread and
51//! give up waiting after `TIMEOUT`, so a stuck prompt bounds how long the
52//! CALLER waits (and any lock it's holding) instead of hanging it forever.
53//! This is safe specifically because a read has no side effect: if the
54//! timeout fires, the detached thread's eventual (possibly much later)
55//! result is just discarded — nothing acts on a stale read. At most one
56//! read per account is in flight ([`SharedReads`]): a retry while one is
57//! still waiting on a dialog joins it rather than queueing another dialog
58//! behind it.
59//!
60//! `put`/`delete` deliberately do NOT use this timeout (reagent + Codex,
61//! PR #2679 round 2): the same "detached thread keeps running after the
62//! caller gives up" behavior is unsafe for a MUTATION. A caller that treats
63//! a timed-out write as failure and proceeds — e.g. skipping a dependent DB
64//! write, or a rollback in `muxbus.rs` writing a different value to the
65//! same entry — can have the orphaned original write land afterward and
66//! silently clobber whatever the caller did next, with no ordering
67//! guarantee between them. There is no cancellation-equivalent compensation
68//! available (the platform call truly cannot be cancelled), so until one
69//! exists, an unbounded wait — the pre-existing, safe-if-slow behavior — is
70//! the correct tradeoff for anything that mutates state. A stuck consent
71//! prompt on a write still blocks its caller indefinitely; only reads are
72//! protected today.
73
74use 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
83/// Keychain service string — constant across all AgentMux secrets.
84pub const SERVICE: &str = "agentmux";
85
86/// How long a caller waits for a keychain operation before giving up. Long
87/// enough for a real user to notice and answer a genuine first-time consent
88/// prompt if they're looking at their screen; short enough that an
89/// unanswered/unanswerable one doesn't wedge whatever the caller is holding
90/// (e.g. `muxbus_save_lock`) indefinitely. See this module's doc comment.
91const TIMEOUT: Duration = Duration::from_secs(15);
92
93/// Why `run_with_timeout` gave up waiting — reagent P2: collapsing these
94/// into one outcome made a closure PANIC (sender dropped without sending,
95/// `mpsc::RecvTimeoutError::Disconnected`) misreport as "timed out after
96/// 15s" — actively misleading, since the operation actually failed
97/// immediately, not after waiting the full deadline.
98#[derive(Debug, PartialEq)]
99enum RunOutcome {
100    /// The deadline elapsed with no answer yet — the likely "stuck consent
101    /// prompt" case this module exists to bound.
102    TimedOut,
103    /// The worker thread's sender was dropped without sending — it panicked
104    /// before calling `f` to completion.
105    WorkerPanicked,
106}
107
108/// What a keychain read returns: `Ok(None)` when there's no entry.
109type ReadResult = Result<Option<Zeroizing<String>>, String>;
110
111/// Keychain reads, at most one in flight per account.
112///
113/// A read runs on a detached thread, and its caller gives up after a
114/// timeout; the platform call underneath can't be cancelled and stays
115/// queued behind an unanswered consent dialog. Without this, every retry
116/// queued another one: on 2026-10-08 an hour of once-a-minute retries
117/// behind one open dialog meant each Deny showed the next queued read's
118/// dialog, six in two seconds. Now a read of an account that already has
119/// one in flight waits on that one, under its own timeout, so an open
120/// dialog stays one dialog. Nothing is cached: a read that starts after the
121/// answer arrived reads again.
122struct SharedReads {
123    in_flight: Arc<Mutex<HashMap<String, Arc<PendingRead>>>>,
124}
125
126#[derive(Default)]
127struct PendingRead {
128    /// `None` until the read finishes; `Err(())` if it panicked.
129    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    /// Wait up to `timeout` for `account_id`'s read, starting it with `read`
139    /// unless one is already in flight. The `RunOutcome` is separate from
140    /// any error the read itself returns; callers fold it into their own
141    /// message (`run_outcome_message`).
142    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    /// [`read`](Self::read) with the thread start passed in, so a test can
155    /// make it fail.
156    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                        // Leave the map first, so a read that starts once the
174                        // answer is out reads again. Only if this is still the
175                        // account's entry: `forget` may have replaced it.
176                        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                        // Nothing will ever answer this entry: drop it, or every
186                        // later read of the account would wait on it and time out.
187                        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    /// Stop sharing `account_id`'s in-flight read: the next read starts its
207    /// own. Called after a write, so no read that starts after it can get
208    /// the value from before it.
209    fn forget(&self, account_id: &str) {
210        lock(&self.in_flight).remove(account_id);
211    }
212
213    /// Pass a write's result through, forgetting the account's in-flight
214    /// read only if the write succeeded. A failed write changed nothing, and
215    /// forgetting then would let the next retry start a second read beside
216    /// the one still blocked on a dialog.
217    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
234/// Install the OS credential store `keyring-core` hands entries to: the
235/// Keychain on macOS, the Credential Manager on Windows, the Secret Service on
236/// Linux. Until it has worked, every call tries again: the Secret Service
237/// connects when the store is made, and a session bus or keyring daemon that
238/// wasn't up yet shouldn't leave this process without credentials until restart.
239/// On Linux every call makes a new store, as keyring 2 connected on every call:
240/// the store keeps one Secret Service session and doesn't reconnect, so one
241/// kept for the life of the process would fail for good after the keyring
242/// daemon restarts.
243/// The stores name an entry the way keyring 2 did (service and user; on Windows
244/// the target `user.service`), so what it stored is found.
245fn 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
273/// What a keychain read or write of an item this build isn't trusted for
274/// fails with on macOS, instead of asking the person ([`is_needs_consent`]).
275pub 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
278/// Whether `err` (from [`get`], [`get_optional`] or [`put`]) is
279/// [`NEEDS_CONSENT`]: the entry exists, but this build may not use it
280/// without the person's consent. Not a transient failure, and not "no entry".
281pub fn is_needs_consent(err: &str) -> bool {
282    err.contains(NEEDS_CONSENT)
283}
284
285/// Turn off the keychain's consent and unlock dialogs for this process.
286/// macOS only (`SecKeychainSetUserInteractionAllowed`, process-wide): a call
287/// that would show one fails at once instead, with `errSecAuthFailed` for an
288/// item that doesn't trust this build, or `errSecInteractionNotAllowed` when
289/// the keychain is locked. Until it has worked, every keychain call tries
290/// again first and is refused if it still can't: never a call with dialogs on.
291fn 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            // The lock turns the dialogs back on when dropped; keep them off.
299            std::mem::forget(lock);
300            let _ = OFF.set(());
301        }
302    }
303    Ok(())
304}
305
306/// How a keychain error is reported: [`NEEDS_CONSENT`] for an item this build
307/// isn't trusted for, a locked keychain said plainly, anything else as is.
308fn 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
316/// `errSecAuthFailed`: with dialogs off, the item doesn't trust this build.
317const ERR_SEC_AUTH_FAILED: i32 = -25293;
318/// `errSecInteractionNotAllowed`: with dialogs off, the keychain is locked.
319const ERR_SEC_INTERACTION_NOT_ALLOWED: i32 = -25308;
320/// `errSecDuplicateItem`: what a write over an item that doesn't trust this
321/// build ends in (it can't be read to be updated, so a new one is added).
322const ERR_SEC_DUPLICATE_ITEM: i32 = -25299;
323/// `errSecInvalidOwnerEdit`: what the Keychain store's delete (`SecItemDelete`)
324/// ends in for an item that doesn't trust this build. keyring 2 deleted by
325/// item reference, which needs no consent, so it never met this.
326const ERR_SEC_INVALID_OWNER_EDIT: i32 = -25244;
327
328/// Delete the keychain item for `account` without reading it, which an item
329/// that doesn't trust this build allows: found by reference, never by its
330/// secret (`keyring-core`'s delete asks for the item's owner rights). `Ok(false)` when
331/// there is none. macOS only.
332#[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), // errSecItemNotFound
346        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
360/// Whether a failed keychain call means the item exists but doesn't trust
361/// this build: a read says `errSecAuthFailed`, a write `errSecDuplicateItem`,
362/// a delete `errSecInvalidOwnerEdit`.
363fn 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
367/// [`delete_without_reading`] as a `keyring_core` result, for [`replace_untrusted`].
368fn 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
382/// The macOS `OSStatus` behind a keychain error, if it carries one.
383fn 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
392/// Write with `set`; when the existing item doesn't trust this build
393/// (`needs_consent`), `delete` it and write again, so the new item does.
394/// Deleting needs no consent. `missing` is "no such item" for the delete.
395fn 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
411/// Build the keychain account string for an identity-account id.
412pub fn account_key(account_id: &str) -> String {
413    format!("acct:{account_id}")
414}
415
416/// Set when [`use_file_store`] chose the file store; unset means the keychain.
417static FILE_STORE: OnceLock<PathBuf> = OnceLock::new();
418
419/// Keep every secret in files under `dir` instead of the OS keychain, for
420/// the rest of this process. Called once at startup, before anything reads
421/// or writes a secret. Creates `dir` (mode `0700`) if needed.
422pub 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
429/// Where an isolated instance keeps its secrets: files under its own shared folder, or `None` only when it is not
430/// isolated (no `AGENTMUX_HOME_OVERRIDE`) or the keychain was asked for (`AGENTMUX_SECRET_STORE=keychain`, for a
431/// test of the keychain itself).
432fn 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    // The launcher's folders when it exported them; else the override's own `shared`: an instance started with only the
438    // override is isolated all the same, and never falls back to the keychain.
439    let shared = shared_dir.unwrap_or_else(|| PathBuf::from(home).join("shared"));
440    Some(shared.join("secrets"))
441}
442
443/// An isolated instance (started with `AGENTMUX_HOME_OVERRIDE`, as `task dev` always is) keeps its secrets in files
444/// under its own home and never in the person's OS keychain. The keychain is the person's: a test build that saved the
445/// first Vault entry would make the real Vault key there, trusted only by that build, and the person's own AgentMux
446/// could not read it (nor would an account key it saved be theirs). Called once at startup, before anything reads a
447/// secret; true when it chose the file store.
448pub 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/// What a try of the OS keychain found ([`probe_keychain`]).
459#[derive(Debug, Clone, PartialEq, Eq)]
460pub enum KeychainProbe {
461    /// A test entry was stored, read back and deleted.
462    Works,
463    /// The store could not be made: no Secret Service on the session bus, or no OS keychain at all.
464    Absent(String),
465    /// Nothing came back in time: a locked keyring waiting for a prompt, which a headless run has nobody to answer.
466    NoAnswer,
467    /// The store answered, but the test entry could not be stored, read back or deleted.
468    RoundTripFailed(String),
469}
470
471/// Try the OS keychain as the server would use it: make the store, then store one test entry, read it back and delete it,
472/// giving up after `wait`. A call that waits on a prompt is left running on its own thread (the caller is a short program that
473/// then ends), never waited for.
474pub 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
503/// Which backend this process uses, for logs: `"keychain"` or `"file"`.
504pub fn backend_name() -> &'static str {
505    if FILE_STORE.get().is_some() {
506        "file"
507    } else {
508        "keychain"
509    }
510}
511
512/// Store (or overwrite) the secret for `account_id` in the OS keychain.
513///
514/// Deliberately unbounded — see this module's doc comment for why a
515/// timeout is unsafe for a mutation specifically (a timed-out-but-later-
516/// completing write can land after the caller has already acted on the
517/// assumption it failed).
518pub fn put(account_id: &str, secret: &str) -> Result<(), String> {
519    // From the moment srv holds the value, whether or not the write below succeeds.
520    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    // An entry saved by a build macOS doesn't trust for it can't be written
526    // over without consent: replace it, so the new one trusts this build.
527    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
537/// Read the secret for `account_id`. Returned wrapped in `Zeroizing` so it
538/// is wiped on drop. Resolved at agent spawn time when injecting env vars.
539pub 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
547/// Read the secret for `account_id`, distinguishing "no entry stored yet"
548/// (`Ok(None)`) from a real storage failure (`Err`) — a locked keychain, no
549/// Secret Service daemon running, permission denied, etc. `get` collapses
550/// both into the same `Err` variant, which is correct for its own callers
551/// (a spawn-time credential resolve should fail either way), but is the
552/// wrong shape for a caller that needs to tell "genuinely never logged in"
553/// apart from "storage is transiently broken" — treating a transient
554/// failure as "no credential" can silently present as a full logout. Use
555/// this variant when that distinction matters.
556pub 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
575/// [`get_optional`], except that an entry this build may not read without
576/// asking ([`NEEDS_CONSENT`]) counts as absent, and is logged. For the MuxBus
577/// sign-in: one saved by an older build is then signed out, and signing in
578/// again writes a fresh entry this build owns, so no dialog ever shows.
579/// Never for a key whose absence makes the caller create a new one (the Vault).
580pub 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
598/// Delete the secret for `account_id`. A missing entry is treated as
599/// success (idempotent delete).
600///
601/// Deliberately unbounded — see this module's doc comment for why a
602/// timeout is unsafe for a mutation specifically.
603pub 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        // It can't be read, which keyring-core's delete needs; it can be deleted.
611        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
629/// The file store. Each entry is one file named by the SHA-256 of its
630/// account key, so no key text (ids, hostnames) reaches a file name and no
631/// key can escape the directory. No timeouts: file operations don't wait
632/// on a user.
633pub 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    /// Create `dir` if needed and make it owner-only (`0700`), also when it
644    /// already existed with wider permissions.
645    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    /// Write via a fresh `0600` temp file and a rename, so a reader never
666    /// sees a partial secret and a crash never leaves one behind.
667    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        // (calls, set results in order, delete result)
714        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        // Any other failure is reported as it is, and nothing is deleted.
736        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        // A delete of an item saved by another build ends in errSecInvalidOwnerEdit
754        // (Keychain store 1.0.2 deletes with SecItemDelete); it is deleted by reference instead.
755        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    /// Against the real login keychain: an `agentmux` entry that trusts no
761    /// app (as one saved by an older srv looks to this build) is reported as
762    /// NEEDS_CONSENT at once, with no dialog, and a write replaces it with one
763    /// this build can read. `cargo test -p agentmux-srv-core -- --ignored needs_consent_live`
764    #[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        // Deleting what isn't there is fine, as with the keychain.
803        file::delete(&dir, &key).unwrap();
804        // Only the entries themselves are left: no temp files.
805        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        // Keys with separators and traversal text stay inside the directory.
815        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        // An existing, wider directory is tightened.
838        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    /// A fake platform read: counts how often it's called, and each call
867    /// blocks until `open`, like a read held by an unanswered dialog.
868    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        // 2026-10-08: once-a-minute retries behind one open dialog queued a
909        // read each, and every Deny showed the next one's dialog.
910        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)); // all three are waiting
931        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        // No caching: a later read must see a later value.
941        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"); // a write happened
966        assert_eq!(reads.read("acct", SHORT, new.read("after")), Err(RunOutcome::TimedOut));
967        // The old read finishing must not drop the new one from the map.
968        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        // A failed write changed nothing: retries keep joining the waiting read.
982        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        // A write that succeeded did: the next read starts its own.
987        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        // Not left waiting on a read that never started.
1001        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        // A panic must not be reported as "timed out": it failed at once,
1007        // not after the full deadline.
1008        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}