Skip to main content

artifactize_provider/auth/
codex.rs

1//! Codex (ChatGPT) sign-in: artifactize's own OAuth tokens in provider-owned private storage,
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;
27pub(crate) use auth_file::import_stamp;
28use auth_file::{AuthFileError, FileToken, read_auth_file_at};
29#[cfg(test)]
30use interactive::*;
31pub use interactive::{CALLBACK_PATH, CALLBACK_PORT, CallbackPort, Prompt, login_with};
32#[cfg(test)]
33use sha2::{Digest, Sha256};
34#[cfg(test)]
35use std::{collections::BTreeMap, ffi::OsStr};
36#[cfg(test)]
37use tokio::sync::oneshot;
38mod timestamp;
39use callback::Callback;
40pub use timestamp::Timestamp;
41
42use super::storage::{Location, MAX_CREDENTIAL_BYTES, Storage};
43
44/// The Codex CLI's public OAuth client, which Pi's provider uses too.
45pub const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
46const AUTH_ROOT: &str = "https://auth.openai.com";
47/// A loopback test endpoint replacing the sign-in root, beside the backends' own.
48pub const AUTH_URL_VARIABLE: &str = "ARTIFACTIZE_CODEX_AUTH_URL";
49/// A Codex auth file (for example `~/.codex/auth.json`) to read instead of
50/// artifactize's own tokens. It is never written, copied or refreshed.
51pub const AUTH_FILE_VARIABLE: &str = "ARTIFACTIZE_CODEX_AUTH_FILE";
52/// The `originator` that sign-in and every Codex request name.
53pub const ORIGINATOR: &str = "artifactize";
54#[cfg(test)]
55const CLAIM: &str = "https://api.openai.com/auth";
56pub(crate) const CREDENTIALS: &str = "codex.json";
57const LOCK: &str = "codex";
58/// Refresh this many seconds before expiry, as the Codex CLI's refresh window does.
59const REFRESH_MARGIN: Duration = Duration::from_secs(300);
60/// Bound individual token-exchange HTTP calls independently of the interactive login wait.
61const AUTH_HTTP_TIMEOUT: Duration = Duration::from_secs(30);
62/// Best-effort logout should finish sooner than an ordinary token exchange.
63const REVOCATION_TIMEOUT: Duration = Duration::from_secs(10);
64const LOGIN_REQUIRED: &str =
65    "Codex is not signed in; run `artifactize login codex` or set ARTIFACTIZE_CODEX_AUTH_FILE.";
66
67#[derive(Deserialize, Serialize)]
68struct Credentials {
69    access_token: String,
70    refresh_token: String,
71    account_id: crate::names::CodexAccountId,
72    #[serde(with = "timestamp::seconds")]
73    expires_at: Timestamp,
74    #[serde(with = "timestamp::seconds")]
75    saved_at: Timestamp,
76}
77
78impl Credentials {
79    fn values(&self) -> [&str; 2] {
80        [&self.access_token, &self.refresh_token]
81    }
82
83    fn publish(&self, storage: &Storage) -> Result<(), String> {
84        crate::secret::history::publish(storage, self.values())
85    }
86}
87
88fn read_stored(storage: &Storage) -> Result<Option<Credentials>, String> {
89    storage.read(CREDENTIALS)
90}
91
92/// Why no token is available. A transient failure (the token endpoint unreachable or
93/// failing with 429 or 5xx) may succeed on a retry; any other means signing in again.
94#[derive(Debug)]
95pub struct TokenError {
96    pub transient: bool,
97    pub message: String,
98}
99
100impl From<String> for TokenError {
101    fn from(message: String) -> Self {
102        Self {
103            transient: false,
104            message,
105        }
106    }
107}
108
109impl From<&str> for TokenError {
110    fn from(message: &str) -> Self {
111        message.to_owned().into()
112    }
113}
114
115/// A bearer token and the ChatGPT account it belongs to. Never printed or logged.
116pub(crate) struct Token {
117    pub access_token: String,
118    pub account_id: crate::names::CodexAccountId,
119    pub refresh_token: Option<String>,
120}
121
122pub(crate) fn now() -> Result<Timestamp, String> {
123    Timestamp::now()
124}
125
126/// The sign-in root: its loopback test endpoint, else `https://auth.openai.com`.
127pub fn auth_root() -> Result<Url, String> {
128    Ok(
129        crate::llm::variable_endpoint(AUTH_URL_VARIABLE)?.map_or_else(
130            || Url::parse(AUTH_ROOT).expect("built-in Codex auth URL"),
131            crate::llm::TestEndpoint::into_url,
132        ),
133    )
134}
135
136fn endpoint(root: &Url, route: &str) -> Result<Url, String> {
137    let mut url = root.clone();
138    url.path_segments_mut()
139        .map_err(|_| "Invalid Codex sign-in URL.")?
140        .pop_if_empty()
141        .push("oauth")
142        .push(route);
143    Ok(url)
144}
145
146/// The configured read-only auth file, if any.
147pub fn auth_file() -> Option<PathBuf> {
148    crate::platform::var(AUTH_FILE_VARIABLE)
149        .filter(|value| !value.is_empty())
150        .map(crate::platform::env_path)
151}
152
153fn client() -> Result<reqwest::Client, String> {
154    reqwest::Client::builder()
155        .redirect(reqwest::redirect::Policy::none())
156        .retry(reqwest::retry::never())
157        .timeout(AUTH_HTTP_TIMEOUT)
158        .build()
159        .map_err(|_| "Cannot initialize the Codex sign-in HTTP client.".into())
160}
161
162/// The JSON claims of a JWT, read without verifying its signature, as Pi does: the
163/// token came over TLS from the token endpoint or from the user's own auth file.
164fn claims(token: &str) -> Option<JwtClaims> {
165    let mut parts = token.split('.');
166    let (_, payload, _, None) = (parts.next()?, parts.next()?, parts.next()?, parts.next()) else {
167        return None;
168    };
169    let bytes = URL_SAFE_NO_PAD
170        .decode(payload)
171        .or_else(|_| URL_SAFE.decode(payload))
172        .ok()?;
173    serde_json::from_slice(&bytes).ok()
174}
175
176impl JwtClaims {
177    fn account_id(self) -> Option<crate::names::CodexAccountId> {
178        self.auth.0?.0.chatgpt_account_id.0
179    }
180}
181
182#[derive(Default, Deserialize)]
183struct JwtClaims {
184    #[serde(default)]
185    exp: crate::json::Optional<Timestamp>,
186    #[serde(default, rename = "https://api.openai.com/auth")]
187    auth: crate::json::Optional<crate::json::Object<AccountClaim>>,
188}
189#[derive(Default, Deserialize)]
190struct AccountClaim {
191    #[serde(default)]
192    chatgpt_account_id: crate::json::Optional<crate::names::CodexAccountId>,
193}
194
195#[derive(Deserialize)]
196struct TokenResponse {
197    access_token: Option<String>,
198    refresh_token: Option<String>,
199    #[serde(
200        default,
201        deserialize_with = "timestamp::optional_duration::deserialize"
202    )]
203    expires_in: Option<Duration>,
204}
205
206fn credentials(tokens: TokenResponse, saved_at: Timestamp) -> Result<Credentials, String> {
207    let invalid = || "Invalid Codex token response; nothing was saved.".to_owned();
208    let access_token = tokens.access_token.filter(|token| !token.is_empty());
209    let refresh_token = tokens.refresh_token.filter(|token| !token.is_empty());
210    let (Some(access_token), Some(refresh_token), Some(expires_in)) = (
211        access_token,
212        refresh_token,
213        tokens.expires_in.filter(|duration| !duration.is_zero()),
214    ) else {
215        return Err(invalid());
216    };
217    let account_id = claims(&access_token)
218        .and_then(JwtClaims::account_id)
219        .ok_or("The Codex access token names no ChatGPT account; nothing was saved.")?;
220    Ok(Credentials {
221        access_token,
222        refresh_token,
223        account_id,
224        expires_at: saved_at.checked_add(expires_in).ok_or_else(invalid)?,
225        saved_at,
226    })
227}
228
229#[derive(Default, Deserialize)]
230struct OAuthError {
231    error: Option<OAuthErrorField>,
232    code: Option<OAuthCode>,
233}
234
235#[derive(Deserialize)]
236#[serde(untagged)]
237enum OAuthErrorField {
238    Text(String),
239    Object { code: Option<OAuthCode> },
240    Other(serde::de::IgnoredAny),
241}
242
243#[derive(Deserialize)]
244#[serde(untagged)]
245enum OAuthCode {
246    Text(String),
247    Other(serde::de::IgnoredAny),
248}
249
250impl OAuthCode {
251    fn text(&self) -> Option<&str> {
252        match self {
253            Self::Text(code) => Some(code),
254            Self::Other(_) => None,
255        }
256    }
257}
258
259impl OAuthError {
260    fn code(&self) -> Option<&str> {
261        let error = match &self.error {
262            Some(OAuthErrorField::Text(code)) => Some(code.as_str()),
263            Some(OAuthErrorField::Object { code }) => code.as_ref().and_then(OAuthCode::text),
264            _ => None,
265        };
266        error.or_else(|| self.code.as_ref().and_then(OAuthCode::text))
267    }
268}
269
270/// Refresh errors after which the refresh token can never work again.
271fn terminal(code: &str) -> bool {
272    matches!(
273        code,
274        "invalid_grant"
275            | "refresh_token_expired"
276            | "refresh_token_reused"
277            | "refresh_token_invalidated"
278    )
279}
280
281enum Exchange {
282    Authorization,
283    Refresh,
284}
285
286enum ExchangeError {
287    TerminalRefresh,
288    Unavailable(TokenError),
289}
290
291impl From<TokenError> for ExchangeError {
292    fn from(error: TokenError) -> Self {
293        Self::Unavailable(error)
294    }
295}
296
297impl ExchangeError {
298    fn diagnostic(self) -> TokenError {
299        match self {
300            Self::TerminalRefresh => {
301                "The Codex refresh token is no longer valid; run `artifactize login codex`.".into()
302            }
303            Self::Unavailable(error) => error,
304        }
305    }
306}
307
308fn rejected(exchange: Exchange, status: reqwest::StatusCode, code: Option<&str>) -> ExchangeError {
309    let number = status.as_u16();
310    let message = match exchange {
311        Exchange::Refresh if code.is_some_and(terminal) => return ExchangeError::TerminalRefresh,
312        Exchange::Refresh => {
313            format!("Codex token refresh failed (HTTP {number}); the stored sign-in was kept.")
314        }
315        Exchange::Authorization if code == Some("invalid_grant") => {
316            "The Codex authorization code was rejected; run `artifactize login codex` again.".into()
317        }
318        Exchange::Authorization => format!("Codex sign-in failed (HTTP {number})."),
319    };
320    ExchangeError::Unavailable(TokenError {
321        transient: status == reqwest::StatusCode::TOO_MANY_REQUESTS || status.is_server_error(),
322        message,
323    })
324}
325
326/// POST a form to the token endpoint. Neither error body nor error code is diagnostic text.
327async fn token_request(
328    root: &Url,
329    form: &[(&str, &str)],
330    exchange: Exchange,
331) -> Result<TokenResponse, ExchangeError> {
332    let response = client()
333        .map_err(TokenError::from)?
334        .post(endpoint(root, "token").map_err(TokenError::from)?)
335        .form(form)
336        .send()
337        .await
338        .map_err(|_| TokenError {
339            transient: true,
340            message:
341                "Codex token request failed; check your connection. The stored sign-in was kept."
342                    .into(),
343        })?;
344    let status = response.status();
345    if !status.is_success() {
346        let body: OAuthError = response.json().await.unwrap_or_default();
347        return Err(rejected(exchange, status, body.code()));
348    }
349    response
350        .json()
351        .await
352        .map_err(|_| TokenError::from("Invalid Codex token response; nothing was saved.").into())
353}
354
355/// A usable token: from the read-only auth file when one is set, else artifactize's own,
356/// refreshed under a cross-process lock when it is about to expire.
357pub(crate) async fn access_token(location: Result<&Location, &str>) -> Result<Token, TokenError> {
358    if let Some(path) = auth_file() {
359        return Ok(read_auth_file_at(&path, now()?)?.token);
360    }
361    stored_token(&Storage::new(location?)?, &auth_root()?).await
362}
363
364async fn stored_token(storage: &Storage, root: &Url) -> Result<Token, TokenError> {
365    stored_token_at(storage, root, now).await
366}
367
368async fn stored_token_at(
369    storage: &Storage,
370    root: &Url,
371    clock: impl Fn() -> Result<Timestamp, String>,
372) -> Result<Token, TokenError> {
373    let _lock = storage.lock(LOCK).await?;
374    let stored = read_stored(storage)?.ok_or(LOGIN_REQUIRED)?;
375    if stored.expires_at > clock()?.saturating_add(REFRESH_MARGIN) {
376        return Ok(Token {
377            access_token: stored.access_token,
378            refresh_token: Some(stored.refresh_token),
379            account_id: stored.account_id,
380        });
381    }
382    stored.publish(storage)?;
383    let tokens = token_request(
384        root,
385        &[
386            ("grant_type", "refresh_token"),
387            ("refresh_token", &stored.refresh_token),
388            ("client_id", CLIENT_ID),
389        ],
390        Exchange::Refresh,
391    )
392    .await;
393    let tokens = match tokens {
394        Ok(tokens) => tokens,
395        Err(error) => {
396            if matches!(error, ExchangeError::TerminalRefresh) {
397                storage.remove(CREDENTIALS)?;
398            }
399            let mut failure = error.diagnostic();
400            failure.message = crate::secret::Inventory::new(stored.values().map(str::to_owned))
401                .scrub(&failure.message);
402            return Err(failure);
403        }
404    };
405    let refreshed = credentials(tokens, clock()?)?;
406    if refreshed.account_id != stored.account_id {
407        return Err(
408            "The refreshed Codex token is for another ChatGPT account; run `artifactize login codex`."
409                .into(),
410        );
411    }
412    refreshed.publish(storage)?;
413    storage.save(CREDENTIALS, &refreshed)?;
414    Ok(Token {
415        access_token: refreshed.access_token,
416        refresh_token: Some(refreshed.refresh_token),
417        account_id: refreshed.account_id,
418    })
419}
420
421/// Known read-only import fields. Wrong-typed optional fields retain the old missing/null
422/// behavior; extra fields are ignored and no credential data is echoed in parse errors.
423/// A read-only file can carry a usable token without an expiry claim. An expired
424/// file reports no timestamp because the existing reader refuses it before returning a token.
425#[derive(Debug)]
426pub enum FileExpiry {
427    Usable { expires_at: Option<Timestamp> },
428    Expired,
429}
430
431/// Owned credentials always carry the expiry saved by the token exchange.
432#[derive(Debug)]
433pub enum StoredExpiry {
434    Usable { expires_at: Timestamp },
435    Expired { expires_at: Timestamp },
436}
437
438/// Offline sign-in states: only file states have a path, only stored states have
439/// a mandatory expiry, and a storage refusal can only accompany an absent sign-in.
440pub enum Status {
441    Absent,
442    Refused { reason: String },
443    File { path: PathBuf, expiry: FileExpiry },
444    Stored { expiry: StoredExpiry },
445}
446
447impl std::fmt::Debug for Status {
448    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
449        match self {
450            Self::Absent => formatter.write_str("Absent"),
451            Self::Refused { reason } => formatter
452                .debug_struct("Refused")
453                .field("reason", reason)
454                .finish(),
455            Self::File { path, expiry } => formatter
456                .debug_struct("File")
457                .field("path", &crate::platform::path_text(path))
458                .field("expiry", expiry)
459                .finish(),
460            Self::Stored { expiry } => formatter
461                .debug_struct("Stored")
462                .field("expiry", expiry)
463                .finish(),
464        }
465    }
466}
467
468impl Serialize for Status {
469    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
470        use serde::ser::SerializeStruct;
471        // Keep the pre-enum JSON contract exactly at the serialization boundary.
472        let (source, file, expires_at, expired, refused) = match self {
473            Self::Absent => ("none", None, None, false, None),
474            Self::Refused { reason } => ("none", None, None, false, Some(reason)),
475            Self::File {
476                path,
477                expiry: FileExpiry::Usable { expires_at },
478            } => ("file", Some(path), *expires_at, false, None),
479            Self::File {
480                path,
481                expiry: FileExpiry::Expired,
482            } => ("file", Some(path), None, true, None),
483            Self::Stored {
484                expiry: StoredExpiry::Usable { expires_at },
485            } => ("stored", None, Some(*expires_at), false, None),
486            Self::Stored {
487                expiry: StoredExpiry::Expired { expires_at },
488            } => ("stored", None, Some(*expires_at), true, None),
489        };
490        let mut wire = serializer.serialize_struct(
491            "Status",
492            3 + usize::from(file.is_some()) + usize::from(refused.is_some()),
493        )?;
494        wire.serialize_field("source", source)?;
495        if let Some(file) = file {
496            wire.serialize_field("authFile", &crate::platform::path_text(file))?;
497        }
498        wire.serialize_field("expiresAt", &expires_at)?;
499        wire.serialize_field("expired", &expired)?;
500        if let Some(reason) = refused {
501            wire.serialize_field("refused", reason)?;
502        }
503        wire.end()
504    }
505}
506
507/// Inspect the sign-in offline: no lock, refresh, network or writes.
508pub fn status(location: Result<&Location, &str>) -> Result<Status, String> {
509    let mut managed = crate::secret::Inventory::read(location.ok(), location.ok());
510    let status = read_status(location);
511    managed.merge(crate::secret::Inventory::read(location.ok(), location.ok()));
512    status
513        .map_err(|error| managed.scrub(&error))
514        .and_then(|status| public_status(status, &managed))
515}
516
517fn public_status(mut status: Status, managed: &crate::secret::Inventory) -> Result<Status, String> {
518    let expires_at = match &mut status {
519        Status::Absent => None,
520        Status::Refused { reason } => {
521            *reason = managed.scrub(reason);
522            None
523        }
524        Status::File { path, expiry } => {
525            let display = crate::platform::path_text(path);
526            if managed.contains(&display) {
527                // This is a presentation path, never the path used to read the import.
528                *path = PathBuf::new();
529            }
530            if let FileExpiry::Usable { expires_at } = expiry {
531                *expires_at =
532                    expires_at.filter(|time| !managed.contains(&time.seconds().to_string()));
533            }
534            None
535        }
536        Status::Stored { expiry } => match expiry {
537            StoredExpiry::Usable { expires_at } | StoredExpiry::Expired { expires_at } => {
538                Some(*expires_at)
539            }
540        },
541    };
542    if expires_at.is_some_and(|time| managed.contains(&time.seconds().to_string())) {
543        return Err(managed.scrub("Cannot show Codex sign-in expiry safely."));
544    }
545    Ok(status)
546}
547
548fn read_status(location: Result<&Location, &str>) -> Result<Status, String> {
549    let now = now()?;
550    if let Some(path) = auth_file() {
551        // Reading fails on an expiring token; that is a state to report, not an error.
552        let expiry = match read_auth_file_at(&path, now) {
553            Ok(FileToken { expires_at, .. }) => FileExpiry::Usable { expires_at },
554            Err(AuthFileError::Expired(_)) => FileExpiry::Expired,
555            Err(error) => return Err(error.into()),
556        };
557        return Ok(Status::File { path, expiry });
558    }
559    let location = location?;
560    if let Some(reason) = location.refusal(CREDENTIALS)? {
561        return Ok(Status::Refused { reason });
562    }
563    let stored = read_stored(&Storage::inspect(location)?)?;
564    Ok(match stored {
565        None => Status::Absent,
566        Some(stored) => Status::Stored {
567            expiry: if stored.expires_at <= now {
568                StoredExpiry::Expired {
569                    expires_at: stored.expires_at,
570                }
571            } else {
572                StoredExpiry::Usable {
573                    expires_at: stored.expires_at,
574                }
575            },
576        },
577    })
578}
579
580/// Revoke and remove artifactize's own tokens; a read-only auth file is left alone.
581/// Returns whether the revocation was confirmed.
582pub async fn logout(location: Result<&Location, &str>) -> Result<bool, String> {
583    sign_out(
584        &Storage::new(location.map_err(str::to_owned)?)?,
585        &auth_root()?,
586    )
587    .await
588}
589
590async fn sign_out(storage: &Storage, root: &Url) -> Result<bool, String> {
591    let _lock = storage.lock(LOCK).await?;
592    let Some(stored) = read_stored(storage)? else {
593        return Ok(true);
594    };
595    stored.publish(storage)?;
596    let revoked = revoke(root, &stored.refresh_token).await;
597    storage.remove(CREDENTIALS)?;
598    Ok(revoked)
599}
600
601async fn revoke(root: &Url, refresh_token: &str) -> bool {
602    let Ok(client) = client() else {
603        return false;
604    };
605    let Ok(url) = endpoint(root, "revoke") else {
606        return false;
607    };
608    client
609        .post(url)
610        .timeout(REVOCATION_TIMEOUT)
611        .json(
612            &json!({"token":refresh_token,"token_type_hint":"refresh_token","client_id":CLIENT_ID}),
613        )
614        .send()
615        .await
616        .is_ok_and(|response| response.status().is_success())
617}
618
619#[cfg(test)]
620mod tests;
621
622/// Inventory stored values without refreshing, revoking or sending anything.
623pub(crate) fn secret_values(location: Option<&Location>) -> Result<Vec<String>, String> {
624    // Inventory extraction is independent of timestamps, account identifiers and
625    // expiry rules needed to use the credentials for sign-in.
626    #[derive(Deserialize)]
627    struct StoredTokens {
628        #[serde(default)]
629        access_token: crate::json::Optional<String>,
630        #[serde(default)]
631        refresh_token: crate::json::Optional<String>,
632    }
633    let saved = location
634        .filter(|location| !location.is_refused())
635        .map(|location| Storage::inspect(location)?.read::<StoredTokens>(CREDENTIALS))
636        .transpose()?
637        .flatten();
638    let mut known = saved
639        .into_iter()
640        .flat_map(|tokens| [tokens.access_token.0, tokens.refresh_token.0])
641        .flatten()
642        .collect::<Vec<_>>();
643    if let Some(path) = auth_file() {
644        known.extend(auth_file::secret_values(&path)?);
645    }
646    Ok(known)
647}