artifactize-provider 0.30.0

Managed credentials, model discovery and direct HTTP turns for Artifactize.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! Codex (ChatGPT) sign-in: the Codex CLI's own, which `codex login` saved in that CLI's
//! store (`$CODEX_HOME/auth.json`, else `~/.codex/auth.json`). artifactize keeps no Codex
//! sign-in of its own.
//!
//! The access token is used as the Codex CLI uses it. When it is about to expire it is
//! refreshed with the Codex public OAuth client, as the CLI refreshes it, and the new tokens
//! are written back to the CLI's store, since a refresh token is used once: keeping the new
//! one elsewhere would sign the CLI out. The ChatGPT account ID comes from the store or from
//! the access token's `https://api.openai.com/auth` claim. Callers must never print or log a
//! token.

use std::{
    path::{Path, PathBuf},
    time::Duration,
};

use base64::{
    Engine,
    engine::general_purpose::{URL_SAFE, URL_SAFE_NO_PAD},
};
use reqwest::Url;
use serde::{Deserialize, Serialize};
mod auth_file;
pub(crate) use auth_file::import_stamp;
use auth_file::{FileToken, read_auth_file_at};
mod timestamp;
pub use timestamp::Timestamp;

use super::storage::{Location, MAX_CREDENTIAL_BYTES, Storage};

/// The Codex CLI's public OAuth client, which refreshes the CLI's tokens.
pub const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
const AUTH_ROOT: &str = "https://auth.openai.com";
/// A loopback test endpoint replacing the sign-in root, beside the backends' own.
pub const AUTH_URL_VARIABLE: &str = "ARTIFACTIZE_CODEX_AUTH_URL";
/// The Codex CLI's own variable naming its home, where `auth.json` lives.
pub const CODEX_HOME_VARIABLE: &str = "CODEX_HOME";
/// The `originator` that every Codex request names.
pub const ORIGINATOR: &str = "artifactize";
#[cfg(test)]
const CLAIM: &str = "https://api.openai.com/auth";
/// The lock that serializes artifactize's own refreshes of the CLI's store.
const LOCK: &str = "codex";
/// Refresh this many seconds before expiry, as the Codex CLI's refresh window does.
const REFRESH_MARGIN: Duration = Duration::from_secs(300);
/// Bound individual token-exchange HTTP calls.
const AUTH_HTTP_TIMEOUT: Duration = Duration::from_secs(30);
pub(crate) const LOGIN_REQUIRED: &str = "Codex is not signed in; run `codex login`.";
const LOGIN_EXPIRED: &str = "The Codex CLI's sign-in has expired; run `codex login` again.";

/// Why no token is available. A transient failure (the token endpoint unreachable or
/// failing with 429 or 5xx) may succeed on a retry; any other means signing in again.
#[derive(Debug)]
pub struct TokenError {
    pub transient: bool,
    pub message: String,
}

impl From<String> for TokenError {
    fn from(message: String) -> Self {
        Self {
            transient: false,
            message,
        }
    }
}

impl From<&str> for TokenError {
    fn from(message: &str) -> Self {
        message.to_owned().into()
    }
}

/// A bearer token and the ChatGPT account it belongs to. Never printed or logged.
pub(crate) struct Token {
    pub access_token: String,
    pub account_id: crate::names::CodexAccountId,
    pub refresh_token: Option<String>,
}

pub(crate) fn now() -> Result<Timestamp, String> {
    Timestamp::now()
}

/// The sign-in root: its loopback test endpoint, else `https://auth.openai.com`.
pub fn auth_root() -> Result<Url, String> {
    Ok(
        crate::llm::variable_endpoint(AUTH_URL_VARIABLE)?.map_or_else(
            || Url::parse(AUTH_ROOT).expect("built-in Codex auth URL"),
            crate::llm::TestEndpoint::into_url,
        ),
    )
}

fn endpoint(root: &Url, route: &str) -> Result<Url, String> {
    let mut url = root.clone();
    url.path_segments_mut()
        .map_err(|_| "Invalid Codex sign-in URL.")?
        .pop_if_empty()
        .push("oauth")
        .push(route);
    Ok(url)
}

/// The Codex CLI's store: `auth.json` in its home. `None` only when no home is known.
pub fn auth_file() -> Option<PathBuf> {
    crate::platform::codex_home().map(|home| home.join("auth.json"))
}

fn client() -> Result<reqwest::Client, String> {
    reqwest::Client::builder()
        .redirect(reqwest::redirect::Policy::none())
        .retry(reqwest::retry::never())
        .timeout(AUTH_HTTP_TIMEOUT)
        .build()
        .map_err(|_| "Cannot initialize the Codex sign-in HTTP client.".into())
}

