Skip to main content

artifactize_core/auth/
codex.rs

1//! Codex (ChatGPT) sign-in: artifactize's own OAuth tokens in `$STATE/auth/codex.json`,
2//! or a Codex auth file that artifactize only reads.
3//!
4//! The protocol follows Pi's `openai-codex` provider (pi-mono
5//! `packages/ai/src/auth/oauth/openai-codex.ts`): the Codex public OAuth client, PKCE
6//! with S256, the `localhost:1455` callback or a pasted redirect URL, the
7//! authorization-code and refresh-token grants, and the ChatGPT account ID from the
8//! access token's `https://api.openai.com/auth` claim. Revocation on logout follows the
9//! Codex CLI (`codex-rs/login/src/auth/revoke.rs`). Callers must never print or log a
10//! token.
11
12use std::{
13    path::{Path, PathBuf},
14    time::Duration,
15};
16
17use base64::{
18    Engine,
19    engine::general_purpose::{URL_SAFE, URL_SAFE_NO_PAD},
20};
21use reqwest::Url;
22use serde::{Deserialize, Serialize};
23use serde_json::json;
24mod auth_file;
25mod callback;
26mod interactive;
27use auth_file::{AuthFileError, FileToken, read_auth_file_at};
28#[cfg(test)]
29use interactive::*;
30pub use interactive::{Prompt, login, login_with};
31#[cfg(test)]
32use sha2::{Digest, Sha256};
33#[cfg(test)]
34use std::{collections::BTreeMap, ffi::OsStr};
35#[cfg(test)]
36use tokio::sync::oneshot;
37mod timestamp;
38use callback::Callback;
39pub use timestamp::Timestamp;
40
41use super::storage::{Location, MAX_CREDENTIAL_BYTES, Storage, Tokens};
42
43/// The Codex CLI's public OAuth client, which Pi's provider uses too.
44pub const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
45const AUTH_ROOT: &str = "https://auth.openai.com";
46/// A loopback test endpoint replacing the sign-in root, beside the backends' own.
47pub const AUTH_URL_VARIABLE: &str = "ARTIFACTIZE_CODEX_AUTH_URL";
48/// A Codex auth file (for example `~/.codex/auth.json`) to read instead of
49/// artifactize's own tokens. It is never written, copied or refreshed.
50pub const AUTH_FILE_VARIABLE: &str = "ARTIFACTIZE_CODEX_AUTH_FILE";
51/// The `originator` that sign-in and every Codex request name.
52pub const ORIGINATOR: &str = "artifactize";
53#[cfg(test)]
54const CLAIM: &str = "https://api.openai.com/auth";
55const CREDENTIALS: &str = "codex.json";
56const LOCK: &str = "codex";
57/// Refresh this many seconds before expiry, as the Codex CLI's refresh window does.
58const REFRESH_MARGIN: Duration = Duration::from_secs(300);
59/// Bound individual token-exchange HTTP calls independently of the interactive login wait.
60const AUTH_HTTP_TIMEOUT: Duration = Duration::from_secs(30);
61/// Best-effort logout should finish sooner than an ordinary token exchange.
62const REVOCATION_TIMEOUT: Duration = Duration::from_secs(10);
63/// OAuth error codes are diagnostics, not arbitrary provider text; keep them short.
64const MAX_OAUTH_ERROR_CHARS: usize = 64;
65const LOGIN_REQUIRED: &str =
66    "Codex is not signed in; run `artifactize login codex` or set ARTIFACTIZE_CODEX_AUTH_FILE.";
67
68#[derive(Deserialize, Serialize)]
69struct Credentials {
70    access_token: String,
71    refresh_token: String,
72    account_id: crate::types::CodexAccountId,
73    #[serde(with = "timestamp::seconds")]
74    expires_at: Timestamp,
75    #[serde(with = "timestamp::seconds")]
76    saved_at: Timestamp,
77}
78
79/// Why no token is available. A transient failure (the token endpoint unreachable or
80/// failing with 429 or 5xx) may succeed on a retry; any other means signing in again.
81#[derive(Debug)]
82pub struct TokenError {
83    pub transient: bool,
84    pub message: String,
85}
86
87impl From<String> for TokenError {
88    fn from(message: String) -> Self {
89        Self {
90            transient: false,
91            message,
92        }
93    }
94}
95
96impl From<&str> for TokenError {
97    fn from(message: &str) -> Self {
98        message.to_owned().into()
99    }
100}
101
102/// A bearer token and the ChatGPT account it belongs to. Never printed or logged.
103pub struct Token {
104    pub access_token: String,
105    pub account_id: crate::types::CodexAccountId,
106}
107
108pub(crate) fn now() -> Result<Timestamp, String> {
109    Timestamp::now()
110}
111
112/// The sign-in root: its loopback test endpoint, else `https://auth.openai.com`.
113pub fn auth_root() -> Result<Url, String> {
114    Ok(
115        crate::llm::variable_endpoint(AUTH_URL_VARIABLE)?.map_or_else(
116            || Url::parse(AUTH_ROOT).expect("built-in Codex auth URL"),
117            crate::llm::TestEndpoint::into_url,
118        ),
119    )
120}
121
122fn endpoint(root: &Url, route: &str) -> Result<Url, String> {
123    let mut url = root.clone();
124    url.path_segments_mut()
125        .map_err(|_| "Invalid Codex sign-in URL.")?
126        .pop_if_empty()
127        .push("oauth")
128        .push(route);
129    Ok(url)
130}
131
132/// The configured read-only auth file, if any.
133pub fn auth_file() -> Option<PathBuf> {
134    crate::platform::environment::var(AUTH_FILE_VARIABLE)
135        .filter(|value| !value.is_empty())
136        .map(PathBuf::from)
137}
138
139fn client() -> Result<reqwest::Client, String> {
140    reqwest::Client::builder()
141        .redirect(reqwest::redirect::Policy::none())
142        .retry(reqwest::retry::never())
143        .timeout(AUTH_HTTP_TIMEOUT)
144        .build()
145        .map_err(|_| "Cannot initialize the Codex sign-in HTTP client.".into())
146}
147
148/// The JSON claims of a JWT, read without verifying its signature, as Pi does: the
149/// token came over TLS from the token endpoint or from the user's own auth file.
150fn claims(token: &str) -> Option<JwtClaims> {
151    let mut parts = token.split('.');
152    let (_, payload, _, None) = (parts.next()?, parts.next()?, parts.next()?, parts.next()) else {
153        return None;
154    };
155    let bytes = URL_SAFE_NO_PAD
156        .decode(payload)
157        .or_else(|_| URL_SAFE.decode(payload))
158        .ok()?;
159    serde_json::from_slice(&bytes).ok()
160}
161
162impl JwtClaims {
163    fn account_id(self) -> Option<crate::types::CodexAccountId> {
164        self.auth.0?.0.chatgpt_account_id.0
165    }
166}
167
168#[derive(Default, Deserialize)]
169struct JwtClaims {
170    #[serde(default)]
171    exp: crate::json::Optional<Timestamp>,
172    #[serde(default, rename = "https://api.openai.com/auth")]
173    auth: crate::json::Optional<crate::json::Object<AccountClaim>>,
174}
175#[derive(Default, Deserialize)]
176struct AccountClaim {
177    #[serde(default)]
178    chatgpt_account_id: crate::json::Optional<crate::types::CodexAccountId>,
179}
180
181#[derive(Deserialize)]
182struct TokenResponse {
183    access_token: Option<String>,
184    refresh_token: Option<String>,
185    #[serde(
186        default,
187        deserialize_with = "timestamp::optional_duration::deserialize"
188    )]
189    expires_in: Option<Duration>,
190}
191
192fn credentials(tokens: TokenResponse, saved_at: Timestamp) -> Result<Credentials, String> {
193    let invalid = || "Invalid Codex token response; nothing was saved.".to_owned();
194    let access_token = tokens.access_token.filter(|token| !token.is_empty());
195    let refresh_token = tokens.refresh_token.filter(|token| !token.is_empty());
196    let (Some(access_token), Some(refresh_token), Some(expires_in)) = (
197        access_token,
198        refresh_token,
199        tokens.expires_in.filter(|duration| !duration.is_zero()),
200    ) else {
201        return Err(invalid());
202    };
203    let account_id = claims(&access_token)
204        .and_then(JwtClaims::account_id)
205        .ok_or("The Codex access token names no ChatGPT account; nothing was saved.")?;
206    Ok(Credentials {
207        access_token,
208        refresh_token,
209        account_id,
210        expires_at: saved_at.checked_add(expires_in).ok_or_else(invalid)?,
211        saved_at,
212    })
213}
214
215#[derive(Default, Deserialize)]
216struct OAuthError {
217    error: Option<OAuthErrorField>,
218    code: Option<OAuthCode>,
219}
220
221#[derive(Deserialize)]
222#[serde(untagged)]
223enum OAuthErrorField {
224    Text(String),
225    Object { code: Option<OAuthCode> },
226    Other(serde::de::IgnoredAny),
227}
228
229#[derive(Deserialize)]
230#[serde(untagged)]
231enum OAuthCode {
232    Text(String),
233    Other(serde::de::IgnoredAny),
234}
235
236impl OAuthCode {
237    fn text(&self) -> Option<&str> {
238        match self {
239            Self::Text(code) => Some(code),
240            Self::Other(_) => None,
241        }
242    }
243}
244
245impl OAuthError {
246    fn code(&self) -> Option<&str> {
247        let error = match &self.error {
248            Some(OAuthErrorField::Text(code)) => Some(code.as_str()),
249            Some(OAuthErrorField::Object { code }) => code.as_ref().and_then(OAuthCode::text),
250            _ => None,
251        };
252        error.or_else(|| self.code.as_ref().and_then(OAuthCode::text))
253    }
254}
255
256/// Refresh errors after which the refresh token can never work again.
257fn terminal(code: &str) -> bool {
258    matches!(
259        code,
260        "invalid_grant"
261            | "refresh_token_expired"
262            | "refresh_token_reused"
263            | "refresh_token_invalidated"
264    )
265}
266
267/// POST a form to the token endpoint. Error bodies are never echoed: they may carry
268/// codes or tokens. A terminal refresh error removes the stored tokens.
269async fn token_request(
270    root: &Url,
271    form: &[(&str, &str)],
272    refreshing: Option<&Storage>,
273) -> Result<TokenResponse, TokenError> {
274    let response = client()?
275        .post(endpoint(root, "token")?)
276        .form(form)
277        .send()
278        .await
279        .map_err(|_| TokenError {
280            transient: true,
281            message:
282                "Codex token request failed; check your connection. The stored sign-in was kept."
283                    .into(),
284        })?;
285    let status = response.status();
286    if !status.is_success() {
287        let body: OAuthError = response.json().await.unwrap_or_default();
288        let code = body.code().unwrap_or_default();
289        // Rate limiting and server failures pass; a client error does not.
290        let transient =
291            status == reqwest::StatusCode::TOO_MANY_REQUESTS || status.is_server_error();
292        let status = status.as_u16();
293        let message = match refreshing {
294            Some(storage) if terminal(code) => {
295                storage.remove(CREDENTIALS)?;
296                format!(
297                    "The Codex refresh token is no longer valid ({code}); run `artifactize login codex`."
298                )
299            }
300            Some(_) => {
301                format!("Codex token refresh failed (HTTP {status}); the stored sign-in was kept.")
302            }
303            None if code == "invalid_grant" => {
304                "The Codex authorization code was rejected (invalid_grant); run `artifactize login codex` again."
305                    .into()
306            }
307            None => format!("Codex sign-in failed (HTTP {status})."),
308        };
309        return Err(TokenError { transient, message });
310    }
311    response
312        .json()
313        .await
314        .map_err(|_| "Invalid Codex token response; nothing was saved.".into())
315}
316
317/// A usable token: from the read-only auth file when one is set, else artifactize's own,
318/// refreshed under a cross-process lock when it is about to expire.
319pub async fn access_token(state: Option<&Path>, repo: Option<&Path>) -> Result<Token, TokenError> {
320    if let Some(path) = auth_file() {
321        return Ok(read_auth_file_at(&path, now()?)?.token);
322    }
323    stored_token(&Storage::new(state, repo, Tokens::Codex)?, &auth_root()?).await
324}
325
326async fn stored_token(storage: &Storage, root: &Url) -> Result<Token, TokenError> {
327    stored_token_at(storage, root, now).await
328}
329
330async fn stored_token_at(
331    storage: &Storage,
332    root: &Url,
333    clock: impl Fn() -> Result<Timestamp, String>,
334) -> Result<Token, TokenError> {
335    let _lock = storage.lock(LOCK).await?;
336    let stored = storage
337        .read::<Credentials>(CREDENTIALS)?
338        .ok_or(LOGIN_REQUIRED)?;
339    if stored.expires_at > clock()?.saturating_add(REFRESH_MARGIN) {
340        return Ok(Token {
341            access_token: stored.access_token,
342            account_id: stored.account_id,
343        });
344    }
345    let tokens = token_request(
346        root,
347        &[
348            ("grant_type", "refresh_token"),
349            ("refresh_token", &stored.refresh_token),
350            ("client_id", CLIENT_ID),
351        ],
352        Some(storage),
353    )
354    .await?;
355    let refreshed = credentials(tokens, clock()?)?;
356    if refreshed.account_id != stored.account_id {
357        return Err(
358            "The refreshed Codex token is for another ChatGPT account; run `artifactize login codex`."
359                .into(),
360        );
361    }
362    storage.save(CREDENTIALS, &refreshed)?;
363    Ok(Token {
364        access_token: refreshed.access_token,
365        account_id: refreshed.account_id,
366    })
367}
368
369/// Known read-only import fields. Wrong-typed optional fields retain the old missing/null
370/// behavior; extra fields are ignored and no credential data is echoed in parse errors.
371/// A read-only file can carry a usable token without an expiry claim. An expired
372/// file reports no timestamp because the existing reader refuses it before returning a token.
373#[derive(Debug)]
374pub enum FileExpiry {
375    Usable { expires_at: Option<Timestamp> },
376    Expired,
377}
378
379/// Owned credentials always carry the expiry saved by the token exchange.
380#[derive(Debug)]
381pub enum StoredExpiry {
382    Usable { expires_at: Timestamp },
383    Expired { expires_at: Timestamp },
384}
385
386/// Offline sign-in states: only file states have a path, only stored states have
387/// a mandatory expiry, and a storage refusal can only accompany an absent sign-in.
388#[derive(Debug)]
389pub enum Status {
390    Absent,
391    Refused { reason: String },
392    File { path: PathBuf, expiry: FileExpiry },
393    Stored { expiry: StoredExpiry },
394}
395
396impl Serialize for Status {
397    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
398        use serde::ser::SerializeStruct;
399        // Keep the pre-enum JSON contract exactly at the serialization boundary.
400        let (source, file, expires_at, expired, refused) = match self {
401            Self::Absent => ("none", None, None, false, None),
402            Self::Refused { reason } => ("none", None, None, false, Some(reason)),
403            Self::File {
404                path,
405                expiry: FileExpiry::Usable { expires_at },
406            } => ("file", Some(path), *expires_at, false, None),
407            Self::File {
408                path,
409                expiry: FileExpiry::Expired,
410            } => ("file", Some(path), None, true, None),
411            Self::Stored {
412                expiry: StoredExpiry::Usable { expires_at },
413            } => ("stored", None, Some(*expires_at), false, None),
414            Self::Stored {
415                expiry: StoredExpiry::Expired { expires_at },
416            } => ("stored", None, Some(*expires_at), true, None),
417        };
418        let mut wire = serializer.serialize_struct(
419            "Status",
420            3 + usize::from(file.is_some()) + usize::from(refused.is_some()),
421        )?;
422        wire.serialize_field("source", source)?;
423        if let Some(file) = file {
424            wire.serialize_field("authFile", &crate::platform::path_text(file))?;
425        }
426        wire.serialize_field("expiresAt", &expires_at)?;
427        wire.serialize_field("expired", &expired)?;
428        if let Some(reason) = refused {
429            wire.serialize_field("refused", reason)?;
430        }
431        wire.end()
432    }
433}
434
435/// Inspect the sign-in offline: no lock, refresh, network or writes.
436pub fn status(state: Option<&Path>, repo: Option<&Path>) -> Result<Status, String> {
437    let now = now()?;
438    if let Some(path) = auth_file() {
439        // Reading fails on an expiring token; that is a state to report, not an error.
440        let expiry = match read_auth_file_at(&path, now) {
441            Ok(FileToken { expires_at, .. }) => FileExpiry::Usable { expires_at },
442            Err(AuthFileError::Expired(_)) => FileExpiry::Expired,
443            Err(error) => return Err(error.into()),
444        };
445        return Ok(Status::File { path, expiry });
446    }
447    let location = Location::find(state, repo)?;
448    if let Some(refusal) = location.refusal(Tokens::Codex) {
449        // Only a sign-in already stored there is at risk; without one this is advice.
450        return match crate::platform::entry_exists(&location.directory.join(CREDENTIALS)) {
451            Ok(false) => Ok(Status::Refused { reason: refusal }),
452            _ => Err(refusal),
453        };
454    }
455    let stored = Storage::inspect(state, repo, Tokens::Codex)?.read::<Credentials>(CREDENTIALS)?;
456    Ok(match stored {
457        None => Status::Absent,
458        Some(stored) => Status::Stored {
459            expiry: if stored.expires_at <= now {
460                StoredExpiry::Expired {
461                    expires_at: stored.expires_at,
462                }
463            } else {
464                StoredExpiry::Usable {
465                    expires_at: stored.expires_at,
466                }
467            },
468        },
469    })
470}
471
472/// Revoke and remove artifactize's own tokens; a read-only auth file is left alone.
473/// Returns whether the revocation was confirmed.
474pub async fn logout(state: Option<&Path>, repo: Option<&Path>) -> Result<bool, String> {
475    sign_out(&Storage::new(state, repo, Tokens::Codex)?, &auth_root()?).await
476}
477
478async fn sign_out(storage: &Storage, root: &Url) -> Result<bool, String> {
479    let _lock = storage.lock(LOCK).await?;
480    let Some(stored) = storage.read::<Credentials>(CREDENTIALS)? else {
481        return Ok(true);
482    };
483    let revoked = revoke(root, &stored.refresh_token).await;
484    storage.remove(CREDENTIALS)?;
485    Ok(revoked)
486}
487
488async fn revoke(root: &Url, refresh_token: &str) -> bool {
489    let Ok(client) = client() else {
490        return false;
491    };
492    let Ok(url) = endpoint(root, "revoke") else {
493        return false;
494    };
495    client
496        .post(url)
497        .timeout(REVOCATION_TIMEOUT)
498        .json(
499            &json!({"token":refresh_token,"token_type_hint":"refresh_token","client_id":CLIENT_ID}),
500        )
501        .send()
502        .await
503        .is_ok_and(|response| response.status().is_success())
504}
505
506#[cfg(test)]
507mod callback_tests;
508#[cfg(test)]
509mod redirect_tests;
510#[cfg(test)]
511mod tests;