Skip to main content

artifactize_provider/auth/
codex.rs

1//! Codex (ChatGPT) sign-in: the Codex CLI's own, which `codex login` saved in that CLI's
2//! store (`$CODEX_HOME/auth.json`, else `~/.codex/auth.json`). artifactize keeps no Codex
3//! sign-in of its own.
4//!
5//! The access token is used as the Codex CLI uses it. When it is about to expire it is
6//! refreshed with the Codex public OAuth client, as the CLI refreshes it, and the new tokens
7//! are written back to the CLI's store, since a refresh token is used once: keeping the new
8//! one elsewhere would sign the CLI out. The ChatGPT account ID comes from the store or from
9//! the access token's `https://api.openai.com/auth` claim. 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};
23mod auth_file;
24pub(crate) use auth_file::import_stamp;
25use auth_file::{FileToken, read_auth_file_at};
26mod timestamp;
27pub use timestamp::Timestamp;
28
29use super::storage::{Location, MAX_CREDENTIAL_BYTES, Storage};
30
31/// The Codex CLI's public OAuth client, which refreshes the CLI's tokens.
32pub const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
33const AUTH_ROOT: &str = "https://auth.openai.com";
34/// A loopback test endpoint replacing the sign-in root, beside the backends' own.
35pub const AUTH_URL_VARIABLE: &str = "ARTIFACTIZE_CODEX_AUTH_URL";
36/// The Codex CLI's own variable naming its home, where `auth.json` lives.
37pub const CODEX_HOME_VARIABLE: &str = "CODEX_HOME";
38/// The `originator` that every Codex request names.
39pub const ORIGINATOR: &str = "artifactize";
40#[cfg(test)]
41const CLAIM: &str = "https://api.openai.com/auth";
42/// The lock that serializes artifactize's own refreshes of the CLI's store.
43const LOCK: &str = "codex";
44/// Refresh this many seconds before expiry, as the Codex CLI's refresh window does.
45const REFRESH_MARGIN: Duration = Duration::from_secs(300);
46/// Bound individual token-exchange HTTP calls.
47const AUTH_HTTP_TIMEOUT: Duration = Duration::from_secs(30);
48pub(crate) const LOGIN_REQUIRED: &str = "Codex is not signed in; run `codex login`.";
49const LOGIN_EXPIRED: &str = "The Codex CLI's sign-in has expired; run `codex login` again.";
50
51/// Why no token is available. A transient failure (the token endpoint unreachable or
52/// failing with 429 or 5xx) may succeed on a retry; any other means signing in again.
53#[derive(Debug)]
54pub struct TokenError {
55    pub transient: bool,
56    pub message: String,
57}
58
59impl From<String> for TokenError {
60    fn from(message: String) -> Self {
61        Self {
62            transient: false,
63            message,
64        }
65    }
66}
67
68impl From<&str> for TokenError {
69    fn from(message: &str) -> Self {
70        message.to_owned().into()
71    }
72}
73
74/// A bearer token and the ChatGPT account it belongs to. Never printed or logged.
75pub(crate) struct Token {
76    pub access_token: String,
77    pub account_id: crate::names::CodexAccountId,
78    pub refresh_token: Option<String>,
79}
80
81pub(crate) fn now() -> Result<Timestamp, String> {
82    Timestamp::now()
83}
84
85/// The sign-in root: its loopback test endpoint, else `https://auth.openai.com`.
86pub fn auth_root() -> Result<Url, String> {
87    Ok(
88        crate::llm::variable_endpoint(AUTH_URL_VARIABLE)?.map_or_else(
89            || Url::parse(AUTH_ROOT).expect("built-in Codex auth URL"),
90            crate::llm::TestEndpoint::into_url,
91        ),
92    )
93}
94
95fn endpoint(root: &Url, route: &str) -> Result<Url, String> {
96    let mut url = root.clone();
97    url.path_segments_mut()
98        .map_err(|_| "Invalid Codex sign-in URL.")?
99        .pop_if_empty()
100        .push("oauth")
101        .push(route);
102    Ok(url)
103}
104
105/// The Codex CLI's store: `auth.json` in its home. `None` only when no home is known.
106pub fn auth_file() -> Option<PathBuf> {
107    crate::platform::codex_home().map(|home| home.join("auth.json"))
108}
109
110fn client() -> Result<reqwest::Client, String> {
111    reqwest::Client::builder()
112        .redirect(reqwest::redirect::Policy::none())
113        .retry(reqwest::retry::never())
114        .timeout(AUTH_HTTP_TIMEOUT)
115        .build()
116        .map_err(|_| "Cannot initialize the Codex sign-in HTTP client.".into())
117}
118
119/// The JSON claims of a JWT, read without verifying its signature: the token came over TLS
120/// from the token endpoint or from the Codex CLI's own store.
121fn claims(token: &str) -> Option<JwtClaims> {
122    let mut parts = token.split('.');
123    let (_, payload, _, None) = (parts.next()?, parts.next()?, parts.next()?, parts.next()) else {
124        return None;
125    };
126    let bytes = URL_SAFE_NO_PAD
127        .decode(payload)
128        .or_else(|_| URL_SAFE.decode(payload))
129        .ok()?;
130    serde_json::from_slice(&bytes).ok()
131}
132
133impl JwtClaims {
134    fn account_id(self) -> Option<crate::names::CodexAccountId> {
135        self.auth.0?.0.chatgpt_account_id.0
136    }
137}
138
139#[derive(Default, Deserialize)]
140struct JwtClaims {
141    #[serde(default)]
142    exp: crate::json::Optional<Timestamp>,
143    #[serde(default, rename = "https://api.openai.com/auth")]
144    auth: crate::json::Optional<crate::json::Object<AccountClaim>>,
145}
146#[derive(Default, Deserialize)]
147struct AccountClaim {
148    #[serde(default)]
149    chatgpt_account_id: crate::json::Optional<crate::names::CodexAccountId>,
150}
151
152#[derive(Deserialize)]
153struct TokenResponse {
154    access_token: Option<String>,
155    refresh_token: Option<String>,
156    id_token: Option<String>,
157}
158
159/// The tokens a refresh returned: a new access token, and a new refresh token unless the
160/// endpoint kept the old one.
161struct Refreshed {
162    access_token: String,
163    refresh_token: Option<String>,
164    id_token: Option<String>,
165}
166
167#[derive(Default, Deserialize)]
168struct OAuthError {
169    error: Option<OAuthErrorField>,
170    code: Option<OAuthCode>,
171}
172
173#[derive(Deserialize)]
174#[serde(untagged)]
175enum OAuthErrorField {
176    Text(String),
177    Object { code: Option<OAuthCode> },
178    Other(serde::de::IgnoredAny),
179}
180
181#[derive(Deserialize)]
182#[serde(untagged)]
183enum OAuthCode {
184    Text(String),
185    Other(serde::de::IgnoredAny),
186}
187
188impl OAuthCode {
189    fn text(&self) -> Option<&str> {
190        match self {
191            Self::Text(code) => Some(code),
192            Self::Other(_) => None,
193        }
194    }
195}
196
197impl OAuthError {
198    fn code(&self) -> Option<&str> {
199        let error = match &self.error {
200            Some(OAuthErrorField::Text(code)) => Some(code.as_str()),
201            Some(OAuthErrorField::Object { code }) => code.as_ref().and_then(OAuthCode::text),
202            _ => None,
203        };
204        error.or_else(|| self.code.as_ref().and_then(OAuthCode::text))
205    }
206}
207
208/// Refresh errors after which the refresh token can never work again.
209fn terminal(code: &str) -> bool {
210    matches!(
211        code,
212        "invalid_grant"
213            | "refresh_token_expired"
214            | "refresh_token_reused"
215            | "refresh_token_invalidated"
216    )
217}
218
219fn rejected(status: reqwest::StatusCode, code: Option<&str>) -> TokenError {
220    if code.is_some_and(terminal) {
221        return LOGIN_EXPIRED.into();
222    }
223    TokenError {
224        transient: status == reqwest::StatusCode::TOO_MANY_REQUESTS || status.is_server_error(),
225        message: format!(
226            "Codex token refresh failed (HTTP {}); the Codex CLI's sign-in was kept.",
227            status.as_u16()
228        ),
229    }
230}
231
232/// Exchange a refresh token at the token endpoint. Neither error body nor error code is
233/// diagnostic text.
234async fn refresh(root: &Url, refresh_token: &str) -> Result<Refreshed, TokenError> {
235    let response = client()?
236        .post(endpoint(root, "token")?)
237        .form(&[
238            ("grant_type", "refresh_token"),
239            ("refresh_token", refresh_token),
240            ("client_id", CLIENT_ID),
241        ])
242        .send()
243        .await
244        .map_err(|_| TokenError {
245            transient: true,
246            message: "Codex token refresh failed; check your connection. The Codex CLI's sign-in was kept."
247                .into(),
248        })?;
249    let status = response.status();
250    if !status.is_success() {
251        let body: OAuthError = response.json().await.unwrap_or_default();
252        return Err(rejected(status, body.code()));
253    }
254    let invalid = || TokenError::from("Invalid Codex token response; nothing was saved.");
255    let tokens: TokenResponse = response.json().await.map_err(|_| invalid())?;
256    let nonempty = |token: Option<String>| token.filter(|token| !token.is_empty());
257    Ok(Refreshed {
258        access_token: nonempty(tokens.access_token).ok_or_else(invalid)?,
259        refresh_token: nonempty(tokens.refresh_token),
260        id_token: nonempty(tokens.id_token),
261    })
262}
263
264/// A usable token from the Codex CLI's store, refreshed there when it is about to expire.
265pub(crate) async fn access_token(location: Result<&Location, &str>) -> Result<Token, TokenError> {
266    let path = auth_file().ok_or(LOGIN_REQUIRED)?;
267    current_token_at(&Storage::new(location?)?, &path, &auth_root()?, now).await
268}
269
270fn usable(file: &FileToken, now: Timestamp) -> bool {
271    file.expires_at
272        .is_none_or(|expires_at| expires_at > now.saturating_add(REFRESH_MARGIN))
273}
274
275async fn current_token_at(
276    storage: &Storage,
277    path: &Path,
278    root: &Url,
279    clock: impl Fn() -> Result<Timestamp, String>,
280) -> Result<Token, TokenError> {
281    let read = || read_auth_file_at(path)?.ok_or_else(|| TokenError::from(LOGIN_REQUIRED));
282    let file = read()?;
283    if usable(&file, clock()?) {
284        return Ok(file.token);
285    }
286    // Refresh once across artifactize's processes; one may have refreshed while we waited.
287    let _lock = storage.lock(LOCK).await?;
288    let file = read()?;
289    if usable(&file, clock()?) {
290        return Ok(file.token);
291    }
292    let old = file.token;
293    let refresh_token = old.refresh_token.clone().ok_or(LOGIN_EXPIRED)?;
294    let previous = [
295        Some(old.access_token.as_str()),
296        Some(&refresh_token),
297        file.id_token.as_deref(),
298    ];
299    crate::secret::history::publish(storage, previous.into_iter().flatten())?;
300    let refreshed = refresh(root, &refresh_token).await.map_err(|mut error| {
301        error.message =
302            crate::secret::Inventory::new(previous.into_iter().flatten().map(str::to_owned))
303                .scrub(&error.message);
304        error
305    })?;
306    let account_id = claims(&refreshed.access_token)
307        .and_then(JwtClaims::account_id)
308        .unwrap_or_else(|| old.account_id.clone());
309    if account_id != old.account_id {
310        return Err(
311            "The refreshed Codex token is for another ChatGPT account; run `codex login` again."
312                .into(),
313        );
314    }
315    let refresh_token = refreshed.refresh_token.clone().unwrap_or(refresh_token);
316    let next = [
317        Some(refreshed.access_token.as_str()),
318        Some(&refresh_token),
319        refreshed.id_token.as_deref(),
320    ];
321    crate::secret::history::publish(storage, next.into_iter().flatten())?;
322    auth_file::write_back(path, &refreshed, &refresh_token)?;
323    Ok(Token {
324        access_token: refreshed.access_token,
325        refresh_token: Some(refresh_token),
326        account_id,
327    })
328}
329
330/// Whether the Codex CLI's store holds a token that can still be used: its access token, or
331/// its refresh token once the access token has expired.
332#[derive(Debug)]
333pub enum FileExpiry {
334    Usable { expires_at: Option<Timestamp> },
335    Expired,
336}
337
338/// The Codex CLI's sign-in as its store holds it, read offline.
339pub enum Status {
340    Absent,
341    File { path: PathBuf, expiry: FileExpiry },
342}
343
344impl std::fmt::Debug for Status {
345    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
346        match self {
347            Self::Absent => formatter.write_str("Absent"),
348            Self::File { path, expiry } => formatter
349                .debug_struct("File")
350                .field("path", &crate::platform::path_text(path))
351                .field("expiry", expiry)
352                .finish(),
353        }
354    }
355}
356
357impl Serialize for Status {
358    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
359        use serde::ser::SerializeStruct;
360        let (source, file, expires_at, expired) = match self {
361            Self::Absent => ("none", None, None, false),
362            Self::File {
363                path,
364                expiry: FileExpiry::Usable { expires_at },
365            } => ("file", Some(path), *expires_at, false),
366            Self::File {
367                path,
368                expiry: FileExpiry::Expired,
369            } => ("file", Some(path), None, true),
370        };
371        let mut wire = serializer.serialize_struct("Status", 3 + usize::from(file.is_some()))?;
372        wire.serialize_field("source", source)?;
373        if let Some(file) = file {
374            wire.serialize_field("authFile", &crate::platform::path_text(file))?;
375        }
376        wire.serialize_field("expiresAt", &expires_at)?;
377        wire.serialize_field("expired", &expired)?;
378        wire.end()
379    }
380}
381
382/// Inspect the sign-in offline: no lock, refresh, network or writes.
383pub fn status() -> Result<Status, String> {
384    let managed = crate::secret::Inventory::new(secret_values()?);
385    read_status()
386        .map_err(|error| managed.scrub(&error))
387        .map(|status| public_status(status, &managed))
388}
389
390fn public_status(mut status: Status, managed: &crate::secret::Inventory) -> Status {
391    if let Status::File { path, expiry } = &mut status {
392        if managed.contains(&crate::platform::path_text(path)) {
393            // This is a presentation path, never the path used to read the store.
394            *path = PathBuf::new();
395        }
396        if let FileExpiry::Usable { expires_at } = expiry {
397            *expires_at = expires_at.filter(|time| !managed.contains(&time.seconds().to_string()));
398        }
399    }
400    status
401}
402
403fn read_status() -> Result<Status, String> {
404    match auth_file() {
405        Some(path) => read_status_at(path, now()?),
406        None => Ok(Status::Absent),
407    }
408}
409
410fn read_status_at(path: PathBuf, now: Timestamp) -> Result<Status, String> {
411    let Some(file) = read_auth_file_at(&path)? else {
412        return Ok(Status::Absent);
413    };
414    let expired = file.expires_at.is_some_and(|expires_at| expires_at <= now)
415        && file.token.refresh_token.is_none();
416    Ok(Status::File {
417        path,
418        expiry: if expired {
419            FileExpiry::Expired
420        } else {
421            FileExpiry::Usable {
422                expires_at: file.expires_at,
423            }
424        },
425    })
426}
427
428#[cfg(test)]
429mod tests;
430
431/// The token values the Codex CLI's store holds, read without refreshing or sending anything.
432pub(crate) fn secret_values() -> Result<Vec<String>, String> {
433    match auth_file() {
434        Some(path) => Ok(auth_file::secret_values(&path)?),
435        None => Ok(Vec::new()),
436    }
437}