/// The JSON claims of a JWT, read without verifying its signature: the token came over TLS
/// from the token endpoint or from the Codex CLI's own store.
fn claims(token: &str) -> Option<JwtClaims> {
    let mut parts = token.split('.');
    let (_, payload, _, None) = (parts.next()?, parts.next()?, parts.next()?, parts.next()) else {
        return None;
    };
    let bytes = URL_SAFE_NO_PAD
        .decode(payload)
        .or_else(|_| URL_SAFE.decode(payload))
        .ok()?;
    serde_json::from_slice(&bytes).ok()
}

impl JwtClaims {
    fn account_id(self) -> Option<crate::names::CodexAccountId> {
        self.auth.0?.0.chatgpt_account_id.0
    }
}

#[derive(Default, Deserialize)]
struct JwtClaims {
    #[serde(default)]
    exp: crate::json::Optional<Timestamp>,
    #[serde(default, rename = "https://api.openai.com/auth")]
    auth: crate::json::Optional<crate::json::Object<AccountClaim>>,
}
#[derive(Default, Deserialize)]
struct AccountClaim {
    #[serde(default)]
    chatgpt_account_id: crate::json::Optional<crate::names::CodexAccountId>,
}

#[derive(Deserialize)]
struct TokenResponse {
    access_token: Option<String>,
    refresh_token: Option<String>,
    id_token: Option<String>,
}

/// The tokens a refresh returned: a new access token, and a new refresh token unless the
/// endpoint kept the old one.
struct Refreshed {
    access_token: String,
    refresh_token: Option<String>,
    id_token: Option<String>,
}

#[derive(Default, Deserialize)]
struct OAuthError {
    error: Option<OAuthErrorField>,
    code: Option<OAuthCode>,
}

#[derive(Deserialize)]
#[serde(untagged)]
enum OAuthErrorField {
    Text(String),
    Object { code: Option<OAuthCode> },
    Other(serde::de::IgnoredAny),
}

#[derive(Deserialize)]
#[serde(untagged)]
enum OAuthCode {
    Text(String),
    Other(serde::de::IgnoredAny),
}

impl OAuthCode {
    fn text(&self) -> Option<&str> {
        match self {
            Self::Text(code) => Some(code),
            Self::Other(_) => None,
        }
    }
}

impl OAuthError {
    fn code(&self) -> Option<&str> {
        let error = match &self.error {
            Some(OAuthErrorField::Text(code)) => Some(code.as_str()),
            Some(OAuthErrorField::Object { code }) => code.as_ref().and_then(OAuthCode::text),
            _ => None,
        };
        error.or_else(|| self.code.as_ref().and_then(OAuthCode::text))
    }
}

/// Refresh errors after which the refresh token can never work again.
fn terminal(code: &str) -> bool {
    matches!(
        code,
        "invalid_grant"
            | "refresh_token_expired"
            | "refresh_token_reused"
            | "refresh_token_invalidated"
    )
}

fn rejected(status: reqwest::StatusCode, code: Option<&str>) -> TokenError {
    if code.is_some_and(terminal) {
        return LOGIN_EXPIRED.into();
    }
    TokenError {
        transient: status == reqwest::StatusCode::TOO_MANY_REQUESTS || status.is_server_error(),
        message: format!(
            "Codex token refresh failed (HTTP {}); the Codex CLI's sign-in was kept.",
            status.as_u16()
        ),
    }
}

/// Exchange a refresh token at the token endpoint. Neither error body nor error code is
/// diagnostic text.
async fn refresh(root: &Url, refresh_token: &str) -> Result<Refreshed, TokenError> {
    let response = client()?
        .post(endpoint(root, "token")?)
        .form(&[
            ("grant_type", "refresh_token"),
            ("refresh_token", refresh_token),
            ("client_id", CLIENT_ID),
        ])
        .send()
        .await
        .map_err(|_| TokenError {
            transient: true,
            message: "Codex token refresh failed; check your connection. The Codex CLI's sign-in was kept."
                .into(),
        })?;
    let status = response.status();
    if !status.is_success() {
        let body: OAuthError = response.json().await.unwrap_or_default();
        return Err(rejected(status, body.code()));
    }
    let invalid = || TokenError::from("Invalid Codex token response; nothing was saved.");
    let tokens: TokenResponse = response.json().await.map_err(|_| invalid())?;
    let nonempty = |token: Option<String>| token.filter(|token| !token.is_empty());
    Ok(Refreshed {
        access_token: nonempty(tokens.access_token).ok_or_else(invalid)?,
        refresh_token: nonempty(tokens.refresh_token),
        id_token: nonempty(tokens.id_token),
    })
}

/// A usable token from the Codex CLI's store, refreshed there when it is about to expire.
pub(crate) async fn access_token(location: Result<&Location, &str>) -> Result<Token, TokenError> {
    let path = auth_file().ok_or(LOGIN_REQUIRED)?;
    current_token_at(&Storage::new(location?)?, &path, &auth_root()?, now).await
}

fn usable(file: &FileToken, now: Timestamp) -> bool {
    file.expires_at
        .is_none_or(|expires_at| expires_at > now.saturating_add(REFRESH_MARGIN))
}

