artifactize-provider 0.30.0

Managed credentials, model discovery and direct HTTP turns for Artifactize.
Documentation
//! Reading the Codex CLI's store, and writing a refresh back into it.
use super::*;
use std::io::Read;

#[derive(Default)]
struct AuthFile {
    /// The key `codex login --with-api-key` saves in place of tokens.
    api_key: crate::json::Optional<String>,
    tokens: crate::json::Optional<crate::json::Object<AuthFileTokens>>,
}
#[derive(Default)]
struct AuthFileTokens {
    id_token: crate::json::Optional<String>,
    access_token: crate::json::Optional<String>,
    refresh_token: crate::json::Optional<String>,
    account_id: crate::json::Optional<String>,
}
impl<'de> Deserialize<'de> for AuthFile {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct AuthVisitor;
        impl<'de> serde::de::Visitor<'de> for AuthVisitor {
            type Value = AuthFile;
            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                formatter.write_str("an auth-file object")
            }
            fn visit_map<M: serde::de::MapAccess<'de>>(
                self,
                mut map: M,
            ) -> Result<Self::Value, M::Error> {
                let mut auth = AuthFile::default();
                while let Some(field) = map.next_key::<String>()? {
                    if field == "tokens" {
                        auth.tokens = map.next_value()?;
                    } else if field == "OPENAI_API_KEY" {
                        auth.api_key = map.next_value()?;
                    } else {
                        map.next_value::<crate::json::Ignored>()?;
                    }
                }
                Ok(auth)
            }
        }
        deserializer.deserialize_map(AuthVisitor)
    }
}
impl<'de> Deserialize<'de> for AuthFileTokens {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct TokensVisitor;
        impl<'de> serde::de::Visitor<'de> for TokensVisitor {
            type Value = AuthFileTokens;
            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                formatter.write_str("an auth-file token object")
            }
            fn visit_map<M: serde::de::MapAccess<'de>>(
                self,
                mut map: M,
            ) -> Result<Self::Value, M::Error> {
                let mut tokens = AuthFileTokens::default();
                while let Some(field) = map.next_key::<String>()? {
                    match field.as_str() {
                        "id_token" => tokens.id_token = map.next_value()?,
                        "access_token" => tokens.access_token = map.next_value()?,
                        "refresh_token" => tokens.refresh_token = map.next_value()?,
                        "account_id" => tokens.account_id = map.next_value()?,
                        _ => {
                            map.next_value::<crate::json::Ignored>()?;
                        }
                    }
                }
                Ok(tokens)
            }
        }
        deserializer.deserialize_map(TokensVisitor)
    }
}

/// Why the Codex CLI's store could not be read; the message explains why.
#[derive(Debug)]
pub(super) enum AuthFileError {
    Unreadable(String),
}

impl std::fmt::Display for AuthFileError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Unreadable(message) => write!(f, "{message}"),
        }
    }
}

impl From<AuthFileError> for String {
    fn from(error: AuthFileError) -> Self {
        error.to_string()
    }
}

impl From<AuthFileError> for TokenError {
    fn from(error: AuthFileError) -> Self {
        error.to_string().into()
    }
}

pub(super) struct FileToken {
    pub(super) token: Token,
    pub(super) expires_at: Option<Timestamp>,
}

#[derive(PartialEq, Eq)]
pub(crate) struct ImportStamp {
    file: artifactize_foundation::platform::private::FileIdentity,
    modified: std::time::SystemTime,
    content: sha2::digest::Output<sha2::Sha256>,
}

/// Unlike provider-owned rotations, external writes have no redaction history.
/// Compare snapshots across the tool batch, including file replacement and edits.
pub(crate) fn import_stamp() -> std::io::Result<Option<ImportStamp>> {
    match auth_file() {
        Some(path) => import_stamp_at(&path),
        None => Ok(None),
    }
}

fn import_stamp_at(path: &Path) -> std::io::Result<Option<ImportStamp>> {
    use sha2::{Digest, Sha256};
    if crate::platform::entry_missing(path) {
        return Ok(None);
    }
    let absolute = crate::platform::absolute(path)?;
    let file = crate::platform::open_regular(&absolute)?;
    // File identity detects replacement without treating sibling writes as credential changes.
    let identity = artifactize_foundation::platform::private::file_identity(&file)?;
    let modified = file.metadata()?.modified()?;
    let mut data = Vec::new();
    file.take(MAX_CREDENTIAL_BYTES as u64 + 1)
        .read_to_end(&mut data)?;
    if data.len() > MAX_CREDENTIAL_BYTES {
        return Err(std::io::ErrorKind::InvalidData.into());
    }
    Ok(Some(ImportStamp {
        file: identity,
        modified,
        content: Sha256::digest(data),
    }))
}

fn read_file(
    path: &Path,
    unreadable: impl Fn(&str) -> AuthFileError,
) -> Result<Option<AuthFileTokens>, AuthFileError> {
    Ok(read_store(path, unreadable)?
        .and_then(|auth| auth.tokens.0.map(|crate::json::Object(tokens)| tokens)))
}

