1use std::path::{Path, PathBuf};
22
23use serde::{Deserialize, Serialize};
24use zeroize::Zeroizing;
25
26use super::{ContainerManager, ContainerMountSpec, CLAUDE_CREDENTIALS_FILE};
27
28pub(crate) const STAGING_ROOT: &str = "container-credentials";
30const META_FILE: &str = "meta.json";
31
32pub(crate) trait Keychain {
35 fn read(&self, service: &str) -> Result<Option<Zeroizing<String>>, String>;
37 fn write(&self, service: &str, value: &str) -> Result<(), String>;
39 fn service_of(&self, config_dir: &str) -> String {
41 service_name(config_dir)
42 }
43}
44
45pub(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 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
77pub(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
87pub(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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub(crate) enum Direction {
98 KeychainToContainer,
100 ContainerToKeychain,
101 ContainerToSibling,
103}
104
105#[derive(Debug, Clone, PartialEq, Eq)]
107pub(crate) struct Moved {
108 pub direction: Direction,
109 pub account: String,
111 pub outcome: Result<(), String>,
113}
114
115#[derive(Serialize, Deserialize)]
116struct Meta {
117 config_dir: String,
118 #[serde(default)]
122 seed: String,
123}
124
125const 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
132fn 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
140fn 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
147fn 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
159fn 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
168fn 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
180const MAX_EXPIRY_AHEAD_MS: i64 = 7 * 24 * 60 * 60 * 1000;
184
185fn plausible_expiry(expires_at: i64) -> bool {
187 expires_at <= agentmux_common::time::now_ms().saturating_add(MAX_EXPIRY_AHEAD_MS)
188}
189
190fn 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
209pub(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
216pub(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 for folder in dir.ancestors().take(3) {
239 private(folder, 0o700)?;
240 }
241 Ok(())
242}
243
244fn 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
259fn 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
268pub(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
308fn 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 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 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 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 (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(©, (&host_uuid, container_account), (&kc, &staged), moved);
400 }
401 Ok(dir)
402 }
403 }
404}
405
406fn 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
415struct 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
427struct Refusal {
430 reason: &'static str,
431 reseed: bool,
434}
435
436fn 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
458fn 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 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 let _ = stage(copy.dir, copy.file, copy.config_dir, staged);
483 push_to_siblings(copy, staged, moved);
484 }
485}
486
487fn 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
511fn 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
534fn 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
545fn 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
557pub(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
570pub(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
595pub(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
606fn 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
617pub(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#[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 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 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#[cfg(target_os = "macos")]
685const MAX_SECURITY_LINE: usize = 3900;
686
687#[cfg(target_os = "macos")]
690struct WriteCall {
691 args: Vec<String>,
692 stdin: Option<Zeroizing<String>>,
693}
694
695#[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 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 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 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 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 seen.insert(config_dir, modified(&file));
812 }
813 }
814 }
815
816 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 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 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 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
896fn 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;