Skip to main content

microclaw_engine/
codex_auth.rs

1use base64::Engine;
2use serde::Deserialize;
3use std::path::{Path, PathBuf};
4
5use microclaw_core::error::MicroClawError;
6
7pub const OPENAI_CODEX_PROVIDER: &str = "openai-codex";
8pub const QWEN_PORTAL_PROVIDER: &str = "qwen-portal";
9
10#[derive(Debug, Deserialize)]
11struct CodexAuthFile {
12    tokens: Option<CodexAuthTokens>,
13    #[serde(rename = "OPENAI_API_KEY")]
14    openai_api_key: Option<String>,
15}
16
17#[derive(Debug, Deserialize)]
18struct CodexAuthTokens {
19    access_token: Option<String>,
20    #[serde(rename = "refresh_token")]
21    _refresh_token: Option<String>,
22    account_id: Option<String>,
23}
24
25#[derive(Debug, Deserialize)]
26struct QwenOauthCredsFile {
27    access_token: Option<String>,
28}
29
30#[derive(Debug, Clone)]
31pub struct CodexAuthResolved {
32    pub bearer_token: String,
33    pub account_id: Option<String>,
34}
35
36pub fn provider_allows_empty_api_key(provider: &str) -> bool {
37    provider.eq_ignore_ascii_case("ollama")
38        || provider.eq_ignore_ascii_case(OPENAI_CODEX_PROVIDER)
39        || provider.eq_ignore_ascii_case(QWEN_PORTAL_PROVIDER)
40}
41
42pub fn is_openai_codex_provider(provider: &str) -> bool {
43    provider.eq_ignore_ascii_case(OPENAI_CODEX_PROVIDER)
44}
45
46pub fn is_qwen_portal_provider(provider: &str) -> bool {
47    provider.eq_ignore_ascii_case(QWEN_PORTAL_PROVIDER)
48}
49
50pub fn default_codex_auth_path() -> PathBuf {
51    let base = std::env::var("CODEX_HOME")
52        .ok()
53        .filter(|v| !v.trim().is_empty())
54        .as_deref()
55        .map(expand_tilde)
56        .unwrap_or_else(|| expand_tilde("~/.codex"));
57    Path::new(&base).join("auth.json")
58}
59
60pub fn default_codex_config_path() -> PathBuf {
61    let base = std::env::var("CODEX_HOME")
62        .ok()
63        .filter(|v| !v.trim().is_empty())
64        .as_deref()
65        .map(expand_tilde)
66        .unwrap_or_else(|| expand_tilde("~/.codex"));
67    Path::new(&base).join("config.toml")
68}
69
70pub fn default_qwen_oauth_creds_path() -> PathBuf {
71    let base = std::env::var("QWEN_HOME")
72        .ok()
73        .filter(|v| !v.trim().is_empty())
74        .as_deref()
75        .map(expand_tilde)
76        .unwrap_or_else(|| expand_tilde("~/.qwen"));
77    Path::new(&base).join("oauth_creds.json")
78}
79
80pub fn codex_auth_file_has_access_token() -> Result<bool, MicroClawError> {
81    if let Ok(token) = std::env::var("OPENAI_CODEX_ACCESS_TOKEN") {
82        if !token.trim().is_empty() {
83            return Ok(true);
84        }
85    }
86
87    let path = default_codex_auth_path();
88    if !path.exists() {
89        return Ok(false);
90    }
91    let content = std::fs::read_to_string(&path).map_err(|e| {
92        MicroClawError::Config(format!(
93            "Failed to read Codex auth file {}: {e}",
94            path.display()
95        ))
96    })?;
97    let parsed: CodexAuthFile = serde_json::from_str(&content).map_err(|e| {
98        MicroClawError::Config(format!(
99            "Failed to parse Codex auth file {}: {e}",
100            path.display()
101        ))
102    })?;
103    let has_access_token = parsed
104        .tokens
105        .as_ref()
106        .and_then(|tokens| tokens.access_token.as_ref())
107        .map(|token| !token.trim().is_empty())
108        .unwrap_or(false);
109    let has_openai_api_key = parsed
110        .openai_api_key
111        .as_ref()
112        .map(|key| !key.trim().is_empty())
113        .unwrap_or(false);
114    Ok(has_access_token || has_openai_api_key)
115}
116
117pub fn resolve_openai_codex_auth(
118    _fallback_api_key: &str,
119) -> Result<CodexAuthResolved, MicroClawError> {
120    if let Ok(token) = std::env::var("OPENAI_CODEX_ACCESS_TOKEN") {
121        let trimmed = token.trim();
122        if !trimmed.is_empty() {
123            return Ok(CodexAuthResolved {
124                bearer_token: trimmed.to_string(),
125                account_id: None,
126            });
127        }
128    }
129
130    let auth_path = default_codex_auth_path();
131    if auth_path.exists() {
132        let content = std::fs::read_to_string(&auth_path).map_err(|e| {
133            MicroClawError::Config(format!(
134                "Failed to read Codex auth file {}: {e}",
135                auth_path.display()
136            ))
137        })?;
138        let parsed: CodexAuthFile = serde_json::from_str(&content).map_err(|e| {
139            MicroClawError::Config(format!(
140                "Failed to parse Codex auth file {}: {e}",
141                auth_path.display()
142            ))
143        })?;
144        if let Some(token) = parsed
145            .tokens
146            .as_ref()
147            .and_then(|tokens| tokens.access_token.as_ref())
148            .map(|token| token.trim())
149            .filter(|token| !token.is_empty())
150        {
151            return Ok(CodexAuthResolved {
152                bearer_token: token.to_string(),
153                account_id: parsed
154                    .tokens
155                    .as_ref()
156                    .and_then(|tokens| tokens.account_id.clone())
157                    .map(|id| id.trim().to_string())
158                    .filter(|id| !id.is_empty()),
159            });
160        }
161
162        if let Some(api_key) = parsed
163            .openai_api_key
164            .as_deref()
165            .map(str::trim)
166            .filter(|key| !key.is_empty())
167        {
168            return Ok(CodexAuthResolved {
169                bearer_token: api_key.to_string(),
170                account_id: None,
171            });
172        }
173    }
174
175    Err(MicroClawError::Config(format!(
176        "OpenAI Codex provider requires ~/.codex/auth.json (access token or OPENAI_API_KEY), or OPENAI_CODEX_ACCESS_TOKEN. Run `codex login` or update Codex config files (expected auth file: {}).",
177        auth_path.display()
178    )))
179}
180
181pub fn qwen_oauth_file_has_access_token() -> Result<bool, MicroClawError> {
182    if let Ok(token) = std::env::var("QWEN_PORTAL_ACCESS_TOKEN") {
183        if !token.trim().is_empty() {
184            return Ok(true);
185        }
186    }
187    if let Ok(token) = std::env::var("QWEN_CODE_ACCESS_TOKEN") {
188        if !token.trim().is_empty() {
189            return Ok(true);
190        }
191    }
192    let path = default_qwen_oauth_creds_path();
193    if !path.exists() {
194        return Ok(false);
195    }
196    let content = std::fs::read_to_string(&path).map_err(|e| {
197        MicroClawError::Config(format!(
198            "Failed to read Qwen oauth creds file {}: {e}",
199            path.display()
200        ))
201    })?;
202    let parsed: QwenOauthCredsFile = serde_json::from_str(&content).map_err(|e| {
203        MicroClawError::Config(format!(
204            "Failed to parse Qwen oauth creds file {}: {e}",
205            path.display()
206        ))
207    })?;
208    Ok(parsed
209        .access_token
210        .as_ref()
211        .map(|v| !v.trim().is_empty())
212        .unwrap_or(false))
213}
214
215pub fn resolve_qwen_portal_auth(
216    fallback_api_key: &str,
217) -> Result<CodexAuthResolved, MicroClawError> {
218    if let Ok(token) = std::env::var("QWEN_PORTAL_ACCESS_TOKEN") {
219        let trimmed = token.trim();
220        if !trimmed.is_empty() {
221            return Ok(CodexAuthResolved {
222                bearer_token: trimmed.to_string(),
223                account_id: None,
224            });
225        }
226    }
227    if let Ok(token) = std::env::var("QWEN_CODE_ACCESS_TOKEN") {
228        let trimmed = token.trim();
229        if !trimmed.is_empty() {
230            return Ok(CodexAuthResolved {
231                bearer_token: trimmed.to_string(),
232                account_id: None,
233            });
234        }
235    }
236    let path = default_qwen_oauth_creds_path();
237    if path.exists() {
238        let content = std::fs::read_to_string(&path).map_err(|e| {
239            MicroClawError::Config(format!(
240                "Failed to read Qwen oauth creds file {}: {e}",
241                path.display()
242            ))
243        })?;
244        let parsed: QwenOauthCredsFile = serde_json::from_str(&content).map_err(|e| {
245            MicroClawError::Config(format!(
246                "Failed to parse Qwen oauth creds file {}: {e}",
247                path.display()
248            ))
249        })?;
250        if let Some(token) = parsed
251            .access_token
252            .as_deref()
253            .map(str::trim)
254            .filter(|v| !v.is_empty())
255        {
256            return Ok(CodexAuthResolved {
257                bearer_token: token.to_string(),
258                account_id: None,
259            });
260        }
261    }
262    let fallback = fallback_api_key.trim();
263    if !fallback.is_empty() {
264        return Ok(CodexAuthResolved {
265            bearer_token: fallback.to_string(),
266            account_id: None,
267        });
268    }
269    Err(MicroClawError::Config(
270        "qwen-portal requires ~/.qwen/oauth_creds.json (access_token), or QWEN_PORTAL_ACCESS_TOKEN, or api_key.".into(),
271    ))
272}
273
274pub fn codex_config_default_openai_base_url() -> Option<String> {
275    let path = default_codex_config_path();
276    let content = std::fs::read_to_string(path).ok()?;
277    parse_codex_config_default_openai_base_url(&content)
278}
279
280fn parse_codex_config_default_openai_base_url(content: &str) -> Option<String> {
281    let mut model_provider: Option<String> = None;
282
283    for raw in content.lines() {
284        let line = raw.split('#').next().unwrap_or("").trim();
285        if line.is_empty() {
286            continue;
287        }
288        if line.starts_with("model_provider") {
289            model_provider = parse_toml_string_assignment(line, "model_provider");
290            if model_provider.is_some() {
291                break;
292            }
293        }
294    }
295
296    let provider = model_provider?;
297    let target = provider.trim();
298    if target.is_empty() {
299        return None;
300    }
301
302    let mut current_provider: Option<String> = None;
303    for raw in content.lines() {
304        let line = raw.split('#').next().unwrap_or("").trim();
305        if line.is_empty() {
306            continue;
307        }
308        if line.starts_with('[') && line.ends_with(']') {
309            let section = &line[1..line.len() - 1];
310            current_provider = section
311                .strip_prefix("model_providers.")
312                .map(|v| v.trim().trim_matches('"').to_string())
313                .filter(|v| !v.is_empty());
314            continue;
315        }
316
317        if current_provider.as_deref() == Some(target) {
318            if let Some(base_url) = parse_toml_string_assignment(line, "base_url") {
319                let normalized = base_url.trim().trim_end_matches('/').to_string();
320                if !normalized.is_empty() {
321                    return Some(normalized);
322                }
323            }
324        }
325    }
326
327    None
328}
329
330fn parse_toml_string_assignment(line: &str, key: &str) -> Option<String> {
331    let (lhs, rhs) = line.split_once('=')?;
332    if lhs.trim() != key {
333        return None;
334    }
335    let value = rhs.trim();
336    if !(value.starts_with('"') && value.ends_with('"') && value.len() >= 2) {
337        return None;
338    }
339    Some(value[1..value.len() - 1].to_string())
340}
341
342fn expand_tilde(input: &str) -> String {
343    if let Some(rest) = input.strip_prefix("~/") {
344        if let Ok(home) = std::env::var("HOME") {
345            return format!("{home}/{rest}");
346        }
347    }
348    if input == "~" {
349        if let Ok(home) = std::env::var("HOME") {
350            return home;
351        }
352    }
353    input.to_string()
354}
355
356#[derive(Debug, Deserialize)]
357struct CodexRefreshResponse {
358    access_token: String,
359    refresh_token: Option<String>,
360    id_token: Option<String>,
361}
362
363/// OpenAI's OAuth token endpoint, used by `codex login`.
364pub(crate) const CODEX_TOKEN_URL: &str = "https://auth.openai.com/oauth/token";
365/// The OAuth client id of the Codex CLI.
366const CODEX_CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
367/// Refresh the access token this long before it expires, so a request never
368/// leaves with a token that runs out on the way.
369const CODEX_REFRESH_MARGIN_SECS: i64 = 300;
370
371/// The OAuth tokens in a Codex auth file, if it has both.
372fn codex_oauth_tokens(parsed: &serde_json::Value) -> Option<(String, String)> {
373    let tokens = parsed.get("tokens")?.as_object()?;
374    let field = |name: &str| {
375        tokens
376            .get(name)
377            .and_then(|v| v.as_str())
378            .map(str::trim)
379            .filter(|v| !v.is_empty())
380            .map(str::to_string)
381    };
382    Some((field("access_token")?, field("refresh_token")?))
383}
384
385fn codex_refresh_body(refresh_token: &str) -> serde_json::Value {
386    serde_json::json!({
387        "grant_type": "refresh_token",
388        "refresh_token": refresh_token,
389        "client_id": CODEX_CLIENT_ID,
390    })
391}
392
393/// Write a refresh response into the parsed auth file. Returns false when the
394/// response carries no access token.
395fn apply_codex_refresh(parsed: &mut serde_json::Value, resp: CodexRefreshResponse) -> bool {
396    if resp.access_token.trim().is_empty() {
397        return false;
398    }
399    let Some(tokens) = parsed.get_mut("tokens").and_then(|t| t.as_object_mut()) else {
400        return false;
401    };
402    tokens.insert(
403        "access_token".to_string(),
404        serde_json::Value::String(resp.access_token),
405    );
406    for (name, value) in [
407        ("refresh_token", resp.refresh_token),
408        ("id_token", resp.id_token),
409    ] {
410        if let Some(value) = value.filter(|v| !v.trim().is_empty()) {
411            tokens.insert(name.to_string(), serde_json::Value::String(value));
412        }
413    }
414    parsed["last_refresh"] = serde_json::Value::String(chrono::Utc::now().to_rfc3339());
415    true
416}
417
418fn read_codex_auth_value(path: &Path) -> Result<serde_json::Value, MicroClawError> {
419    let content = std::fs::read_to_string(path).map_err(|e| {
420        MicroClawError::Config(format!(
421            "Failed to read Codex auth file {}: {e}",
422            path.display()
423        ))
424    })?;
425    serde_json::from_str(&content).map_err(|e| {
426        MicroClawError::Config(format!(
427            "Failed to parse Codex auth file {}: {e}",
428            path.display()
429        ))
430    })
431}
432
433/// `std::fs::write` keeps the existing file's mode (Codex creates it 0600).
434fn write_codex_auth_value(path: &Path, parsed: &serde_json::Value) -> Result<(), MicroClawError> {
435    let text = serde_json::to_string_pretty(parsed).map_err(|e| {
436        MicroClawError::Config(format!("Failed to serialize refreshed Codex auth: {e}"))
437    })?;
438    std::fs::write(path, text)?;
439    Ok(())
440}
441
442/// Refreshes an expired Codex access token in `~/.codex/auth.json`.
443///
444/// Blocking: it uses `reqwest::blocking`, so never call it from async code
445/// (the client panics when dropped inside a Tokio runtime). Providers use
446/// [`openai_codex_auth_for_request`], which refreshes before every request.
447pub fn refresh_openai_codex_auth_if_needed() -> Result<(), MicroClawError> {
448    let auth_path = default_codex_auth_path();
449    if !auth_path.exists() {
450        return Ok(());
451    }
452    let mut parsed = read_codex_auth_value(&auth_path)?;
453    let Some((access, refresh)) = codex_oauth_tokens(&parsed) else {
454        return Ok(());
455    };
456    if !jwt_expires_within(&access, 0) {
457        return Ok(());
458    }
459
460    let client = reqwest::blocking::Client::builder()
461        .timeout(std::time::Duration::from_secs(10))
462        .build()?;
463    let resp = client
464        .post(CODEX_TOKEN_URL)
465        .header("content-type", "application/json")
466        .body(codex_refresh_body(&refresh).to_string())
467        .send()?;
468    if !resp.status().is_success() {
469        return Ok(());
470    }
471    let parsed_resp: CodexRefreshResponse = resp.json().map_err(|e| {
472        MicroClawError::Config(format!(
473            "Failed to parse OpenAI Codex refresh response: {e}"
474        ))
475    })?;
476    if apply_codex_refresh(&mut parsed, parsed_resp) {
477        write_codex_auth_value(&auth_path, &parsed)?;
478    }
479    Ok(())
480}
481
482/// One refresh at a time: OpenAI rotates refresh tokens, so two concurrent
483/// refreshes with the same token would make the second one fail.
484fn codex_refresh_lock() -> &'static tokio::sync::Mutex<()> {
485    static LOCK: std::sync::OnceLock<tokio::sync::Mutex<()>> = std::sync::OnceLock::new();
486    LOCK.get_or_init(|| tokio::sync::Mutex::new(()))
487}
488
489/// Refreshes the OAuth access token in the Codex auth file at `path` when it
490/// expires within [`CODEX_REFRESH_MARGIN_SECS`], or when the server rejected
491/// it (`rejected` is the token that was sent). If the file already holds a
492/// different token than the rejected one, someone else refreshed it and
493/// nothing is done. Returns whether the file was refreshed.
494pub(crate) async fn refresh_codex_auth_file(
495    http: &reqwest::Client,
496    token_url: &str,
497    path: &Path,
498    rejected: Option<&str>,
499) -> Result<bool, MicroClawError> {
500    let _guard = codex_refresh_lock().lock().await;
501    if !path.exists() {
502        return Ok(false);
503    }
504    let mut parsed = read_codex_auth_value(path)?;
505    let Some((access, refresh)) = codex_oauth_tokens(&parsed) else {
506        return Ok(false);
507    };
508    let needed = match rejected.map(str::trim) {
509        Some(rejected) => rejected == access,
510        None => jwt_expires_within(&access, CODEX_REFRESH_MARGIN_SECS),
511    };
512    if !needed {
513        return Ok(false);
514    }
515
516    let resp = http
517        .post(token_url)
518        .header("content-type", "application/json")
519        .timeout(std::time::Duration::from_secs(15))
520        .body(codex_refresh_body(&refresh).to_string())
521        .send()
522        .await?;
523    let status = resp.status();
524    if !status.is_success() {
525        let text = resp.text().await.unwrap_or_default();
526        return Err(MicroClawError::Config(format!(
527            "OpenAI Codex token refresh failed (HTTP {status}): {}; run `codex login` again",
528            text.chars().take(300).collect::<String>()
529        )));
530    }
531    let parsed_resp: CodexRefreshResponse = resp.json().await.map_err(|e| {
532        MicroClawError::Config(format!(
533            "Failed to parse OpenAI Codex refresh response: {e}"
534        ))
535    })?;
536    if !apply_codex_refresh(&mut parsed, parsed_resp) {
537        return Ok(false);
538    }
539    write_codex_auth_value(path, &parsed)?;
540    Ok(true)
541}
542
543/// The Codex credentials for one request. Reads the auth file every time, so
544/// a token refreshed by the Codex CLI is picked up too, and refreshes the
545/// OAuth token first when it is about to expire or `rejected` (the token the
546/// server just turned down) is still the current one. Refresh errors are
547/// logged, not returned: the current token is still worth a try.
548/// `OPENAI_CODEX_ACCESS_TOKEN` is used as is and never refreshed.
549pub async fn openai_codex_auth_for_request(
550    http: &reqwest::Client,
551    rejected: Option<&str>,
552) -> Result<CodexAuthResolved, MicroClawError> {
553    let env_token = std::env::var("OPENAI_CODEX_ACCESS_TOKEN")
554        .map(|t| !t.trim().is_empty())
555        .unwrap_or(false);
556    if !env_token {
557        let path = default_codex_auth_path();
558        match refresh_codex_auth_file(http, &codex_token_url(), &path, rejected).await {
559            Ok(true) => tracing::info!("Refreshed the OpenAI Codex access token"),
560            Ok(false) => {}
561            Err(e) => tracing::warn!("{e}"),
562        }
563    }
564    resolve_openai_codex_auth("")
565}
566
567#[cfg(not(test))]
568fn codex_token_url() -> String {
569    CODEX_TOKEN_URL.to_string()
570}
571
572#[cfg(test)]
573pub(crate) static TEST_CODEX_TOKEN_URL: std::sync::Mutex<Option<String>> =
574    std::sync::Mutex::new(None);
575
576#[cfg(test)]
577fn codex_token_url() -> String {
578    TEST_CODEX_TOKEN_URL
579        .lock()
580        .unwrap()
581        .clone()
582        .unwrap_or_else(|| "http://127.0.0.1:9/never-called".to_string())
583}
584
585/// Whether the JWT's `exp` claim is less than `secs` seconds away (or past).
586/// A token without a readable `exp` never counts as expiring.
587fn jwt_expires_within(token: &str, secs: i64) -> bool {
588    let parts: Vec<&str> = token.split('.').collect();
589    if parts.len() < 2 {
590        return false;
591    }
592    let payload = parts[1].trim_end_matches('=');
593    let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD
594        .decode(payload.as_bytes())
595        .ok()
596        .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok());
597    let exp = decoded
598        .as_ref()
599        .and_then(|v| v.get("exp"))
600        .and_then(|v| v.as_i64());
601    match exp {
602        Some(ts) => chrono::Utc::now().timestamp() + secs >= ts,
603        None => false,
604    }
605}
606
607#[cfg(test)]
608pub(crate) mod tests {
609    use super::*;
610
611    fn env_lock() -> std::sync::MutexGuard<'static, ()> {
612        crate::test_support::env_lock()
613    }
614
615    #[test]
616    fn test_provider_allows_empty_api_key() {
617        assert!(provider_allows_empty_api_key("ollama"));
618        assert!(provider_allows_empty_api_key("openai-codex"));
619        assert!(provider_allows_empty_api_key("qwen-portal"));
620        assert!(!provider_allows_empty_api_key("openai"));
621    }
622
623    #[test]
624    fn test_is_openai_codex_provider() {
625        assert!(is_openai_codex_provider("openai-codex"));
626        assert!(is_openai_codex_provider("OPENAI-CODEX"));
627        assert!(!is_openai_codex_provider("openai"));
628    }
629
630    #[test]
631    fn test_is_qwen_portal_provider() {
632        assert!(is_qwen_portal_provider("qwen-portal"));
633        assert!(is_qwen_portal_provider("QWEN-PORTAL"));
634        assert!(!is_qwen_portal_provider("qwen"));
635    }
636
637    #[test]
638    fn test_codex_auth_file_has_access_token_accepts_env_var() {
639        let _guard = env_lock();
640        let prev_access = std::env::var("OPENAI_CODEX_ACCESS_TOKEN").ok();
641        std::env::set_var("OPENAI_CODEX_ACCESS_TOKEN", "env-token");
642
643        let has = codex_auth_file_has_access_token().unwrap();
644
645        if let Some(prev) = prev_access {
646            std::env::set_var("OPENAI_CODEX_ACCESS_TOKEN", prev);
647        } else {
648            std::env::remove_var("OPENAI_CODEX_ACCESS_TOKEN");
649        }
650        assert!(has);
651    }
652
653    #[test]
654    fn test_codex_auth_file_has_access_token_accepts_openai_api_key_only() {
655        let _guard = env_lock();
656        let prev_codex_home = std::env::var("CODEX_HOME").ok();
657        let prev_access = std::env::var("OPENAI_CODEX_ACCESS_TOKEN").ok();
658        std::env::remove_var("OPENAI_CODEX_ACCESS_TOKEN");
659
660        let auth_dir = std::env::temp_dir().join(format!(
661            "microclaw-codex-auth-openai-key-only-{}",
662            std::time::SystemTime::now()
663                .duration_since(std::time::UNIX_EPOCH)
664                .unwrap_or_default()
665                .as_nanos()
666        ));
667        std::fs::create_dir_all(&auth_dir).unwrap();
668        std::fs::write(
669            auth_dir.join("auth.json"),
670            r#"{"OPENAI_API_KEY":"sk-user-stale"}"#,
671        )
672        .unwrap();
673        std::env::set_var("CODEX_HOME", &auth_dir);
674
675        let has = codex_auth_file_has_access_token().unwrap();
676
677        if let Some(prev) = prev_codex_home {
678            std::env::set_var("CODEX_HOME", prev);
679        } else {
680            std::env::remove_var("CODEX_HOME");
681        }
682        if let Some(prev) = prev_access {
683            std::env::set_var("OPENAI_CODEX_ACCESS_TOKEN", prev);
684        } else {
685            std::env::remove_var("OPENAI_CODEX_ACCESS_TOKEN");
686        }
687        let _ = std::fs::remove_file(auth_dir.join("auth.json"));
688        let _ = std::fs::remove_dir(auth_dir);
689
690        assert!(has);
691    }
692
693    #[test]
694    fn test_resolve_openai_codex_auth_accepts_openai_api_key_only() {
695        let _guard = env_lock();
696        let prev_codex_home = std::env::var("CODEX_HOME").ok();
697        let prev_access = std::env::var("OPENAI_CODEX_ACCESS_TOKEN").ok();
698        std::env::remove_var("OPENAI_CODEX_ACCESS_TOKEN");
699        std::env::remove_var("OPENAI_CODEX_ACCESS_TOKEN");
700
701        let auth_dir = std::env::temp_dir().join(format!(
702            "microclaw-codex-auth-openai-key-reject-{}",
703            std::time::SystemTime::now()
704                .duration_since(std::time::UNIX_EPOCH)
705                .unwrap_or_default()
706                .as_nanos()
707        ));
708        std::fs::create_dir_all(&auth_dir).unwrap();
709        std::fs::write(
710            auth_dir.join("auth.json"),
711            r#"{"OPENAI_API_KEY":"sk-user-stale"}"#,
712        )
713        .unwrap();
714        std::env::set_var("CODEX_HOME", &auth_dir);
715
716        let auth = resolve_openai_codex_auth("").unwrap();
717
718        if let Some(prev) = prev_codex_home {
719            std::env::set_var("CODEX_HOME", prev);
720        } else {
721            std::env::remove_var("CODEX_HOME");
722        }
723        if let Some(prev) = prev_access {
724            std::env::set_var("OPENAI_CODEX_ACCESS_TOKEN", prev);
725        } else {
726            std::env::remove_var("OPENAI_CODEX_ACCESS_TOKEN");
727        }
728        let _ = std::fs::remove_file(auth_dir.join("auth.json"));
729        let _ = std::fs::remove_dir(auth_dir);
730
731        assert_eq!(auth.bearer_token, "sk-user-stale");
732        assert!(auth.account_id.is_none());
733    }
734
735    #[test]
736    fn test_parse_codex_config_default_openai_base_url() {
737        let content = r#"
738model_provider = "tabcode"
739
740[model_providers.tabcode]
741name = "openai"
742base_url = "https://api.tabcode.cc/openai"
743wire_api = "responses"
744"#;
745        let base = parse_codex_config_default_openai_base_url(content).unwrap();
746        assert_eq!(base, "https://api.tabcode.cc/openai");
747    }
748
749    #[test]
750    fn test_qwen_oauth_file_has_access_token() {
751        let _guard = env_lock();
752        let prev_qwen_home = std::env::var("QWEN_HOME").ok();
753        let prev_qwen_access = std::env::var("QWEN_PORTAL_ACCESS_TOKEN").ok();
754        std::env::remove_var("QWEN_PORTAL_ACCESS_TOKEN");
755        let qwen_dir = std::env::temp_dir().join(format!(
756            "microclaw-qwen-oauth-creds-{}",
757            std::time::SystemTime::now()
758                .duration_since(std::time::UNIX_EPOCH)
759                .unwrap_or_default()
760                .as_nanos()
761        ));
762        std::fs::create_dir_all(&qwen_dir).unwrap();
763        std::fs::write(
764            qwen_dir.join("oauth_creds.json"),
765            r#"{"access_token":"qwen-oauth-token"}"#,
766        )
767        .unwrap();
768        std::env::set_var("QWEN_HOME", &qwen_dir);
769
770        let has = qwen_oauth_file_has_access_token().unwrap();
771
772        if let Some(prev) = prev_qwen_home {
773            std::env::set_var("QWEN_HOME", prev);
774        } else {
775            std::env::remove_var("QWEN_HOME");
776        }
777        if let Some(prev) = prev_qwen_access {
778            std::env::set_var("QWEN_PORTAL_ACCESS_TOKEN", prev);
779        } else {
780            std::env::remove_var("QWEN_PORTAL_ACCESS_TOKEN");
781        }
782        let _ = std::fs::remove_file(qwen_dir.join("oauth_creds.json"));
783        let _ = std::fs::remove_dir(qwen_dir);
784
785        assert!(has);
786    }
787
788    #[test]
789    fn test_resolve_qwen_portal_auth_reads_oauth_creds_file() {
790        let _guard = env_lock();
791        let prev_qwen_home = std::env::var("QWEN_HOME").ok();
792        let prev_qwen_access = std::env::var("QWEN_PORTAL_ACCESS_TOKEN").ok();
793        std::env::remove_var("QWEN_PORTAL_ACCESS_TOKEN");
794
795        let qwen_dir = std::env::temp_dir().join(format!(
796            "microclaw-qwen-oauth-resolve-{}",
797            std::time::SystemTime::now()
798                .duration_since(std::time::UNIX_EPOCH)
799                .unwrap_or_default()
800                .as_nanos()
801        ));
802        std::fs::create_dir_all(&qwen_dir).unwrap();
803        std::fs::write(
804            qwen_dir.join("oauth_creds.json"),
805            r#"{"access_token":"qwen-oauth-token"}"#,
806        )
807        .unwrap();
808        std::env::set_var("QWEN_HOME", &qwen_dir);
809
810        let auth = resolve_qwen_portal_auth("").unwrap();
811
812        if let Some(prev) = prev_qwen_home {
813            std::env::set_var("QWEN_HOME", prev);
814        } else {
815            std::env::remove_var("QWEN_HOME");
816        }
817        if let Some(prev) = prev_qwen_access {
818            std::env::set_var("QWEN_PORTAL_ACCESS_TOKEN", prev);
819        } else {
820            std::env::remove_var("QWEN_PORTAL_ACCESS_TOKEN");
821        }
822        let _ = std::fs::remove_file(qwen_dir.join("oauth_creds.json"));
823        let _ = std::fs::remove_dir(qwen_dir);
824
825        assert_eq!(auth.bearer_token, "qwen-oauth-token");
826        assert!(auth.account_id.is_none());
827    }
828
829    pub(crate) fn fake_jwt(exp: i64) -> String {
830        let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD
831            .encode(serde_json::json!({ "exp": exp }).to_string());
832        format!("eyJhbGciOiJub25lIn0.{payload}.sig")
833    }
834
835    /// Serves one canned HTTP response per connection, in order, and sends
836    /// back each request's text.
837    pub(crate) fn serve_responses(
838        responses: Vec<(u16, String)>,
839    ) -> (String, std::sync::mpsc::Receiver<String>) {
840        use std::io::{Read, Write};
841        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
842        let addr = listener.local_addr().unwrap();
843        let (tx, rx) = std::sync::mpsc::channel();
844        std::thread::spawn(move || {
845            for (status, body) in responses {
846                let Ok((mut stream, _)) = listener.accept() else {
847                    return;
848                };
849                stream
850                    .set_read_timeout(Some(std::time::Duration::from_secs(2)))
851                    .unwrap();
852                let mut req = Vec::new();
853                let mut buf = [0u8; 8192];
854                loop {
855                    let n = stream.read(&mut buf).unwrap_or(0);
856                    if n == 0 {
857                        break;
858                    }
859                    req.extend_from_slice(&buf[..n]);
860                    let text = String::from_utf8_lossy(&req);
861                    if let Some(head_end) = text.find("\r\n\r\n") {
862                        let len = text[..head_end]
863                            .lines()
864                            .find_map(|l| {
865                                let lower = l.to_ascii_lowercase();
866                                lower
867                                    .strip_prefix("content-length:")
868                                    .map(|v| v.trim().parse::<usize>().unwrap_or(0))
869                            })
870                            .unwrap_or(0);
871                        if req.len() >= head_end + 4 + len {
872                            break;
873                        }
874                    }
875                }
876                let _ = tx.send(String::from_utf8_lossy(&req).to_string());
877                let reason = if status == 200 { "OK" } else { "Error" };
878                let response = format!(
879                    "HTTP/1.1 {status} {reason}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
880                    body.len()
881                );
882                let _ = stream.write_all(response.as_bytes());
883                let _ = stream.flush();
884            }
885        });
886        (format!("http://{addr}"), rx)
887    }
888
889    fn write_auth(dir: &Path, access: &str) -> PathBuf {
890        let path = dir.join("auth.json");
891        std::fs::write(
892            &path,
893            serde_json::json!({
894                "tokens": {
895                    "access_token": access,
896                    "refresh_token": "refresh-1",
897                    "account_id": "acct-1",
898                },
899                "OPENAI_API_KEY": null,
900            })
901            .to_string(),
902        )
903        .unwrap();
904        path
905    }
906
907    fn read_tokens(path: &Path) -> serde_json::Value {
908        let v: serde_json::Value =
909            serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
910        v["tokens"].clone()
911    }
912
913    #[test]
914    fn test_jwt_expires_within() {
915        let now = chrono::Utc::now().timestamp();
916        assert!(jwt_expires_within(&fake_jwt(now - 10), 0));
917        assert!(jwt_expires_within(&fake_jwt(now + 60), 300));
918        assert!(!jwt_expires_within(&fake_jwt(now + 3600), 300));
919        assert!(!jwt_expires_within("not-a-jwt", 300));
920        // Padded payloads (as some encoders emit) still parse.
921        let padded = base64::engine::general_purpose::URL_SAFE
922            .encode(serde_json::json!({ "exp": now - 1 }).to_string());
923        assert!(jwt_expires_within(&format!("h.{padded}.s"), 0));
924    }
925
926    #[tokio::test]
927    async fn test_refresh_codex_auth_file_refreshes_expiring_token() {
928        let dir = tempfile::tempdir().unwrap();
929        let old = fake_jwt(chrono::Utc::now().timestamp() + 60);
930        let path = write_auth(dir.path(), &old);
931        let (url, requests) = serve_responses(vec![(
932            200,
933            r#"{"access_token":"new-access","refresh_token":"refresh-2","id_token":"id-2"}"#.into(),
934        )]);
935        let http = reqwest::Client::new();
936        let refreshed = refresh_codex_auth_file(&http, &format!("{url}/oauth/token"), &path, None)
937            .await
938            .unwrap();
939        assert!(refreshed);
940        let req = requests.recv().unwrap();
941        assert!(req.starts_with("POST /oauth/token"));
942        assert!(req.contains(r#""refresh_token":"refresh-1""#));
943        assert!(req.contains(CODEX_CLIENT_ID));
944        let tokens = read_tokens(&path);
945        assert_eq!(tokens["access_token"], "new-access");
946        assert_eq!(tokens["refresh_token"], "refresh-2");
947        assert_eq!(tokens["id_token"], "id-2");
948        assert_eq!(tokens["account_id"], "acct-1");
949    }
950
951    #[tokio::test]
952    async fn test_refresh_codex_auth_file_keeps_fresh_token() {
953        let dir = tempfile::tempdir().unwrap();
954        let fresh = fake_jwt(chrono::Utc::now().timestamp() + 3600);
955        let path = write_auth(dir.path(), &fresh);
956        let http = reqwest::Client::new();
957        let refreshed =
958            refresh_codex_auth_file(&http, "http://127.0.0.1:9/never-called", &path, None)
959                .await
960                .unwrap();
961        assert!(!refreshed);
962        assert_eq!(read_tokens(&path)["access_token"], fresh.as_str());
963    }
964
965    #[tokio::test]
966    async fn test_refresh_codex_auth_file_refreshes_rejected_token() {
967        let dir = tempfile::tempdir().unwrap();
968        let fresh = fake_jwt(chrono::Utc::now().timestamp() + 3600);
969        let path = write_auth(dir.path(), &fresh);
970        let (url, _requests) =
971            serve_responses(vec![(200, r#"{"access_token":"new-access"}"#.into())]);
972        let http = reqwest::Client::new();
973        let refreshed = refresh_codex_auth_file(&http, &url, &path, Some(&fresh))
974            .await
975            .unwrap();
976        assert!(refreshed);
977        let tokens = read_tokens(&path);
978        assert_eq!(tokens["access_token"], "new-access");
979        assert_eq!(tokens["refresh_token"], "refresh-1");
980    }
981
982    #[tokio::test]
983    async fn test_refresh_codex_auth_file_skips_when_already_replaced() {
984        let dir = tempfile::tempdir().unwrap();
985        let current = fake_jwt(chrono::Utc::now().timestamp() + 3600);
986        let path = write_auth(dir.path(), &current);
987        let http = reqwest::Client::new();
988        let refreshed = refresh_codex_auth_file(
989            &http,
990            "http://127.0.0.1:9/never-called",
991            &path,
992            Some("an-older-token"),
993        )
994        .await
995        .unwrap();
996        assert!(!refreshed);
997        assert_eq!(read_tokens(&path)["access_token"], current.as_str());
998    }
999
1000    #[tokio::test]
1001    async fn test_refresh_codex_auth_file_reports_failed_refresh() {
1002        let dir = tempfile::tempdir().unwrap();
1003        let old = fake_jwt(chrono::Utc::now().timestamp() - 10);
1004        let path = write_auth(dir.path(), &old);
1005        let (url, _requests) = serve_responses(vec![(400, r#"{"error":"invalid_grant"}"#.into())]);
1006        let http = reqwest::Client::new();
1007        let err = refresh_codex_auth_file(&http, &url, &path, None)
1008            .await
1009            .unwrap_err();
1010        assert!(err.to_string().contains("codex login"));
1011        assert_eq!(read_tokens(&path)["access_token"], old.as_str());
1012    }
1013}