artifactize-provider 0.29.0

Managed credentials, model discovery and direct HTTP turns for Artifactize.
Documentation
use std::{collections::BTreeMap, fs};

use rig_core::test_utils::MockHttpResponse;
use serde_json::{Value, json};

use super::*;
use crate::llm::tests::Server;

/// An unsigned JWT with the ChatGPT account claim, as the token endpoint issues them.
pub(crate) fn jwt(account: &str, exp: u64) -> String {
    let encode = |value: Value| URL_SAFE_NO_PAD.encode(value.to_string());
    let mut claims = json!({"exp":exp});
    claims[CLAIM] = json!({"chatgpt_account_id":account});
    format!(
        "{}.{}.signature",
        encode(json!({"alg":"RS256","typ":"JWT"})),
        encode(claims)
    )
}

fn storage(root: &Path) -> Storage {
    Storage::new(&Location::beside(&root.join("state")).unwrap()).unwrap()
}

/// A Codex CLI store as `codex login` writes it, with fields artifactize must keep.
fn store(path: &Path, access: &str, refresh: Option<&str>) {
    let mut tokens = json!({"id_token":"old-id","access_token":access,"account_id":"account-1"});
    if let Some(refresh) = refresh {
        tokens["refresh_token"] = refresh.into();
    }
    fs::write(
        path,
        json!({"OPENAI_API_KEY":null,"tokens":tokens,"last_refresh":"2026-10-01T00:00:00Z","extra":{"kept":true}})
            .to_string(),
    )
    .unwrap();
}

fn read(path: &Path) -> Value {
    serde_json::from_slice(&fs::read(path).unwrap()).unwrap()
}

fn root(server: &Server) -> Url {
    server.base.parse().unwrap()
}

fn form(body: &Value) -> BTreeMap<String, String> {
    url::form_urlencoded::parse(body.as_str().unwrap().as_bytes())
        .into_owned()
        .collect()
}

const NOW: u64 = 10_000;

fn clock() -> Result<Timestamp, String> {
    Ok(Timestamp::from_seconds(NOW))
}

#[tokio::test]
async fn a_usable_token_is_used_as_the_cli_saved_it() {
    let temp = tempfile::tempdir().unwrap();
    let path = temp.path().join("auth.json");
    let access = jwt("account-1", NOW + 3600);
    store(&path, &access, Some("refresh-1"));
    let before = fs::read(&path).unwrap();
    Server::run(vec![], async |server| {
        let token = current_token_at(&storage(temp.path()), &path, &root(server), clock)
            .await
            .unwrap();
        assert_eq!(token.access_token, access);
        assert_eq!(token.account_id, "account-1");
        assert!(server.requests().is_empty());
    })
    .await;
    assert_eq!(fs::read(&path).unwrap(), before, "nothing is written");
}

#[tokio::test]
async fn an_expiring_token_refreshes_once_and_is_written_back_to_the_cli_store() {
    let temp = tempfile::tempdir().unwrap();
    let path = temp.path().join("auth.json");
    store(&path, &jwt("account-1", NOW + 60), Some("refresh-1"));
    let fresh = jwt("account-1", NOW + 3600);
    let response = MockHttpResponse::success(
        json!({"access_token":fresh,"refresh_token":"refresh-2","id_token":"new-id"}).to_string(),
    );
    Server::run(vec![response], async |server| {
        let root = root(server);
        let storage = storage(temp.path());
        let refresh = || current_token_at(&storage, &path, &root, clock);
        let (first, second) = tokio::join!(refresh(), refresh());
        for token in [first.unwrap(), second.unwrap()] {
            assert_eq!(token.access_token, fresh);
        }
        let requests = server.requests();
        assert_eq!(requests.len(), 1, "the lock lets one process refresh");
        assert_eq!(
            form(&requests[0].body),
            BTreeMap::from([
                ("grant_type".into(), "refresh_token".into()),
                ("refresh_token".into(), "refresh-1".into()),
                ("client_id".into(), CLIENT_ID.into()),
            ])
        );
    })
    .await;
    let saved = read(&path);
    assert_eq!(saved["tokens"]["access_token"], fresh.as_str());
    assert_eq!(saved["tokens"]["refresh_token"], "refresh-2");
    assert_eq!(saved["tokens"]["id_token"], "new-id");
    assert_eq!(saved["tokens"]["account_id"], "account-1");
    assert_eq!(saved["extra"], json!({"kept":true}));
    assert!(saved["OPENAI_API_KEY"].is_null());
    assert_ne!(saved["last_refresh"], "2026-10-01T00:00:00Z");
}