fn read_store(
    path: &Path,
    unreadable: impl Fn(&str) -> AuthFileError,
) -> Result<Option<AuthFile>, AuthFileError> {
    let file = match crate::platform::open_regular(path) {
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        result => result.map_err(|error| unreadable(&error.to_string()))?,
    };
    if !file.metadata().is_ok_and(|metadata| metadata.is_file()) {
        return Err(unreadable("it is not a regular file"));
    }
    let mut data = Vec::new();
    // Match owned credential storage: one extra byte detects oversized imports.
    file.take(MAX_CREDENTIAL_BYTES as u64 + 1)
        .read_to_end(&mut data)
        .map_err(|error| unreadable(&error.to_string()))?;
    if data.len() > MAX_CREDENTIAL_BYTES {
        return Err(unreadable("it is larger than 1 MiB"));
    }
    let auth: crate::json::Optional<crate::json::Object<AuthFile>> =
        serde_json::from_slice(&data).map_err(|_| unreadable("it is not a Codex auth file"))?;
    Ok(auth.0.map(|crate::json::Object(auth)| auth))
}

pub(super) fn secret_values(path: &Path) -> Result<Vec<String>, AuthFileError> {
    let Some(auth) = read_store(path, |reason| AuthFileError::Unreadable(reason.to_owned()))?
    else {
        return Ok(Vec::new());
    };
    // Every credential the store holds: its tokens, and an API key saved in their place.
    let tokens = auth.tokens.0.map(|crate::json::Object(tokens)| tokens);
    Ok(tokens
        .into_iter()
        .flat_map(|tokens| {
            [
                tokens.id_token.0,
                tokens.access_token.0,
                tokens.refresh_token.0,
            ]
        })
        .chain([auth.api_key.0])
        .flatten()
        .collect())
}

pub(super) fn read_auth_file_at(path: &Path) -> Result<Option<FileToken>, AuthFileError> {
    let name = crate::platform::path_text(path);
    let unreadable = |reason: &str| {
        AuthFileError::Unreadable(format!(
            "Cannot read the Codex CLI's sign-in in {name}: {reason}."
        ))
    };
    let Some(tokens) = read_file(path, unreadable)? else {
        return Ok(None);
    };
    let Some(access_token) = tokens
        .access_token
        .0
        .as_deref()
        .filter(|token| !token.is_empty())
    else {
        // An API key saved by `codex login --with-api-key` is not a ChatGPT sign-in.
        return Ok(None);
    };
    let claims = claims(access_token).unwrap_or_default();
    let expires_at = claims.exp.0;
    let account_id = tokens
        .account_id
        .0
        .as_deref()
        .filter(|id| !id.is_empty())
        .and_then(|id| id.parse().ok())
        .or_else(|| claims.account_id())
        .ok_or_else(|| unreadable("its token names no ChatGPT account"))?;
    Ok(Some(FileToken {
        token: Token {
            access_token: access_token.to_owned(),
            refresh_token: tokens.refresh_token.0.filter(|token| !token.is_empty()),
            account_id,
        },
        expires_at,
    }))
}

/// Write a refresh back into the Codex CLI's store, keeping every other field the CLI wrote,
/// as the CLI does after its own refresh.
pub(super) fn write_back(
    path: &Path,
    refreshed: &Refreshed,
    refresh_token: &str,
) -> Result<(), TokenError> {
    let failed =
        || TokenError::from("Cannot save the refreshed Codex sign-in in the Codex CLI's store.");
    let mut data = Vec::new();
    crate::platform::open_regular(path)
        .and_then(|file| {
            file.take(MAX_CREDENTIAL_BYTES as u64 + 1)
                .read_to_end(&mut data)
        })
        .map_err(|_| failed())?;
    let mut auth: serde_json::Value = serde_json::from_slice(&data).map_err(|_| failed())?;
    let tokens = auth
        .as_object_mut()
        .and_then(|auth| auth.get_mut("tokens"))
        .and_then(serde_json::Value::as_object_mut)
        .ok_or_else(failed)?;
    tokens.insert("access_token".into(), refreshed.access_token.clone().into());
    tokens.insert("refresh_token".into(), refresh_token.into());
    if let Some(id_token) = &refreshed.id_token {
        tokens.insert("id_token".into(), id_token.clone().into());
    }
    let refreshed_at = time::OffsetDateTime::now_utc()
        .format(&time::format_description::well_known::Rfc3339)
        .map_err(|_| failed())?;
    auth["last_refresh"] = refreshed_at.into();
    let bytes = serde_json::to_vec_pretty(&auth).map_err(|_| failed())?;
    let directory = path.parent().ok_or_else(failed)?;
    crate::platform::credential_files::replace(directory, path, |file| {
        use std::io::Write;
        file.write_all(&bytes).map_err(|error| error.to_string())
    })
    .map_err(|_| failed())
}

#[cfg(test)]
mod tests;