agentmux_srv/server/account_episodes/
fresh.rs1use crate::backend::providers::resolve_provider_alias;
12use crate::backend::storage::identities::{IdentityAccount, SecretRef};
13use crate::identity::resolver::{probe_oauth_status, OAuthProbeStatus};
14use crate::server::AppState;
15
16const REREAD_GAP: std::time::Duration = std::time::Duration::from_millis(100);
17
18fn status_now(account: &IdentityAccount, now_ms: i64) -> String {
25 status_after(account, now_ms, || std::thread::sleep(REREAD_GAP))
26}
27
28fn status_after(account: &IdentityAccount, now_ms: i64, between_looks: impl FnOnce()) -> String {
30 let SecretRef::OAuthConfigDir { dir } = &account.secret_ref else { return account.status.clone() };
31 if !matches!(account.status.as_str(), "valid" | "ok" | "expired") {
32 return account.status.clone();
33 }
34 let provider = resolve_provider_alias(&account.provider);
35 let mut read = probe_oauth_status(provider, dir, now_ms);
36 if read == Some(OAuthProbeStatus::NeedsReauth) {
37 between_looks();
39 read = probe_oauth_status(provider, dir, now_ms);
40 }
41 match read {
42 Some(OAuthProbeStatus::NeedsReauth) => "needs_reauth".to_string(),
43 Some(OAuthProbeStatus::Valid) if account.status == "expired" => "valid".to_string(),
44 _ => account.status.clone(),
45 }
46}
47
48pub(super) fn refreshed(mut accounts: Vec<IdentityAccount>, now_ms: i64) -> Vec<IdentityAccount> {
50 for a in &mut accounts {
51 a.status = status_now(a, now_ms);
52 }
53 accounts
54}
55
56pub(super) fn identity_list(state: &AppState) -> Result<Vec<IdentityAccount>, String> {
58 let all = state.id_store.identity_list(None).map_err(|e| e.to_string())?;
59 Ok(refreshed(all, agentmux_common::time::now_ms()))
60}
61
62#[cfg(test)]
63mod tests {
64 use super::*;
65
66 const NOW: i64 = 5_000_000;
67
68 fn account(dir: &std::path::Path, status: &str) -> IdentityAccount {
69 IdentityAccount {
70 id: "fresh-1".into(),
71 name: "fresh-1".into(),
72 provider: "claude".into(),
73 kind: "oauth".into(),
74 display_name: String::new(),
75 secret_ref: SecretRef::OAuthConfigDir { dir: dir.to_str().unwrap().into() },
76 context: serde_json::json!({}),
77 status: status.into(),
78 created_at: 0,
79 updated_at: 0,
80 }
81 }
82
83 fn read(file: &str, status: &str) -> String {
84 let tmp = tempfile::tempdir().unwrap();
85 std::fs::write(tmp.path().join(".credentials.json"), file).unwrap();
86 status_now(&account(tmp.path(), status), NOW)
87 }
88
89 #[test]
90 fn a_lapsed_access_token_that_can_renew_is_left_as_stored() {
91 let lapsed = format!(r#"{{"claudeAiOauth":{{"accessToken":"a","refreshToken":"r","expiresAt":{}}}}}"#, NOW - 1);
92 assert_eq!(read(&lapsed, "valid"), "valid");
93 assert_eq!(read(&lapsed, "expired"), "expired");
94 }
95
96 #[test]
97 fn an_emptied_file_is_signed_out_whatever_the_store_says() {
98 assert_eq!(read(r#"{"claudeAiOauth":{}}"#, "valid"), "needs_reauth");
99 assert_eq!(read(r#"{"claudeAiOauth":{}}"#, "ok"), "needs_reauth");
100 }
101
102 #[test]
103 fn a_file_that_is_whole_again_on_the_second_look_is_not_signed_out() {
104 let tmp = tempfile::tempdir().unwrap();
105 let file = tmp.path().join(".credentials.json");
106 std::fs::write(&file, "{ half written").unwrap();
107 let whole = format!(r#"{{"claudeAiOauth":{{"accessToken":"a","refreshToken":"r","expiresAt":{}}}}}"#, NOW + 3_600_000);
108 assert_eq!(status_after(&account(tmp.path(), "valid"), NOW, || std::fs::write(&file, &whole).unwrap()), "valid");
111 let once = std::cell::Cell::new(0);
112 assert_eq!(status_after(&account(tmp.path(), "valid"), NOW, || once.set(once.get() + 1)), "valid", "a file that is whole stays valid");
113 assert_eq!(once.get(), 0, "and is not looked at twice");
114 }
115
116 #[test]
117 fn a_live_token_keeps_ok_and_turns_a_stored_expired_back_to_valid() {
118 let live = format!(r#"{{"claudeAiOauth":{{"accessToken":"a","refreshToken":"r","expiresAt":{}}}}}"#, NOW + 3_600_000);
119 assert_eq!(read(&live, "ok"), "ok");
120 assert_eq!(read(&live, "expired"), "valid");
121 }
122
123 #[test]
124 fn a_refusal_and_an_unchecked_account_stay_as_stored() {
125 let live = format!(r#"{{"claudeAiOauth":{{"accessToken":"a","refreshToken":"r","expiresAt":{}}}}}"#, NOW + 3_600_000);
126 for stored in ["invalid", "needs_reauth", "unknown"] {
127 assert_eq!(read(&live, stored), stored);
128 }
129 }
130
131 #[test]
132 fn an_account_with_no_config_dir_keeps_its_status() {
133 let mut a = account(std::path::Path::new("x"), "valid");
134 a.secret_ref = SecretRef::Keychain { service: "s".into(), account: "a".into() };
135 assert_eq!(status_now(&a, NOW), "valid");
136 }
137}