Skip to main content

agentmux_srv_core/backend/container/
keychain_credentials.rs

1//! A container agent's login for a Claude account whose credentials are in the macOS Keychain.
2//!
3//! On Linux and Windows the bound account's `.credentials.json` is bind-mounted into the container. On macOS
4//! Claude Code keeps that login in the Keychain, under `Claude Code-credentials-<first 8 hex of the sha256 of
5//! the config dir>`, and never writes the file, so nothing was mounted and the container started signed out.
6//!
7//! Here srv reads that one Keychain entry and writes it to a staging file of its own, which is mounted like the
8//! account's file would be. The Keychain stays the source of truth: when either side refreshes the token the
9//! newer `expiresAt` wins, and a refresh made in the container is written back to the same entry, because refresh
10//! tokens rotate and the host's login would otherwise stop working.
11//!
12//! The guards:
13//! - only the bound account's own entry is read or written, by the service name computed from its config dir;
14//!   nothing is searched or listed;
15//! - the staging folder is `<AgentMux root>/container-credentials/<container>/<account>` (`0700`, the file `0600`), never
16//!   in the account's dir or the agent's workspace, and it is deleted with the container;
17//! - a refresh is written back only when the container's `.claude.json` names the same account as the host's
18//!   and the staged `expiresAt` is newer than the Keychain's;
19//! - each read and each write-back is one audit row (agent, account, direction), and no value is ever logged.
20
21use std::path::{Path, PathBuf};
22
23use serde::{Deserialize, Serialize};
24use zeroize::Zeroizing;
25
26use super::{ContainerManager, ContainerMountSpec, CLAUDE_CREDENTIALS_FILE};
27
28/// Folder under the AgentMux root that holds one staging folder per container.
29pub(crate) const STAGING_ROOT: &str = "container-credentials";
30const META_FILE: &str = "meta.json";
31
32/// Where an account's own login lives on the host, as far as this module needs it: the macOS Keychain, or the
33/// account's `.credentials.json`. One entry is addressed by its service name.
34pub(crate) trait Keychain {
35    /// The entry's data, or `None` when there is no such entry.
36    fn read(&self, service: &str) -> Result<Option<Zeroizing<String>>, String>;
37    /// Replaces the data of the existing entry.
38    fn write(&self, service: &str, value: &str) -> Result<(), String>;
39    /// The service name of the login of `config_dir` in this store.
40    fn service_of(&self, config_dir: &str) -> String {
41        service_name(config_dir)
42    }
43}
44
45/// The account's own login file: `<config dir>/.credentials.json`, where Claude Code keeps it on Linux and Windows
46/// (and on macOS for an account that has one). Nothing binds it into a container any more, so it is written by
47/// replacing the file, never in place: a host CLI reading it never sees half of it.
48pub(crate) struct FileLogin;
49
50impl Keychain for FileLogin {
51    fn read(&self, service: &str) -> Result<Option<Zeroizing<String>>, String> {
52        match std::fs::read_to_string(service) {
53            Ok(text) => Ok(Some(Zeroizing::new(text))),
54            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
55            Err(e) => Err(e.to_string()),
56        }
57    }
58
59    fn write(&self, service: &str, value: &str) -> Result<(), String> {
60        // A name of its own for each write: two syncs never share a temporary file.
61        static WRITES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
62        let file = Path::new(service);
63        let n = WRITES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
64        let temp = file.with_extension(format!("agentmux-{}-{n}", std::process::id()));
65        let wrote = put_file(&temp, value).and_then(|()| std::fs::rename(&temp, file));
66        if wrote.is_err() {
67            let _ = std::fs::remove_file(&temp);
68        }
69        wrote.map_err(|e| e.to_string())
70    }
71
72    fn service_of(&self, config_dir: &str) -> String {
73        Path::new(config_dir).join(CLAUDE_CREDENTIALS_FILE).to_string_lossy().into_owned()
74    }
75}
76
77/// The store that holds the login of `config_dir`: its file when it has one, else (macOS) the Keychain.
78pub(crate) fn store_for(config_dir: &str) -> Box<dyn Keychain + Send> {
79    #[cfg(target_os = "macos")]
80    if !Path::new(config_dir).join(CLAUDE_CREDENTIALS_FILE).is_file() {
81        return Box::new(SecurityCli);
82    }
83    let _ = config_dir;
84    Box::new(FileLogin)
85}
86
87/// The service name Claude Code uses on macOS for the login of `config_dir` (an absolute path, as
88/// `CLAUDE_CONFIG_DIR` holds it).
89pub(crate) fn service_name(config_dir: &str) -> String {
90    use sha2::{Digest, Sha256};
91    let digest = Sha256::digest(config_dir.as_bytes());
92    format!("Claude Code-credentials-{}", hex::encode(&digest[..4]))
93}
94
95/// Which way a login moved.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub(crate) enum Direction {
98    /// The account's own login to a container's copy: seeded, refreshed by the host, or put back after a refusal.
99    KeychainToContainer,
100    ContainerToKeychain,
101    /// A container's refresh, pushed to another container's copy of the same account.
102    ContainerToSibling,
103}
104
105/// One thing done, or refused, with a login: what the audit row says. Never carries a value.
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub(crate) struct Moved {
108    pub direction: Direction,
109    /// The account's label (its email), or `unknown`.
110    pub account: String,
111    /// `Ok` when it was done; `Err` with the plain reason when it was refused or failed.
112    pub outcome: Result<(), String>,
113}
114
115#[derive(Serialize, Deserialize)]
116struct Meta {
117    config_dir: String,
118    /// A short digest of the refresh token this copy was last made level with the account's own login by. A copy
119    /// whose account has refreshed since was made from a refresh token the provider has already replaced, so what
120    /// the container holds is not a login to write back. Empty for a copy made before this was kept.
121    #[serde(default)]
122    seed: String,
123}
124
125/// How often a running container's copy of the login is looked at for a refresh.
126const WATCH_EVERY: std::time::Duration = std::time::Duration::from_secs(15);
127
128fn modified(file: &Path) -> Option<std::time::SystemTime> {
129    std::fs::metadata(file).and_then(|m| m.modified()).ok()
130}
131
132/// Whether the copy of `key` changed since it was last looked at. The first look of a key only notes it.
133fn changed_since_last_look(seen: &mut std::collections::HashMap<String, Option<std::time::SystemTime>>, key: &str, now: Option<std::time::SystemTime>) -> bool {
134    match seen.insert(key.to_string(), now) {
135        None => false,
136        Some(before) => before != now,
137    }
138}
139
140/// The lock of one account (by its config dir), held for a whole [`sync_account`].
141fn account_lock(config_dir: &str) -> std::sync::Arc<std::sync::Mutex<()>> {
142    static LOCKS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<std::sync::Mutex<()>>>>> = std::sync::OnceLock::new();
143    let mut locks = LOCKS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
144    locks.entry(config_dir.to_string()).or_default().clone()
145}
146
147/// A short digest of a login's refresh token, to tell whether two copies descend from one refresh. Not a secret,
148/// and never logged.
149fn refresh_digest(raw: &str) -> String {
150    use sha2::{Digest, Sha256};
151    let value: serde_json::Value = serde_json::from_str(raw).unwrap_or_default();
152    let token = value.pointer("/claudeAiOauth/refreshToken").and_then(|v| v.as_str()).unwrap_or_default();
153    if token.is_empty() {
154        return String::new();
155    }
156    hex::encode(&Sha256::digest(token.as_bytes())[..8])
157}
158
159/// The seed noted for the copy in `dir`, or empty.
160fn seed_of(dir: &Path) -> String {
161    std::fs::read_to_string(dir.join(META_FILE))
162        .ok()
163        .and_then(|text| serde_json::from_str::<Meta>(&text).ok())
164        .map(|meta| meta.seed)
165        .unwrap_or_default()
166}
167
168/// The expiry of a login in the Keychain's JSON, when that JSON holds a usable one.
169fn expires_at(raw: &str) -> Option<i64> {
170    let value: serde_json::Value = serde_json::from_str(raw).ok()?;
171    let oauth = value.get("claudeAiOauth")?;
172    for token in ["accessToken", "refreshToken"] {
173        if oauth.get(token)?.as_str()?.is_empty() {
174            return None;
175        }
176    }
177    oauth.get("expiresAt")?.as_i64()
178}
179
180/// The furthest ahead a login's `expiresAt` may be and still be taken as a real refresh. Claude's access tokens
181/// last hours, so a week is generous; a container can write its own `.credentials.json`, and without a limit a
182/// far-future `expiresAt` would outrank every later refresh the host makes.
183const MAX_EXPIRY_AHEAD_MS: i64 = 7 * 24 * 60 * 60 * 1000;
184
185/// Whether `expires_at` (milliseconds since the epoch) is no further ahead than a real login's.
186fn plausible_expiry(expires_at: i64) -> bool {
187    expires_at <= agentmux_common::time::now_ms().saturating_add(MAX_EXPIRY_AHEAD_MS)
188}
189
190/// The account a Claude config dir (host or container) is signed in as: its id and its email.
191fn account_in(claude_json: &str) -> (String, String) {
192    let value: serde_json::Value = serde_json::from_str(claude_json).unwrap_or_default();
193    let field = |name: &str| {
194        value
195            .pointer(&format!("/oauthAccount/{name}"))
196            .and_then(|v| v.as_str())
197            .unwrap_or_default()
198            .to_string()
199    };
200    (field("accountUuid"), field("emailAddress"))
201}
202
203fn host_account(config_dir: &str) -> (String, String) {
204    let text =
205        std::fs::read_to_string(Path::new(config_dir).join(".claude.json")).unwrap_or_default();
206    account_in(&text)
207}
208
209/// Whether a folder bound into a container (`bound`: the host side of every bind) is the folder that holds the
210/// staged logins, or one above it: the container would then see every container's copy, not its own.
211pub(crate) fn staging_is_exposed(root: &Path, bound: &[String]) -> bool {
212    let staging = root.join(STAGING_ROOT);
213    bound.iter().filter(|dir| !dir.is_empty()).any(|dir| staging.starts_with(Path::new(dir)))
214}
215
216/// The staging folder of the login of `config_dir` for `container_name`, under the AgentMux `root`. It is named by
217/// the account, so an agent bound to another account mounts another path: the container is then recreated (the
218/// mount source changed) and can't keep a bind to the previous account's file.
219pub(crate) fn staging_dir(root: &Path, container_name: &str, config_dir: &str) -> PathBuf {
220    use sha2::{Digest, Sha256};
221    let account = hex::encode(&Sha256::digest(config_dir.as_bytes())[..6]);
222    root.join(STAGING_ROOT).join(container_name).join(account)
223}
224
225#[cfg(unix)]
226fn private(path: &Path, mode: u32) -> std::io::Result<()> {
227    use std::os::unix::fs::PermissionsExt;
228    std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))
229}
230#[cfg(not(unix))]
231fn private(_: &Path, _: u32) -> std::io::Result<()> {
232    Ok(())
233}
234
235fn create_private_dir(dir: &Path) -> std::io::Result<()> {
236    std::fs::create_dir_all(dir)?;
237    // The account's folder and the two above it (the container's, and the shared root of all of them).
238    for folder in dir.ancestors().take(3) {
239        private(folder, 0o700)?;
240    }
241    Ok(())
242}
243
244/// Writes `value` to `file`: in place when it exists, so a container that has it bind-mounted keeps seeing the
245/// same file; created `0600` when it does not.
246fn put_file(file: &Path, value: &str) -> std::io::Result<()> {
247    use std::io::Write as _;
248    let mut options = std::fs::OpenOptions::new();
249    options.write(true).create(true).truncate(true);
250    #[cfg(unix)]
251    {
252        use std::os::unix::fs::OpenOptionsExt as _;
253        options.mode(0o600);
254    }
255    options.open(file)?.write_all(value.as_bytes())?;
256    private(file, 0o600)
257}
258
259/// Puts `raw`, a login that is now the account's own, in the staging folder, with the note of which config dir it
260/// is for and which refresh it is level with.
261fn stage(dir: &Path, file: &Path, config_dir: &str, raw: &str) -> Result<(), String> {
262    create_private_dir(dir).map_err(|e| format!("couldn't create the staging folder: {e}"))?;
263    put_file(file, raw).map_err(|e| format!("couldn't write the staged login: {e}"))?;
264    let meta = serde_json::to_string(&Meta { config_dir: config_dir.to_string(), seed: refresh_digest(raw) }).unwrap_or_default();
265    put_file(&dir.join(META_FILE), &meta).map_err(|e| format!("couldn't write the staging note: {e}"))
266}
267
268/// [`sync_account`] for the account the agent is bound to now, after dealing with the accounts it was bound to
269/// before: what an earlier account's login refreshed goes back to its own entry, and its staged login is deleted
270/// unless a refresh is still pending (then it stays, unmounted). Each account is synced on its own, so this does
271/// not recurse.
272pub(crate) fn prepare(
273    keychain: &dyn Keychain,
274    root: &Path,
275    container_name: &str,
276    config_dir: &str,
277    container_account: Option<&str>,
278    moved: &mut dyn FnMut(Moved),
279) -> Result<PathBuf, String> {
280    for earlier in staged_config_dirs(root, container_name)
281        .into_iter()
282        .filter(|earlier| earlier != config_dir)
283    {
284        let _ = sync_account(
285            keychain,
286            root,
287            container_name,
288            &earlier,
289            container_account,
290            &mut *moved,
291        );
292        if refresh_pending(keychain, root, container_name, &earlier) {
293            tracing::warn!(container = container_name, "container agent: keeping the staged login of an account the agent is no longer bound to, it holds a refresh the Keychain doesn't have yet");
294        } else {
295            remove_staging(root, container_name, &earlier);
296        }
297    }
298    sync_account(
299        keychain,
300        root,
301        container_name,
302        config_dir,
303        container_account,
304        moved,
305    )
306}
307
308/// Brings the staged login of `container_name` in step with the Keychain entry of `config_dir`, and returns the
309/// staging folder to mount (its `.credentials.json` is the login).
310///
311/// `container_account` is the account id the container's own `.claude.json` names, or `None` when it can't be
312/// told (the container isn't running, or the file isn't there): a refresh made in the container is then not
313/// written back, only the Keychain's newer login reaches the container.
314///
315/// `Err` when there is no login to give the container (no Keychain entry, or one that isn't a login), with the
316/// reason in plain words; nothing is left staged in that case.
317fn sync_account(
318    keychain: &dyn Keychain,
319    root: &Path,
320    container_name: &str,
321    config_dir: &str,
322    container_account: Option<&str>,
323    moved: &mut dyn FnMut(Moved),
324) -> Result<PathBuf, String> {
325    // One sync of an account at a time: what is read, compared and written (the account's login, this copy and the
326    // other containers' copies) is never changed under it by a sync for another container of the same account.
327    let lock = account_lock(config_dir);
328    let _one_at_a_time = lock.lock().unwrap_or_else(|e| e.into_inner());
329    let dir = staging_dir(root, container_name, config_dir);
330    let file = dir.join(CLAUDE_CREDENTIALS_FILE);
331    let service = keychain.service_of(config_dir);
332    let (host_uuid, label) = host_account(config_dir);
333    let label = if label.is_empty() {
334        "unknown".to_string()
335    } else {
336        label
337    };
338
339    let staged = std::fs::read_to_string(&file).ok().map(Zeroizing::new);
340    // Whatever this copy holds is kept out of every transcript from this look on, before anything is decided or written
341    // with it: a login that first appears here (the container's CLI refreshed) is not the account's yet.
342    if let Some(raw) = &staged {
343        withhold_login(&dir, raw);
344    }
345    let staged = staged.filter(|raw| expires_at(raw).is_some());
346    let in_keychain = match keychain.read(&service) {
347        Ok(entry) => entry.filter(|raw| expires_at(raw).is_some()),
348        Err(e) => {
349            let reason = format!("couldn't read the account's login from the Keychain: {e}");
350            moved(Moved {
351                direction: Direction::KeychainToContainer,
352                account: label,
353                outcome: Err(reason.clone()),
354            });
355            // A login that is already staged stays mounted and untouched, so the container is not changed under a
356            // running agent and a refresh it made is not lost; it is synced at the next start that can read.
357            return if staged.is_some() {
358                Ok(dir)
359            } else {
360                Err(reason)
361            };
362        }
363    };
364
365    match (in_keychain, staged) {
366        (None, None) => {
367            let _ = std::fs::remove_dir_all(&dir);
368            Err("this account has no login in the Keychain; sign in with it first".to_string())
369        }
370        // The Keychain entry is gone (signed out on the host) while a login is staged: leave both as they are and
371        // never create the entry again from here.
372        (None, Some(_)) => Ok(dir),
373        (Some(kc), None) => {
374            stage(&dir, &file, config_dir, &kc)?;
375            moved(Moved {
376                direction: Direction::KeychainToContainer,
377                account: label,
378                outcome: Ok(()),
379            });
380            Ok(dir)
381        }
382        (Some(kc), Some(staged)) => {
383            let (kc_expiry, staged_expiry) = (
384                expires_at(&kc).unwrap_or(0),
385                expires_at(&staged).unwrap_or(0),
386            );
387            if kc_expiry >= staged_expiry && kc.as_str() == staged.as_str() {
388                return Ok(dir);
389            }
390            if kc_expiry >= staged_expiry {
391                stage(&dir, &file, config_dir, &kc)?;
392                moved(Moved {
393                    direction: Direction::KeychainToContainer,
394                    account: label,
395                    outcome: Ok(()),
396                });
397            } else {
398                let copy = Copy { keychain, root, container_name, config_dir, dir: &dir, file: &file, service: &service, label: &label };
399                write_back(&copy, (&host_uuid, container_account), (&kc, &staged), moved);
400            }
401            Ok(dir)
402        }
403    }
404}
405
406/// Registers the tokens in a login read out of the container's copy in staging folder `folder` with the sign-in
407/// withhold, under owners named by that folder (a container can write its copy, so what it holds is not filed under
408/// the account's own owners).
409fn withhold_login(folder: &Path, raw: &str) {
410    if let Ok(json) = serde_json::from_str::<serde_json::Value>(raw) {
411        crate::identity::staged_watch::withhold_copy(folder, &json);
412    }
413}
414
415/// One container's staged login, and the account's own login it is level with.
416struct Copy<'a> {
417    keychain: &'a dyn Keychain,
418    root: &'a Path,
419    container_name: &'a str,
420    config_dir: &'a str,
421    dir: &'a Path,
422    file: &'a Path,
423    service: &'a str,
424    label: &'a str,
425}
426
427/// Why a container's login is not taken as the account's refresh, and whether the container is then given the
428/// account's own login back.
429struct Refusal {
430    reason: &'static str,
431    /// The container holds a login that is not this account's, or that the account has moved on from: it is no use
432    /// to keep, so it gets the account's own. Not set when the container may hold the only live copy of a refresh.
433    reseed: bool,
434}
435
436/// Whether the login a container refreshed (`staged`) can be taken as the account's (`kc`), by the guards the
437/// account must pass: the id is known, the container is signed in as it, the expiry is a real one, and the account
438/// has not refreshed since the copy was made (a copy made from an earlier refresh token is a dead pair).
439fn refusal(host_uuid: &str, container_account: Option<&str>, kc: &str, staged: &str, seed: &str) -> Option<Refusal> {
440    let refuse = |reason, reseed| Some(Refusal { reason, reseed });
441    if host_uuid.is_empty() {
442        return refuse("the host account's id isn't known, so the container's login can't be tied to it", false);
443    }
444    match container_account {
445        None => return refuse("the container can't say which account it is signed in as, so its login stays there", false),
446        Some(id) if id != host_uuid => return refuse("the container isn't signed in as the bound account, so its login is replaced by the account's own", true),
447        Some(_) => {}
448    }
449    if !expires_at(staged).is_some_and(plausible_expiry) {
450        return refuse("the container's login expires further ahead than a real one does, so it isn't kept", true);
451    }
452    if !seed.is_empty() && seed != refresh_digest(kc) {
453        return refuse("the account's login was refreshed after this copy was made, so the copy is replaced by the account's own", true);
454    }
455    None
456}
457
458/// A container's login is newer than the account's: takes it as the account's when the guards pass, and in the same
459/// step hands it to the account's file and to every other container's copy of the account, so no copy is left
460/// holding a refresh token the provider has already replaced. When the guards refuse it and the container's login
461/// is of no use, the container is given the account's own login at once. One audit row for each thing done.
462fn write_back(copy: &Copy, (host_uuid, container_account): (&str, Option<&str>), (kc, staged): (&str, &str), moved: &mut dyn FnMut(Moved)) {
463    let row = |direction, outcome: Result<(), String>| Moved { direction, account: copy.label.to_string(), outcome };
464    if let Some(refused) = refusal(host_uuid, container_account, kc, staged, &seed_of(copy.dir)) {
465        // One row for the whole event: what was refused, and (when it was) that the account's own login went back.
466        let mut reason = refused.reason.to_string();
467        if refused.reseed {
468            if let Err(e) = stage(copy.dir, copy.file, copy.config_dir, kc) {
469                reason = format!("{reason}; and putting the account's login back failed: {e}");
470            }
471        }
472        moved(row(Direction::ContainerToKeychain, Err(reason)));
473        return;
474    }
475    let outcome = with_login_of(kc, staged)
476        .ok_or_else(|| "the account's login or the container's can't be read as JSON".to_string())
477        .and_then(|merged| write_verified(copy.keychain, copy.service, &merged, kc));
478    let accepted = outcome.is_ok();
479    moved(row(Direction::ContainerToKeychain, outcome));
480    if accepted {
481        // The container's copy is now level with the account: note it, and give the others the same login.
482        let _ = stage(copy.dir, copy.file, copy.config_dir, staged);
483        push_to_siblings(copy, staged, moved);
484    }
485}
486
487/// Every other container's copy of this account that is older than `login` is replaced by it, in place, so a
488/// container that has the file bound sees it.
489fn push_to_siblings(copy: &Copy, login: &str, moved: &mut dyn FnMut(Moved)) {
490    let Some(newer) = expires_at(login) else { return };
491    let Ok(entries) = std::fs::read_dir(copy.root.join(STAGING_ROOT)) else { return };
492    for entry in entries.flatten() {
493        let sibling = entry.file_name().to_string_lossy().into_owned();
494        if sibling == copy.container_name {
495            continue;
496        }
497        let dir = staging_dir(copy.root, &sibling, copy.config_dir);
498        let file = dir.join(CLAUDE_CREDENTIALS_FILE);
499        let raw = std::fs::read_to_string(&file).ok().map(Zeroizing::new);
500        if let Some(raw) = &raw {
501            withhold_login(&dir, raw);
502        }
503        let held = raw.and_then(|raw| expires_at(&raw));
504        if held.is_some_and(|held| held < newer) {
505            let outcome = stage(&dir, &file, copy.config_dir, login);
506            moved(Moved { direction: Direction::ContainerToSibling, account: copy.label.to_string(), outcome });
507        }
508    }
509}
510
511/// Writes `value` to the entry and reads it back. When what is stored isn't `value`, the entry is put back to
512/// `previous`, so a bad write never leaves the host signed out.
513fn write_verified(
514    keychain: &dyn Keychain,
515    service: &str,
516    value: &str,
517    previous: &str,
518) -> Result<(), String> {
519    let wrote = keychain.write(service, value);
520    let stored_ok = matches!(keychain.read(service), Ok(Some(raw)) if same_json(&raw, value));
521    if wrote.is_ok() && stored_ok {
522        return Ok(());
523    }
524    if !stored_ok {
525        let _ = keychain.write(service, previous);
526    }
527    Err(match wrote {
528        Err(e) => format!("couldn't write the refreshed login to the Keychain: {e}"),
529        Ok(()) => "the Keychain didn't keep what was written, so the previous login was put back"
530            .to_string(),
531    })
532}
533
534/// Whether two JSON texts hold the same value, whatever their key order or spacing.
535fn same_json(a: &str, b: &str) -> bool {
536    match (
537        serde_json::from_str::<serde_json::Value>(a),
538        serde_json::from_str::<serde_json::Value>(b),
539    ) {
540        (Ok(a), Ok(b)) => a == b,
541        _ => false,
542    }
543}
544
545/// The Keychain's JSON with only its `claudeAiOauth` replaced by the staged file's: whatever else the host keeps
546/// in that entry stays as it is.
547fn with_login_of(keychain_json: &str, staged_json: &str) -> Option<String> {
548    let mut entry: serde_json::Value = serde_json::from_str(keychain_json).ok()?;
549    let staged: serde_json::Value = serde_json::from_str(staged_json).ok()?;
550    entry.as_object_mut()?.insert(
551        "claudeAiOauth".to_string(),
552        staged.get("claudeAiOauth")?.clone(),
553    );
554    serde_json::to_string(&entry).ok()
555}
556
557/// The config dirs that have a staged login for `container_name` (one per account it was bound to).
558pub(crate) fn staged_config_dirs(root: &Path, container_name: &str) -> Vec<String> {
559    let Ok(entries) = std::fs::read_dir(root.join(STAGING_ROOT).join(container_name)) else {
560        return Vec::new();
561    };
562    entries
563        .flatten()
564        .filter_map(|entry| std::fs::read_to_string(entry.path().join(META_FILE)).ok())
565        .filter_map(|text| serde_json::from_str::<Meta>(&text).ok())
566        .map(|meta| meta.config_dir)
567        .collect()
568}
569
570/// Whether the staged login of `config_dir` holds a refresh that is not in the Keychain yet: it expires later
571/// than the Keychain's, or the Keychain can't be read to tell. Deleting the staged login then would lose a
572/// rotated token.
573pub(crate) fn refresh_pending(
574    keychain: &dyn Keychain,
575    root: &Path,
576    container_name: &str,
577    config_dir: &str,
578) -> bool {
579    let staged = std::fs::read_to_string(
580        staging_dir(root, container_name, config_dir).join(CLAUDE_CREDENTIALS_FILE),
581    )
582    .ok()
583    .map(Zeroizing::new)
584    .and_then(|raw| expires_at(&raw));
585    let Some(staged) = staged.filter(|&expiry| plausible_expiry(expiry)) else {
586        return false;
587    };
588    match keychain.read(&keychain.service_of(config_dir)) {
589        Err(_) => true,
590        Ok(None) => false,
591        Ok(Some(raw)) => expires_at(&raw).is_none_or(|kc| staged > kc),
592    }
593}
594
595/// Deletes the staged login of `config_dir` for `container_name` (and the container's folder when it is empty).
596pub(crate) fn remove_staging(root: &Path, container_name: &str, config_dir: &str) {
597    let dir = staging_dir(root, container_name, config_dir);
598    if dir.exists() {
599        if let Err(e) = std::fs::remove_dir_all(&dir) {
600            tracing::warn!(container = container_name, error = %e, "container agent: couldn't delete the staged login");
601        }
602    }
603    let _ = std::fs::remove_dir(root.join(STAGING_ROOT).join(container_name));
604}
605
606/// The account id in the `.claude.json` that a Docker archive download holds (a tar with that one file).
607fn account_in_archive(tar_bytes: &[u8]) -> Option<String> {
608    use std::io::Read as _;
609    const LIMIT: u64 = 4 * 1024 * 1024;
610    let mut archive = tar::Archive::new(tar_bytes);
611    let mut file = archive.entries().ok()?.next()?.ok()?;
612    let mut text = String::new();
613    file.by_ref().take(LIMIT).read_to_string(&mut text).ok()?;
614    Some(account_in(&text).0).filter(|id| !id.is_empty())
615}
616
617/// What the pane says when a container agent's Claude login can't be given to its container on macOS.
618pub(super) fn no_login_message(reason: &str) -> String {
619    format!(
620        "This agent's Claude account can't sign in inside its container: {reason}. Sign in with the account under \
621         Connectors > Accounts (or bind an account that uses an API key), then send your message again."
622    )
623}
624
625/// The real Keychain, through `/usr/bin/security`: the entries Claude Code writes allow that tool to read them
626/// without a prompt.
627#[cfg(target_os = "macos")]
628pub(crate) struct SecurityCli;
629
630#[cfg(target_os = "macos")]
631impl SecurityCli {
632    const LIMIT: std::time::Duration = std::time::Duration::from_secs(10);
633
634    fn user() -> Result<String, String> {
635        std::env::var("USER")
636            .ok()
637            .filter(|u| !u.is_empty())
638            .ok_or_else(|| "no USER in the environment".to_string())
639    }
640
641    /// Runs `security` with `args` (and `stdin` when given), waits at most [`Self::LIMIT`], and returns the exit
642    /// code and stdout. Polls rather than spending a thread on the wait.
643    fn run(args: &[&str], stdin: Option<&str>) -> Result<(i32, Zeroizing<String>), String> {
644        use std::io::{Read as _, Write as _};
645        use std::process::{Command, Stdio};
646        let mut command = Command::new("/usr/bin/security");
647        command
648            .args(args)
649            .stdin(if stdin.is_some() {
650                Stdio::piped()
651            } else {
652                Stdio::null()
653            })
654            .stdout(Stdio::piped())
655            .stderr(Stdio::null());
656        // The tool needs nothing of this instance's identity.
657        crate::backend::pane_env::sanitize_external_std_command(&mut command);
658        let mut child = command.spawn().map_err(|e| e.to_string())?;
659        if let (Some(text), Some(mut pipe)) = (stdin, child.stdin.take()) {
660            pipe.write_all(text.as_bytes()).map_err(|e| e.to_string())?;
661        }
662        let deadline = std::time::Instant::now() + Self::LIMIT;
663        let status = loop {
664            if let Some(status) = child.try_wait().map_err(|e| e.to_string())? {
665                break status;
666            }
667            if std::time::Instant::now() >= deadline {
668                let _ = child.kill();
669                let _ = child.wait();
670                return Err("the Keychain didn't answer in time".to_string());
671            }
672            std::thread::sleep(std::time::Duration::from_millis(25));
673        };
674        let mut out = Zeroizing::new(String::new());
675        if let Some(mut pipe) = child.stdout.take() {
676            let _ = pipe.read_to_string(&mut out);
677        }
678        Ok((status.code().unwrap_or(-1), out))
679    }
680}
681
682/// The longest line `security -i` takes. Past about 4 KB it runs the first part as a command and then fails on the
683/// rest, which has already replaced the entry with a cut-off value.
684#[cfg(target_os = "macos")]
685const MAX_SECURITY_LINE: usize = 3900;
686
687/// How `security` is asked to replace the data of the entry `service` / `user`: the arguments, and the line for
688/// its stdin when there is one.
689#[cfg(target_os = "macos")]
690struct WriteCall {
691    args: Vec<String>,
692    stdin: Option<Zeroizing<String>>,
693}
694
695/// The call that replaces the entry's data. Through `security -i` while the line fits, so the login is read from
696/// stdin and never shows in a process listing; hex, so no quoting of the JSON is needed. A larger entry (one that
697/// keeps many MCP tokens) goes as the `-X` argument instead, which has no such limit: for a few milliseconds the
698/// login is then in the arguments of a process only the same user can list (the operator treats same-user processes as trusted).
699#[cfg(target_os = "macos")]
700fn write_call(service: &str, user: &str, value: &str) -> WriteCall {
701    let hex = Zeroizing::new(hex::encode(value));
702    let line = Zeroizing::new(format!(
703        "add-generic-password -U -s \"{service}\" -a \"{user}\" -X \"{}\"\n",
704        hex.as_str()
705    ));
706    if line.len() <= MAX_SECURITY_LINE {
707        return WriteCall {
708            args: vec!["-i".to_string()],
709            stdin: Some(line),
710        };
711    }
712    WriteCall {
713        args: [
714            "add-generic-password",
715            "-U",
716            "-s",
717            service,
718            "-a",
719            user,
720            "-X",
721            hex.as_str(),
722        ]
723        .map(String::from)
724        .to_vec(),
725        stdin: None,
726    }
727}
728
729#[cfg(target_os = "macos")]
730impl Keychain for SecurityCli {
731    fn read(&self, service: &str) -> Result<Option<Zeroizing<String>>, String> {
732        let user = Self::user()?;
733        let (code, out) = Self::run(
734            &["find-generic-password", "-s", service, "-a", &user, "-w"],
735            None,
736        )?;
737        match code {
738            0 => Ok(Some(Zeroizing::new(out.trim_end_matches('\n').to_string()))),
739            // errSecItemNotFound
740            44 => Ok(None),
741            other => Err(format!("security exited with {other}")),
742        }
743    }
744
745    fn write(&self, service: &str, value: &str) -> Result<(), String> {
746        let user = Self::user()?;
747        let call = write_call(service, &user, value);
748        let args: Vec<&str> = call.args.iter().map(String::as_str).collect();
749        let (code, _) = Self::run(&args, call.stdin.as_deref().map(String::as_str))?;
750        if code == 0 {
751            Ok(())
752        } else {
753            Err(format!("security exited with {code}"))
754        }
755    }
756}
757
758impl ContainerManager {
759    /// Stages the login of the account whose config dir is `config_dir` for the container about to be created, and
760    /// returns the folder to mount as the account's credentials; `Err` with the reason in plain words when there is
761    /// no login to give. The container never gets the account's own file: it holds a copy of its own.
762    pub async fn stage_login(&self, container_name: &str, config_dir: &str, spec: &ContainerMountSpec) -> Result<String, String> {
763        let root = agentmux_common::data_paths::agentmux_root().map_err(|e| format!("AgentMux's data folder isn't available: {e}"))?;
764        if staging_is_exposed(&root, &spec.bound_host_dirs()) {
765            return Err("the folder that holds the container's copy of the login would be visible inside a container".to_string());
766        }
767        let dir = self.sync_login(container_name, config_dir, true).await.map(|dir| dir.to_string_lossy().into_owned())?;
768        self.watch_staged_login(container_name);
769        Ok(dir)
770    }
771
772    /// While the container runs, a refresh its CLI makes in its copy is taken at once (to the account's file and the
773    /// other containers' copies), not at the next start or removal: the copy's modification time is looked at every
774    /// [`WATCH_EVERY`], and a change is synced. One watch per container; it ends when the container's copies are gone.
775    fn watch_staged_login(&self, container_name: &str) {
776        static WATCHED: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> = std::sync::OnceLock::new();
777        let watched = WATCHED.get_or_init(Default::default);
778        if !watched.lock().unwrap_or_else(|e| e.into_inner()).insert(container_name.to_string()) {
779            return;
780        }
781        let (cm, name) = (self.clone(), container_name.to_string());
782        tokio::spawn(async move {
783            cm.watch_loop(&name).await;
784            watched.lock().unwrap_or_else(|e| e.into_inner()).remove(&name);
785        });
786    }
787
788    async fn watch_loop(&self, container_name: &str) {
789        let mut seen = std::collections::HashMap::new();
790        // What the start just synced is the baseline: a refresh in the first moments is a change from it.
791        if let Ok(root) = agentmux_common::data_paths::agentmux_root() {
792            for config_dir in staged_config_dirs(&root, container_name) {
793                let file = staging_dir(&root, container_name, &config_dir).join(CLAUDE_CREDENTIALS_FILE);
794                changed_since_last_look(&mut seen, &config_dir, modified(&file));
795            }
796        }
797        loop {
798            tokio::time::sleep(WATCH_EVERY).await;
799            let Ok(root) = agentmux_common::data_paths::agentmux_root() else { return };
800            let dirs = staged_config_dirs(&root, container_name);
801            if dirs.is_empty() {
802                return;
803            }
804            for config_dir in dirs {
805                let file = staging_dir(&root, container_name, &config_dir).join(CLAUDE_CREDENTIALS_FILE);
806                if !changed_since_last_look(&mut seen, &config_dir, modified(&file)) {
807                    continue;
808                }
809                let _ = self.sync_login(container_name, &config_dir, false).await;
810                // What the sync itself wrote is not a change to sync again.
811                seen.insert(config_dir, modified(&file));
812            }
813        }
814    }
815
816    /// After a drift removal, which is followed at once by a create from the same mount spec: the folder `remove`
817    /// deleted is made again, since Docker refuses a bind mount whose source is missing.
818    pub(crate) async fn restage_login(&self, container_name: &str, spec: &ContainerMountSpec) {
819        if let Some(config_dir) = spec.staged_login_config_dir.as_deref() {
820            let _ = self.stage_login(container_name, config_dir, spec).await;
821        }
822    }
823
824    /// Before a container is removed: writes a login it refreshed back to the account, and to the other containers'
825    /// copies, while the container is still there to ask which account it is signed in as. Best effort; it never
826    /// fails the removal.
827    pub(crate) async fn write_back_login(&self, container_name: &str) {
828        if let Ok(root) = agentmux_common::data_paths::agentmux_root() {
829            for config_dir in staged_config_dirs(&root, container_name) {
830                let _ = self.sync_login(container_name, &config_dir, false).await;
831            }
832        }
833    }
834
835    /// After a container is removed: deletes its staged logins, except one that holds a refresh that did not reach
836    /// the account (it stays until a later sync can write it back).
837    pub(crate) async fn drop_staged_login(&self, container_name: &str) {
838        let Ok(root) = agentmux_common::data_paths::agentmux_root() else {
839            return;
840        };
841        for config_dir in staged_config_dirs(&root, container_name) {
842            let (root_for_check, name, dir) = (root.clone(), container_name.to_string(), config_dir.clone());
843            let pending = tokio::task::spawn_blocking(move || refresh_pending(&*store_for(&dir), &root_for_check, &name, &dir)).await.unwrap_or(true);
844            if pending {
845                tracing::warn!(container = container_name, "container agent: keeping the staged login, it holds a refresh the account doesn't have yet");
846                continue;
847            }
848            remove_staging(&root, container_name, &config_dir);
849        }
850    }
851
852    /// The account id the container's own `.claude.json` names, or `None` when there is no container or file. Read
853    /// through Docker's archive API, which works for a stopped container too: a container is stopped before it is
854    /// removed, and its login must be written back then.
855    async fn container_account(&self, container_name: &str) -> Option<String> {
856        use bollard::container::DownloadFromContainerOptions;
857        use futures_util::StreamExt as _;
858        const LIMIT: usize = 4 * 1024 * 1024;
859        let path = format!("{}/.claude.json", super::CONTAINER_CLAUDE_DIR);
860        let mut stream = self.inner.docker.download_from_container(container_name, Some(DownloadFromContainerOptions { path }));
861        let mut tar_bytes = Vec::new();
862        while let Some(chunk) = stream.next().await {
863            tar_bytes.extend_from_slice(&chunk.ok()?);
864            if tar_bytes.len() > LIMIT {
865                return None;
866            }
867        }
868        account_in_archive(&tar_bytes)
869    }
870
871    async fn sync_login(&self, container_name: &str, config_dir: &str, rebind_cleanup: bool) -> Result<PathBuf, String> {
872        let root = agentmux_common::data_paths::agentmux_root().map_err(|e| format!("AgentMux's data folder isn't available: {e}"))?;
873        let account = self.container_account(container_name).await;
874        let (name, dir) = (container_name.to_string(), config_dir.to_string());
875        let (result, rows) = tokio::task::spawn_blocking(move || {
876            let mut rows = Vec::new();
877            let sync = if rebind_cleanup { prepare } else { sync_account };
878            let result = sync(&*store_for(&dir), &root, &name, &dir, account.as_deref(), &mut |m| rows.push(m));
879            (result, rows)
880        })
881        .await
882        .map_err(|e| format!("reading the account's login was interrupted: {e}"))?;
883        for row in &rows {
884            audit(container_name, row);
885        }
886        match result {
887            Ok(dir) => Ok(dir),
888            Err(reason) => {
889                tracing::warn!(container = container_name, %reason, "container agent: no login to give the container");
890                Err(reason)
891            }
892        }
893    }
894}
895
896/// One audit row for a login that moved (or was refused), in the same trail as the fleet actions. The row names the
897/// container (which carries the agent's id) and the account's label; never a value.
898fn audit(container_name: &str, moved: &Moved) {
899    let (action, how) = match moved.direction {
900        Direction::KeychainToContainer => ("container_credential_read", "account to container"),
901        Direction::ContainerToKeychain => ("container_credential_writeback", "container to account"),
902        Direction::ContainerToSibling => ("container_credential_sibling", "container to the other containers' copies"),
903    };
904    let reason = format!("account {}: {how}", moved.account);
905    let error = moved.outcome.as_ref().err().map(String::as_str);
906    crate::backend::reactive::handler::get_global_handler().log_fleet_action_audit(
907        Some("agentmux"),
908        container_name,
909        "",
910        action,
911        moved.outcome.is_ok(),
912        error,
913        &uuid::Uuid::new_v4().to_string(),
914        Some(&reason),
915    );
916}
917
918#[cfg(test)]
919mod tests;