async fn current_token_at(
    storage: &Storage,
    path: &Path,
    root: &Url,
    clock: impl Fn() -> Result<Timestamp, String>,
) -> Result<Token, TokenError> {
    let read = || read_auth_file_at(path)?.ok_or_else(|| TokenError::from(LOGIN_REQUIRED));
    let file = read()?;
    if usable(&file, clock()?) {
        return Ok(file.token);
    }
    // Refresh once across artifactize's processes; one may have refreshed while we waited.
    let _lock = storage.lock(LOCK).await?;
    let file = read()?;
    if usable(&file, clock()?) {
        return Ok(file.token);
    }
    let old = file.token;
    let refresh_token = old.refresh_token.clone().ok_or(LOGIN_EXPIRED)?;
    crate::secret::history::publish(storage, [old.access_token.as_str(), &refresh_token])?;
    let refreshed = refresh(root, &refresh_token).await.map_err(|mut error| {
        error.message =
            crate::secret::Inventory::new([old.access_token.clone(), refresh_token.clone()])
                .scrub(&error.message);
        error
    })?;
    let account_id = claims(&refreshed.access_token)
        .and_then(JwtClaims::account_id)
        .unwrap_or_else(|| old.account_id.clone());
    if account_id != old.account_id {
        return Err(
            "The refreshed Codex token is for another ChatGPT account; run `codex login` again."
                .into(),
        );
    }
    let refresh_token = refreshed.refresh_token.clone().unwrap_or(refresh_token);
    crate::secret::history::publish(storage, [refreshed.access_token.as_str(), &refresh_token])?;
    auth_file::write_back(path, &refreshed, &refresh_token)?;
    Ok(Token {
        access_token: refreshed.access_token,
        refresh_token: Some(refresh_token),
        account_id,
    })
}

/// Whether the Codex CLI's store holds a token that can still be used: its access token, or
/// its refresh token once the access token has expired.
#[derive(Debug)]
pub enum FileExpiry {
    Usable { expires_at: Option<Timestamp> },
    Expired,
}

/// The Codex CLI's sign-in as its store holds it, read offline.
pub enum Status {
    Absent,
    File { path: PathBuf, expiry: FileExpiry },
}

impl std::fmt::Debug for Status {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Absent => formatter.write_str("Absent"),
            Self::File { path, expiry } => formatter
                .debug_struct("File")
                .field("path", &crate::platform::path_text(path))
                .field("expiry", expiry)
                .finish(),
        }
    }
}

impl Serialize for Status {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let (source, file, expires_at, expired) = match self {
            Self::Absent => ("none", None, None, false),
            Self::File {
                path,
                expiry: FileExpiry::Usable { expires_at },
            } => ("file", Some(path), *expires_at, false),
            Self::File {
                path,
                expiry: FileExpiry::Expired,
            } => ("file", Some(path), None, true),
        };
        let mut wire = serializer.serialize_struct("Status", 3 + usize::from(file.is_some()))?;
        wire.serialize_field("source", source)?;
        if let Some(file) = file {
            wire.serialize_field("authFile", &crate::platform::path_text(file))?;
        }
        wire.serialize_field("expiresAt", &expires_at)?;
        wire.serialize_field("expired", &expired)?;
        wire.end()
    }
}

/// Inspect the sign-in offline: no lock, refresh, network or writes.
pub fn status() -> Result<Status, String> {
    let managed = crate::secret::Inventory::new(secret_values()?);
    read_status()
        .map_err(|error| managed.scrub(&error))
        .map(|status| public_status(status, &managed))
}

fn public_status(mut status: Status, managed: &crate::secret::Inventory) -> Status {
    if let Status::File { path, expiry } = &mut status {
        if managed.contains(&crate::platform::path_text(path)) {
            // This is a presentation path, never the path used to read the store.
            *path = PathBuf::new();
        }
        if let FileExpiry::Usable { expires_at } = expiry {
            *expires_at = expires_at.filter(|time| !managed.contains(&time.seconds().to_string()));
        }
    }
    status
}

fn read_status() -> Result<Status, String> {
    match auth_file() {
        Some(path) => read_status_at(path, now()?),
        None => Ok(Status::Absent),
    }
}

fn read_status_at(path: PathBuf, now: Timestamp) -> Result<Status, String> {
    let Some(file) = read_auth_file_at(&path)? else {
        return Ok(Status::Absent);
    };
    let expired = file.expires_at.is_some_and(|expires_at| expires_at <= now)
        && file.token.refresh_token.is_none();
    Ok(Status::File {
        path,
        expiry: if expired {
            FileExpiry::Expired
        } else {
            FileExpiry::Usable {
                expires_at: file.expires_at,
            }
        },
    })
}

#[cfg(test)]
mod tests;

/// The token values the Codex CLI's store holds, read without refreshing or sending anything.
pub(crate) fn secret_values() -> Result<Vec<String>, String> {
    match auth_file() {
        Some(path) => Ok(auth_file::secret_values(&path)?),
        None => Ok(Vec::new()),
    }
}