1use std::path::Path;
12
13pub mod oauth_status {
23 pub const VALID: &str = "valid";
25 pub const EXPIRED: &str = "expired";
27 pub const NEEDS_REAUTH: &str = "needs_reauth";
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum OAuthProbeStatus {
39 Valid,
40 Expired,
41 NeedsReauth,
42}
43
44impl OAuthProbeStatus {
45 pub fn as_str(self) -> &'static str {
46 match self {
47 Self::Valid => oauth_status::VALID,
48 Self::Expired => oauth_status::EXPIRED,
49 Self::NeedsReauth => oauth_status::NEEDS_REAUTH,
50 }
51 }
52}
53
54pub fn claude_token_expiry_ms(dir: &str) -> Option<i64> {
58 let contents = std::fs::read_to_string(Path::new(dir).join(".credentials.json")).ok()?;
59 let json: serde_json::Value = serde_json::from_str(&contents).ok()?;
60 json.get("claudeAiOauth").and_then(|o| o.get("expiresAt")).and_then(|v| v.as_i64())
61}
62
63pub fn sign_in_file(provider: &str, dir: &Path) -> Option<std::path::PathBuf> {
66 match provider {
67 "claude" => Some(dir.join(".credentials.json")),
68 "codex" => Some(dir.join("auth.json")),
69 _ => super::cli_sign_in_files::credential_path(provider, dir),
70 }
71}
72
73pub const MAX_SIGN_IN_VALUE: usize = 8 * 1024;
76
77pub(super) fn sign_in_owner(dir: &str, what: &str) -> String {
79 format!("sign-in:{dir}:{what}")
80}
81
82pub fn release_sign_in(dir: &str) {
85 crate::backend::transcript::withhold::release_prefix(&sign_in_owner(dir, ""));
86}
87
88pub fn withhold_sign_in(dir: &str, json: &serde_json::Value) {
94 let oauth = json.get("claudeAiOauth").unwrap_or(json);
95 let text = |keys: [&str; 2]| {
96 keys.iter().find_map(|k| oauth.get(k).and_then(|v| v.as_str())).filter(|s| !s.is_empty() && s.len() <= MAX_SIGN_IN_VALUE)
97 };
98 let expires_at = oauth.get("expiresAt").and_then(|v| v.as_i64());
99 if let Some(access) = text(["accessToken", "access_token"]) {
100 match expires_at {
101 Some(at) => crate::backend::transcript::withhold::hold_until(&sign_in_owner(dir, "access"), access, at),
102 None => crate::backend::transcript::withhold::hold_kept(&sign_in_owner(dir, "access"), access),
103 }
104 }
105 if let Some(refresh) = text(["refreshToken", "refresh_token"]) {
106 crate::backend::transcript::withhold::hold_kept(&sign_in_owner(dir, "refresh"), refresh);
107 }
108}
109
110fn probe_codex_auth(dir: &Path) -> OAuthProbeStatus {
116 let path = dir.join("auth.json");
117 let json: Option<serde_json::Value> = std::fs::read_to_string(&path)
118 .ok()
119 .and_then(|s| serde_json::from_str(&s).ok());
120 json.iter().for_each(|j| super::sign_in_withhold::withhold_file("codex", dir, j));
121 let non_empty = |v: Option<&serde_json::Value>| v.and_then(|v| v.as_str()).is_some_and(|s| !s.is_empty());
122 let signed_in = json.as_ref().is_some_and(|j| {
123 non_empty(j.get("tokens").and_then(|t| t.get("refresh_token"))) || non_empty(j.get("OPENAI_API_KEY"))
124 });
125 if signed_in {
126 OAuthProbeStatus::Valid
127 } else {
128 tracing::debug!(
129 target: "identity",
130 path = %path.display(),
131 "oauth probe: codex auth.json missing or holds no credential — status=needs_reauth"
132 );
133 OAuthProbeStatus::NeedsReauth
134 }
135}
136
137fn probe_login_file(provider: &str, dir: &Path, now_ms: i64) -> Option<OAuthProbeStatus> {
140 match provider {
141 "codex" => Some(probe_codex_auth(dir)),
142 _ => super::cli_sign_in_files::probe(provider, dir, now_ms),
143 }
144}
145
146pub fn probe_oauth_status(
179 provider: &str,
180 dir: &str,
181 now_ms: i64,
182) -> Option<OAuthProbeStatus> {
183 let probe_path: std::path::PathBuf = match provider {
184 "codex" | "grok" | "muse" => return probe_login_file(provider, Path::new(dir), now_ms),
188 "claude" => Path::new(dir).join(".credentials.json"),
192 _ => return None,
193 };
194
195 let contents = match std::fs::read_to_string(&probe_path) {
196 Ok(s) => s,
197 Err(e) => {
198 if provider == "claude" && cfg!(target_os = "macos") {
199 tracing::debug!(
200 target: "identity",
201 provider,
202 path = %probe_path.display(),
203 error = %e,
204 "oauth probe: token file unreadable on macOS — Claude Code stores \
205 credentials in Keychain here, not this file, so this is not evidence \
206 of needs_reauth; leaving status unchanged"
207 );
208 return None;
209 }
210 tracing::debug!(
211 target: "identity",
212 provider,
213 path = %probe_path.display(),
214 error = %e,
215 "oauth probe: token file unreadable — status=needs_reauth"
216 );
217 return Some(OAuthProbeStatus::NeedsReauth);
218 }
219 };
220 let json: serde_json::Value = match serde_json::from_str(&contents) {
221 Ok(v) => { withhold_sign_in(dir, &v); v }
222 Err(e) => {
223 tracing::debug!(
224 target: "identity",
225 provider,
226 path = %probe_path.display(),
227 error = %e,
228 "oauth probe: token file parse failed — status=needs_reauth"
229 );
230 return Some(OAuthProbeStatus::NeedsReauth);
231 }
232 };
233
234 let expires_at_ms = json
239 .get("claudeAiOauth")
240 .and_then(|o| o.get("expiresAt"))
241 .and_then(|v| v.as_i64())
242 .or_else(|| json.get("expiresAt").and_then(|v| v.as_i64()))
243 .or_else(|| json.get("expires_at").and_then(|v| v.as_i64()));
244
245 let has_refresh = json
246 .get("claudeAiOauth")
247 .and_then(|o| o.get("refreshToken"))
248 .and_then(|v| v.as_str())
249 .map(|s| !s.is_empty())
250 .unwrap_or(false)
251 || json
252 .get("refresh_token")
253 .and_then(|v| v.as_str())
254 .map(|s| !s.is_empty())
255 .unwrap_or(false);
256
257 if provider == "claude" {
261 let has_access = json
262 .get("claudeAiOauth")
263 .and_then(|o| o.get("accessToken"))
264 .and_then(|v| v.as_str())
265 .map(|s| !s.is_empty())
266 .unwrap_or(false);
267 if !has_access && !has_refresh {
268 return Some(OAuthProbeStatus::NeedsReauth);
269 }
270 }
271
272 match expires_at_ms {
273 Some(exp) if exp <= now_ms => {
274 if has_refresh {
279 Some(OAuthProbeStatus::Expired)
280 } else {
281 Some(OAuthProbeStatus::NeedsReauth)
282 }
283 }
284 Some(_) => Some(OAuthProbeStatus::Valid),
285 None => {
286 tracing::debug!(
291 target: "identity",
292 provider,
293 path = %probe_path.display(),
294 "oauth probe: file present but no parseable expiry — status=valid (best-effort)"
295 );
296 Some(OAuthProbeStatus::Valid)
297 }
298 }
299}
300
301#[cfg(test)]
302mod tests {
303 use super::*;
304
305 fn write_claude_creds(
312 dir: &std::path::Path,
313 expires_ms: i64,
314 with_refresh: bool,
315 ) {
316 std::fs::create_dir_all(dir).unwrap();
317 let body = serde_json::json!({
318 "claudeAiOauth": {
319 "accessToken": "test-access",
320 "refreshToken": if with_refresh { "test-refresh" } else { "" },
321 "expiresAt": expires_ms,
322 }
323 });
324 std::fs::write(
325 dir.join(".credentials.json"),
326 serde_json::to_string(&body).unwrap(),
327 )
328 .unwrap();
329 }
330
331 #[test]
332 fn a_deleted_accounts_sign_in_values_are_released_and_another_accounts_stay() {
333 use crate::backend::transcript::withhold;
334 let (a, b) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
335 let now = agentmux_common::time::now_ms();
336 write_sign_in(a.path(), "canary-release-access-A1", "canary-release-refresh-A1", now + 3_600_000);
337 write_sign_in(b.path(), "canary-release-access-B1", "canary-release-refresh-B1", now + 3_600_000);
338 for dir in [a.path(), b.path()] {
339 probe_oauth_status("claude", dir.to_str().unwrap(), now);
340 }
341 release_sign_in(a.path().to_str().unwrap());
342 for value in ["canary-release-access-A1", "canary-release-refresh-A1"] {
343 assert_eq!(withhold::text(value), value, "released with its account");
344 }
345 for value in ["canary-release-access-B1", "canary-release-refresh-B1"] {
346 assert_eq!(withhold::text(value), withhold::MARK, "another account's stays");
347 }
348 }
349
350 #[test]
351 fn probe_oauth_status_unknown_provider_returns_none() {
352 let r = probe_oauth_status("github", "/tmp/whatever", 0);
358 assert_eq!(r, None);
359 }
360
361 #[test]
362 fn probe_oauth_status_missing_dir_is_needs_reauth_for_codex() {
363 let r = probe_oauth_status("codex", "/definitely/does/not/exist-xyz-9q", 0);
368 assert_eq!(r, Some(OAuthProbeStatus::NeedsReauth));
369 }
370
371 #[test]
374 fn a_codex_sign_in_is_read_from_auth_json() {
375 let probe = |contents: Option<&str>| {
376 let tmp = tempfile::tempdir().unwrap();
377 if let Some(c) = contents {
378 std::fs::write(tmp.path().join("auth.json"), c).unwrap();
379 }
380 probe_oauth_status("codex", tmp.path().to_str().unwrap(), 0)
381 };
382 let chatgpt = r#"{"auth_mode":"chatgpt","OPENAI_API_KEY":null,"tokens":{"id_token":"x","access_token":"y","refresh_token":"z","account_id":"a"},"last_refresh":"2026-10-22T00:00:00Z"}"#;
383 assert_eq!(probe(Some(chatgpt)), Some(OAuthProbeStatus::Valid), "a ChatGPT sign-in");
384 assert_eq!(probe(Some(r#"{"OPENAI_API_KEY":"sk-test"}"#)), Some(OAuthProbeStatus::Valid), "an API-key sign-in");
385 assert_eq!(probe(Some(r#"{"OPENAI_API_KEY":null,"tokens":{"refresh_token":""}}"#)), Some(OAuthProbeStatus::NeedsReauth));
386 assert_eq!(probe(Some("not json")), Some(OAuthProbeStatus::NeedsReauth));
387 assert_eq!(probe(None), Some(OAuthProbeStatus::NeedsReauth), "signed out: no auth.json");
388 }
389
390 #[test]
391 fn a_claude_shaped_credentials_file_does_not_sign_codex_in() {
392 let tmp = tempfile::tempdir().unwrap();
393 std::fs::write(
394 tmp.path().join(".credentials.json"),
395 r#"{"claudeAiOauth":{"refreshToken":"r","expiresAt":9999999999999}}"#,
396 )
397 .unwrap();
398 let r = probe_oauth_status("codex", tmp.path().to_str().unwrap(), 0);
399 assert_eq!(r, Some(OAuthProbeStatus::NeedsReauth));
400 }
401
402 #[cfg(target_os = "macos")]
403 #[test]
404 fn probe_oauth_status_missing_dir_is_none_for_claude_on_macos() {
405 let r = probe_oauth_status("claude", "/definitely/does/not/exist-xyz-9q", 0);
414 assert_eq!(r, None);
415 }
416
417 #[cfg(not(target_os = "macos"))]
418 #[test]
419 fn probe_oauth_status_missing_dir_is_needs_reauth_for_claude_off_macos() {
420 let r = probe_oauth_status("claude", "/definitely/does/not/exist-xyz-9q", 0);
423 assert_eq!(r, Some(OAuthProbeStatus::NeedsReauth));
424 }
425
426 fn write_sign_in(dir: &std::path::Path, access: &str, refresh: &str, expires_ms: i64) {
427 let body = serde_json::json!({ "claudeAiOauth": { "accessToken": access, "refreshToken": refresh, "expiresAt": expires_ms } });
428 std::fs::write(dir.join(".credentials.json"), body.to_string()).unwrap();
429 }
430
431 #[test]
432 fn the_tokens_in_a_sign_in_file_are_withheld_when_it_is_read_and_a_renewed_pair_replaces_them() {
433 use crate::backend::transcript::withhold;
434 let tmp = tempfile::tempdir().unwrap();
435 let dir = tmp.path().to_str().unwrap();
436 let now = agentmux_common::time::now_ms();
437 write_sign_in(tmp.path(), "canary-signin-access-0001", "canary-signin-refresh-0001", now + 3_600_000);
438 assert_eq!(withhold::text("a canary-signin-access-0001"), "a canary-signin-access-0001", "not read yet");
439 probe_oauth_status("claude", dir, now);
440 assert_eq!(withhold::text("a canary-signin-access-0001"), format!("a {}", withhold::MARK));
441 assert_eq!(withhold::text("r canary-signin-refresh-0001"), format!("r {}", withhold::MARK));
442
443 write_sign_in(tmp.path(), "canary-signin-access-0002", "canary-signin-refresh-0002", now + 7_200_000);
446 probe_oauth_status("claude", dir, now);
447 assert_eq!(withhold::text("a canary-signin-access-0002"), format!("a {}", withhold::MARK));
448 assert_eq!(withhold::text("r canary-signin-refresh-0002"), format!("r {}", withhold::MARK));
449 assert_eq!(withhold::text("a canary-signin-access-0001"), format!("a {}", withhold::MARK));
450 assert_eq!(withhold::text("r canary-signin-refresh-0001"), format!("r {}", withhold::MARK));
451
452 std::fs::write(tmp.path().join(".credentials.json"), r#"{"claudeAiOauth":{}}"#).unwrap();
454 probe_oauth_status("claude", dir, now);
455 assert_eq!(withhold::text("r canary-signin-refresh-0002"), format!("r {}", withhold::MARK));
456 }
457
458 #[test]
459 fn an_access_token_is_withheld_only_until_it_expires_and_its_refresh_token_stays() {
460 use crate::backend::transcript::withhold;
461 let tmp = tempfile::tempdir().unwrap();
462 let dir = tmp.path().to_str().unwrap();
463 let now = agentmux_common::time::now_ms();
464 write_sign_in(tmp.path(), "canary-signin-access-0003", "canary-signin-refresh-0003", now - 1);
466 probe_oauth_status("claude", dir, now);
467 assert_eq!(withhold::text("a canary-signin-access-0003"), "a canary-signin-access-0003");
468 assert_eq!(withhold::text("r canary-signin-refresh-0003"), format!("r {}", withhold::MARK));
469 }
470
471 #[test]
472 fn probe_oauth_status_future_expiry_is_valid() {
473 let tmp = tempfile::tempdir().unwrap();
474 let now_ms = 1_700_000_000_000;
475 write_claude_creds(tmp.path(), now_ms + 3_600_000, true);
476 let r = probe_oauth_status("claude", tmp.path().to_str().unwrap(), now_ms);
477 assert_eq!(r, Some(OAuthProbeStatus::Valid));
478 }
479
480 #[test]
481 fn probe_oauth_status_past_expiry_with_refresh_is_expired() {
482 let tmp = tempfile::tempdir().unwrap();
483 let now_ms = 1_700_000_000_000;
484 write_claude_creds(tmp.path(), now_ms - 1, true);
485 let r = probe_oauth_status("claude", tmp.path().to_str().unwrap(), now_ms);
486 assert_eq!(r, Some(OAuthProbeStatus::Expired));
487 }
488
489 #[test]
490 fn probe_oauth_status_past_expiry_no_refresh_is_needs_reauth() {
491 let tmp = tempfile::tempdir().unwrap();
495 let now_ms = 1_700_000_000_000;
496 write_claude_creds(tmp.path(), now_ms - 1, false);
497 let r = probe_oauth_status("claude", tmp.path().to_str().unwrap(), now_ms);
498 assert_eq!(r, Some(OAuthProbeStatus::NeedsReauth));
499 }
500
501 #[test]
502 fn probe_oauth_status_malformed_json_is_needs_reauth() {
503 let tmp = tempfile::tempdir().unwrap();
504 std::fs::write(tmp.path().join(".credentials.json"), "{ not json").unwrap();
505 let r = probe_oauth_status("claude", tmp.path().to_str().unwrap(), 0);
506 assert_eq!(r, Some(OAuthProbeStatus::NeedsReauth));
507 }
508
509 #[test]
512 fn probe_oauth_status_claude_file_with_no_tokens_is_needs_reauth() {
513 for body in [r#"{}"#, r#"{"claudeAiOauth":{}}"#, r#"{"claudeAiOauth":{"accessToken":"","refreshToken":""}}"#] {
514 let tmp = tempfile::tempdir().unwrap();
515 std::fs::write(tmp.path().join(".credentials.json"), body).unwrap();
516 let r = probe_oauth_status("claude", tmp.path().to_str().unwrap(), 0);
517 assert_eq!(r, Some(OAuthProbeStatus::NeedsReauth), "{body}");
518 }
519 }
520
521 #[test]
524 fn probe_oauth_status_claude_with_only_a_refresh_token_is_not_signed_out() {
525 let tmp = tempfile::tempdir().unwrap();
526 std::fs::write(
527 tmp.path().join(".credentials.json"),
528 r#"{"claudeAiOauth":{"refreshToken":"rt","expiresAt":1}}"#,
529 )
530 .unwrap();
531 let r = probe_oauth_status("claude", tmp.path().to_str().unwrap(), 1_700_000_000_000);
532 assert_eq!(r, Some(OAuthProbeStatus::Expired));
533 }
534}