Skip to main content

agentmux_srv_core/identity/resolver/
oauth_probe.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! OAuth token-file probing: the [`oauth_status`] canonical-value
5//! constants, [`OAuthProbeStatus`], and [`probe_oauth_status`] itself.
6//!
7//! Split out of the single ~2193-line `resolver.rs` (pure relocation, no
8//! behavior change) — self-contained, on-disk OAuth token-file probing
9//! with no dependency on the rest of the resolver module.
10
11use std::path::Path;
12
13/// Canonical-value enumeration for OAuth-class `IdentityAccount.status`.
14///
15/// `IdentityAccount.status` is a `String` (free-form) at the SQLite layer
16/// — api-key rows keep using whatever the legacy paths wrote
17/// (`"unknown"`, `"ok"`, etc.). For oauth-class bindings we pin a small
18/// closed set per spec §4.4 so the frontend status-badge dispatch is
19/// deterministic and the resolver's expiry probe can never write an
20/// off-the-spec string. Every place the resolver SETS or READS an
21/// oauth-class status uses these constants.
22pub mod oauth_status {
23    /// Token file present and (probed) not expired.
24    pub const VALID: &str = "valid";
25    /// Access token expired; refresh likely succeeds.
26    pub const EXPIRED: &str = "expired";
27    /// Refresh rejected / file missing / parse error; user must Reconnect.
28    pub const NEEDS_REAUTH: &str = "needs_reauth";
29}
30
31/// Result of probing a per-bundle OAuth token directory.
32///
33/// Computed by [`probe_oauth_status`] reading the CLI's on-disk token
34/// file (e.g. `<dir>/.credentials.json` for Claude Code). Maps directly
35/// to [`oauth_status`] strings. Returned as an enum so the caller can
36/// branch without re-parsing the string.
37#[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
54/// When the access token in a Claude config dir's `.credentials.json` expires (unix ms), or `None`
55/// when the file is missing, unreadable or has no expiry. A token that expired before a turn failed
56/// on "OAuth access token has expired" cannot be the one that is there now if this reads later.
57pub 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
63/// The file `probe_oauth_status` reads the sign-in of `provider` from under config dir `dir`, or `None` for a provider
64/// it does not read a file for.
65pub 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
73/// The longest sign-in value that is withheld (bytes). A file a container can write could hold a value so large that
74/// the matcher of every withheld value no longer builds, so a longer one is not withheld.
75pub const MAX_SIGN_IN_VALUE: usize = 8 * 1024;
76
77/// Who holds a sign-in file's access or refresh token in the transcript withhold registry, named by the config dir.
78pub(super) fn sign_in_owner(dir: &str, what: &str) -> String {
79    format!("sign-in:{dir}:{what}")
80}
81
82/// Stops withholding every value read from the sign-in files under config dir `dir`: the account that owned the
83/// directory is deleted, and its credentials with it.
84pub fn release_sign_in(dir: &str) {
85    crate::backend::transcript::withhold::release_prefix(&sign_in_owner(dir, ""));
86}
87
88/// Keeps the tokens in a sign-in file just read out of every transcript: the CLI reads the file itself and renews both
89/// tokens while an agent runs, so each look at the file holds what is there now. An access token is withheld until
90/// its own expiry, even after a renewed one is in the file (the old one still works); a value with no known expiry
91/// stays withheld after the file holds another (up to `withhold::KEPT_PER_OWNER` per owner). A look that finds no
92/// token (a sign-out) leaves what was held.
93pub 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
110/// Codex's sign-in, from `<dir>/auth.json` (what `codex login` writes under
111/// `CODEX_HOME`): a ChatGPT sign-in has `tokens.refresh_token`, an API-key
112/// sign-in a non-empty `OPENAI_API_KEY`. Either is `Valid`; expiry is left to
113/// the CLI, which refreshes its own token. No file, or neither credential in
114/// it, is `NeedsReauth`. SPEC_CODEX_OAUTH_IN_CONNECTORS_AND_EMAIL_LABELS_2026_10_22.md §5.
115fn 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
137/// The providers whose sign-in is a plain file in the config dir: codex's, and the CLIs with no status
138/// command (grok, muse; see `cli_sign_in_files`).
139fn 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
146/// Cheap on-disk probe of the per-bundle OAuth token file for a
147/// provider. No network calls — just reads + parses the token JSON,
148/// then compares `expiresAt` against `now_ms`.
149///
150/// **Provider token-file shape (spec §4.4 + §4.5):**
151/// - `claude` — `<dir>/.credentials.json` with
152///   `{ "claudeAiOauth": { "accessToken", "refreshToken", "expiresAt": <ms> } }`
153///   (Anthropic's documented format — see
154///   `docs/specs/agentmux-isolated-auth.md` §1.6).
155/// - `codex` — `<dir>/auth.json`, see [`probe_codex_auth`].
156///
157/// **Returns** `Some(status)` on a definitive read, `None` when probing
158/// isn't supported for the provider (so the caller skips status
159/// updates rather than mis-writing `needs_reauth` for a provider whose
160/// file we just don't know how to parse yet).
161///
162/// **macOS caveat (`claude` only):** the Claude Code CLI stores OAuth
163/// credentials in the encrypted macOS Keychain, never in
164/// `<dir>/.credentials.json` — confirmed against Claude Code's own docs
165/// and empirically on a real per-account auth dir on this machine (zero
166/// `.credentials.json` present despite a working session). Unlike Linux
167/// and Windows, this is true regardless of `CLAUDE_CONFIG_DIR` — see
168/// `docs/retro/retro-macos-keychain-credential-isolation-gap-2026-08-17.md`.
169/// So on macOS, a missing `claude` token file is not evidence the account
170/// needs reauth — it's the expected, permanent shape, and reporting
171/// `NeedsReauth` here would be a standing false positive on every working
172/// macOS Claude account. `None` is returned instead (status left alone) —
173/// see the `None` variant's doc above for why that's the honest answer
174/// when this probe genuinely can't tell. `codex` is not
175/// covered by this carve-out: their macOS credential-storage behavior
176/// hasn't been verified, so their existing file-probe semantics are
177/// unchanged.
178pub 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 keeps its sign-in in `$CODEX_HOME/auth.json`, not
185        // `.credentials.json`; reading the latter marked every working
186        // Codex account needs_reauth at its first spawn.
187        "codex" | "grok" | "muse" => return probe_login_file(provider, Path::new(dir), now_ms),
188        // Claude Code writes to `<config_dir>/.credentials.json` per
189        // `docs/specs/provider-auth-isolation.md` (the agentmux-managed
190        // dir is what CLAUDE_CONFIG_DIR points at).
191        "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    // Claude shape — `claudeAiOauth.expiresAt` is ms since epoch.
235    // Many shape-compatible providers nest under the same key; try
236    // that first, then fall back to any top-level `expiresAt` /
237    // `expires_at` an alternative provider might use.
238    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    // A Claude file that holds neither an access nor a refresh token is signed out, whatever else
258    // it says: a refresh that two CLIs raced for can leave exactly this (#6080). Without this it
259    // read as `Valid` (no expiry to parse), so nothing showed until the next spawn failed.
260    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            // Past expiry. If a refresh token is present, the next
275            // CLI call will likely refresh it cleanly → `expired`
276            // (transient, not user-actionable). Without a refresh
277            // token the user must re-OAuth → `needs_reauth`.
278            if has_refresh {
279                Some(OAuthProbeStatus::Expired)
280            } else {
281                Some(OAuthProbeStatus::NeedsReauth)
282            }
283        }
284        Some(_) => Some(OAuthProbeStatus::Valid),
285        None => {
286            // Shape doesn't expose an expiry we can parse. Treat the
287            // file's existence as `Valid` rather than guess — false
288            // `needs_reauth` would force the user to reconnect a
289            // working session. codex falls here today.
290            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    // ── PR D — OAuth expiry probe + status semantics ───────────────────
306
307    /// Helper: write a Claude-shape `.credentials.json` into a temp dir
308    /// and return the dir path. `expires_ms` controls validity; `with_refresh`
309    /// toggles the refreshToken field so the resolver can distinguish
310    /// `Expired` (refresh present) from `NeedsReauth` (no refresh).
311    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        // Probing a provider that isn't in the oauth-class set is a
353        // signal to the caller to leave `status` alone — None ≠
354        // NeedsReauth. Guards against silent mis-classification of
355        // api-key providers if a future caller accidentally feeds
356        // them through here.
357        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        // codex isn't covered by the macOS carve-out (its macOS
364        // credential-storage behavior hasn't been verified the way
365        // Claude Code's has) — a missing file is still a definitive
366        // needs_reauth signal for it, on every platform.
367        let r = probe_oauth_status("codex", "/definitely/does/not/exist-xyz-9q", 0);
368        assert_eq!(r, Some(OAuthProbeStatus::NeedsReauth));
369    }
370
371    /// The failure this guards: Codex's sign-in is `auth.json`, and probing
372    /// `.credentials.json` marked every working Codex account needs_reauth.
373    #[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        // Claude Code stores OAuth credentials in the macOS Keychain, not
406        // `<dir>/.credentials.json`, regardless of CLAUDE_CONFIG_DIR — a
407        // missing file here is the expected, permanent shape on macOS, not
408        // evidence of needs_reauth. See
409        // docs/retro/retro-macos-keychain-credential-isolation-gap-2026-08-17.md.
410        // Asserting `None` (not `NeedsReauth`) is what stops this probe
411        // from mislabeling every working macOS Claude account as needing
412        // reauth.
413        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        // On Linux/Windows, CLAUDE_CONFIG_DIR genuinely relocates
421        // `.credentials.json` — a missing file there is a real signal.
422        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        // The CLI renews both: the next look withholds the new pair, and the replaced ones stay withheld: the
444        // access token works until it expires, the refresh token is kept.
445        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        // A sign-out leaves what was held: an agent may still hold the refresh token.
453        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        // Its expiry is already past, so it is not held at all; the refresh token has no expiry.
465        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        // No refresh token in the file → the CLI can't auto-refresh
492        // and the user has to OAuth again. Maps to `needs_reauth`,
493        // NOT `expired` (per spec §4.4).
494        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    /// A refresh that two CLIs raced for can leave a file with no tokens in it (#6080). It has no
510    /// expiry to parse, which used to read as `Valid` and showed nothing until a spawn failed.
511    #[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    /// Only Claude's file is held to that: a refresh token alone (the access token lapsed away) is
522    /// still a sign-in the CLI can renew.
523    #[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}