#[tokio::test]
async fn a_refused_refresh_asks_for_codex_login_and_leaves_the_store_alone() {
    let temp = tempfile::tempdir().unwrap();
    let path = temp.path().join("auth.json");
    store(&path, &jwt("account-1", NOW - 1), Some("refresh-1"));
    let before = fs::read(&path).unwrap();
    let refused = MockHttpResponse::error(
        rig_core::http_client::StatusCode::BAD_REQUEST,
        json!({"error":"invalid_grant"}).to_string(),
    );
    Server::run(vec![refused], async |server| {
        let error = current_token_at(&storage(temp.path()), &path, &root(server), clock)
            .await
            .err()
            .unwrap();
        assert_eq!(error.message, LOGIN_EXPIRED);
        assert!(!error.transient);
    })
    .await;
    assert_eq!(fs::read(&path).unwrap(), before);
}

#[tokio::test]
async fn no_store_or_an_api_key_alone_is_not_a_sign_in() {
    let temp = tempfile::tempdir().unwrap();
    let path = temp.path().join("auth.json");
    let missing = current_token_at(
        &storage(temp.path()),
        &path,
        &"http://127.0.0.1:9/".parse().unwrap(),
        clock,
    )
    .await
    .err()
    .unwrap();
    assert_eq!(missing.message, LOGIN_REQUIRED);
    fs::write(&path, json!({"OPENAI_API_KEY":"sk-key"}).to_string()).unwrap();
    let key_only = current_token_at(
        &storage(temp.path()),
        &path,
        &"http://127.0.0.1:9/".parse().unwrap(),
        clock,
    )
    .await
    .err()
    .unwrap();
    assert_eq!(key_only.message, LOGIN_REQUIRED);
}

#[test]
fn status_reads_the_store_and_its_expiry_offline() {
    let temp = tempfile::tempdir().unwrap();
    let path = temp.path().join("auth.json");
    let at = Timestamp::from_seconds(NOW);
    assert!(matches!(
        read_status_at(path.clone(), at).unwrap(),
        Status::Absent
    ));
    store(&path, &jwt("account-1", NOW + 3600), Some("refresh-1"));
    assert!(matches!(
        read_status_at(path.clone(), at).unwrap(),
        Status::File {
            expiry: FileExpiry::Usable {
                expires_at: Some(_)
            },
            ..
        }
    ));
    // An expired access token still signs in while a refresh token can renew it.
    store(&path, &jwt("account-1", NOW - 1), Some("refresh-1"));
    assert!(matches!(
        read_status_at(path.clone(), at).unwrap(),
        Status::File {
            expiry: FileExpiry::Usable { .. },
            ..
        }
    ));
    store(&path, &jwt("account-1", NOW - 1), None);
    let expired = read_status_at(path, at).unwrap();
    assert!(matches!(
        expired,
        Status::File {
            expiry: FileExpiry::Expired,
            ..
        }
    ));
    assert_eq!(
        serde_json::to_value(&expired).unwrap()["expired"],
        json!(true)
    );
}

#[test]
fn the_store_tokens_are_managed_secrets() {
    let temp = tempfile::tempdir().unwrap();
    let path = temp.path().join("auth.json");
    let access = jwt("account-1", NOW + 3600);
    store(&path, &access, Some("refresh-secret-value"));
    let values = auth_file::secret_values(&path).unwrap();
    assert!(values.contains(&access));
    assert!(values.contains(&"refresh-secret-value".to_owned()));
    // The ID token and an API key saved by `codex login --with-api-key` are credentials too.
    let mut saved: serde_json::Value =
        serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
    saved["tokens"]["id_token"] = json!("id-token-secret-value");
    saved["OPENAI_API_KEY"] = json!("api-key-secret-value");
    std::fs::write(&path, saved.to_string()).unwrap();
    let values = auth_file::secret_values(&path).unwrap();
    assert!(values.contains(&"id-token-secret-value".to_owned()));
    assert!(values.contains(&"api-key-secret-value".to_owned()));
}