From 184fb02a9a1cae9b94fae76d1915189ef64c114a Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim <219906144+aibrahim-oai@users.noreply.github.com> Date: Wed, 18 Mar 2026 05:11:40 +0000 Subject: [PATCH] Extract codex-auth from codex-core Co-authored-by: Codex --- codex-rs/Cargo.lock | 24 ++ codex-rs/Cargo.toml | 2 + codex-rs/auth/BUILD.bazel | 6 + codex-rs/auth/Cargo.toml | 39 +++ codex-rs/auth/src/env_telemetry.rs | 52 ++++ codex-rs/auth/src/lib.rs | 103 +++++++ codex-rs/auth/src/storage.rs | 371 ++++++++++++++++++++++++ codex-rs/auth/src/storage_tests.rs | 289 ++++++++++++++++++ codex-rs/auth/src/token_data.rs | 167 +++++++++++ codex-rs/auth/src/token_data_tests.rs | 20 ++ codex-rs/core/Cargo.toml | 1 + codex-rs/core/src/auth.rs | 164 +---------- codex-rs/core/src/auth/storage.rs | 340 +--------------------- codex-rs/core/src/auth_env_telemetry.rs | 63 +--- codex-rs/core/src/token_data.rs | 181 +----------- codex-rs/login/Cargo.toml | 1 + codex-rs/login/src/lib.rs | 14 +- codex-rs/login/src/server.rs | 10 +- 18 files changed, 1119 insertions(+), 728 deletions(-) create mode 100644 codex-rs/auth/BUILD.bazel create mode 100644 codex-rs/auth/Cargo.toml create mode 100644 codex-rs/auth/src/env_telemetry.rs create mode 100644 codex-rs/auth/src/lib.rs create mode 100644 codex-rs/auth/src/storage.rs create mode 100644 codex-rs/auth/src/storage_tests.rs create mode 100644 codex-rs/auth/src/token_data.rs create mode 100644 codex-rs/auth/src/token_data_tests.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 0edb8df79e..72fb64f90b 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1594,6 +1594,28 @@ dependencies = [ "tokio-util", ] +[[package]] +name = "codex-auth" +version = "0.0.0" +dependencies = [ + "anyhow", + "base64 0.22.1", + "chrono", + "codex-app-server-protocol", + "codex-keyring-store", + "keyring", + "once_cell", + "pretty_assertions", + "schemars 0.8.22", + "serde", + "serde_json", + "sha2", + "tempfile", + "thiserror 2.0.18", + "tokio", + "tracing", +] + [[package]] name = "codex-backend-client" version = "0.0.0" @@ -1841,6 +1863,7 @@ dependencies = [ "codex-arg0", "codex-artifacts", "codex-async-utils", + "codex-auth", "codex-client", "codex-config", "codex-connectors", @@ -2148,6 +2171,7 @@ dependencies = [ "base64 0.22.1", "chrono", "codex-app-server-protocol", + "codex-auth", "codex-client", "codex-core", "core_test_support", diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index b1e0fcf371..2d9d4c662b 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -2,6 +2,7 @@ members = [ "backend-client", "ansi-escape", + "auth", "async-utils", "app-server", "app-server-client", @@ -86,6 +87,7 @@ license = "Apache-2.0" app_test_support = { path = "app-server/tests/common" } codex-ansi-escape = { path = "ansi-escape" } codex-api = { path = "codex-api" } +codex-auth = { path = "auth" } codex-artifacts = { path = "artifacts" } codex-package-manager = { path = "package-manager" } codex-app-server = { path = "app-server" } diff --git a/codex-rs/auth/BUILD.bazel b/codex-rs/auth/BUILD.bazel new file mode 100644 index 0000000000..c302696048 --- /dev/null +++ b/codex-rs/auth/BUILD.bazel @@ -0,0 +1,6 @@ +load("//:defs.bzl", "codex_rust_crate") + +codex_rust_crate( + name = "auth", + crate_name = "codex_auth", +) diff --git a/codex-rs/auth/Cargo.toml b/codex-rs/auth/Cargo.toml new file mode 100644 index 0000000000..1694fbe1df --- /dev/null +++ b/codex-rs/auth/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "codex-auth" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lints] +workspace = true + +[dependencies] +base64 = { workspace = true } +chrono = { workspace = true, features = ["serde"] } +codex-app-server-protocol = { workspace = true } +codex-keyring-store = { workspace = true } +once_cell = { workspace = true } +schemars = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +sha2 = { workspace = true } +thiserror = { workspace = true } +tracing = { workspace = true } + +[target.'cfg(target_os = "linux")'.dependencies] +keyring = { workspace = true, features = ["linux-native-async-persistent"] } + +[target.'cfg(target_os = "macos")'.dependencies] +keyring = { workspace = true, features = ["apple-native"] } + +[target.'cfg(target_os = "windows")'.dependencies] +keyring = { workspace = true, features = ["windows-native"] } + +[target.'cfg(any(target_os = "freebsd", target_os = "openbsd"))'.dependencies] +keyring = { workspace = true, features = ["sync-secret-service"] } + +[dev-dependencies] +anyhow = { workspace = true } +pretty_assertions = { workspace = true } +tempfile = { workspace = true } +tokio = { workspace = true, features = ["macros", "rt"] } diff --git a/codex-rs/auth/src/env_telemetry.rs b/codex-rs/auth/src/env_telemetry.rs new file mode 100644 index 0000000000..bf3056f736 --- /dev/null +++ b/codex-rs/auth/src/env_telemetry.rs @@ -0,0 +1,52 @@ +use crate::CODEX_API_KEY_ENV_VAR; +use crate::OPENAI_API_KEY_ENV_VAR; +use crate::REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR; + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct AuthEnvTelemetry { + pub openai_api_key_env_present: bool, + pub codex_api_key_env_present: bool, + pub codex_api_key_env_enabled: bool, + pub provider_env_key_name: Option, + pub provider_env_key_present: Option, + pub refresh_token_url_override_present: bool, +} + +pub fn collect_auth_env_telemetry( + provider_env_key_configured: bool, + provider_env_key: Option<&str>, + codex_api_key_env_enabled: bool, +) -> AuthEnvTelemetry { + AuthEnvTelemetry { + openai_api_key_env_present: env_var_present(OPENAI_API_KEY_ENV_VAR), + codex_api_key_env_present: env_var_present(CODEX_API_KEY_ENV_VAR), + codex_api_key_env_enabled, + provider_env_key_name: provider_env_key_configured.then(|| "configured".to_string()), + provider_env_key_present: provider_env_key.map(env_var_present), + refresh_token_url_override_present: env_var_present(REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR), + } +} + +fn env_var_present(name: &str) -> bool { + match std::env::var(name) { + Ok(value) => !value.trim().is_empty(), + Err(std::env::VarError::NotUnicode(_)) => true, + Err(std::env::VarError::NotPresent) => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + #[test] + fn collect_auth_env_telemetry_buckets_provider_env_key_name() { + let telemetry = collect_auth_env_telemetry(true, Some("sk-should-not-leak"), false); + + assert_eq!( + telemetry.provider_env_key_name, + Some("configured".to_string()) + ); + } +} diff --git a/codex-rs/auth/src/lib.rs b/codex-rs/auth/src/lib.rs new file mode 100644 index 0000000000..c578df0bf5 --- /dev/null +++ b/codex-rs/auth/src/lib.rs @@ -0,0 +1,103 @@ +mod env_telemetry; +pub mod storage; +pub mod token_data; + +use std::env; +use std::path::Path; + +use codex_app_server_protocol::AuthMode; + +pub use env_telemetry::AuthEnvTelemetry; +pub use env_telemetry::collect_auth_env_telemetry; +pub use storage::AuthCredentialsStoreMode; +pub use storage::AuthDotJson; +pub use storage::AuthStorageBackend; +pub use storage::create_auth_storage; +pub use token_data::IdTokenInfo; +pub use token_data::IdTokenInfoError; +pub use token_data::KnownPlan; +pub use token_data::PlanType; +pub use token_data::TokenData; +pub use token_data::parse_chatgpt_jwt_claims; + +pub const OPENAI_API_KEY_ENV_VAR: &str = "OPENAI_API_KEY"; +pub const CODEX_API_KEY_ENV_VAR: &str = "CODEX_API_KEY"; +pub const REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR: &str = "CODEX_REFRESH_TOKEN_URL_OVERRIDE"; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExternalAuthTokens { + pub access_token: String, + pub chatgpt_account_id: String, + pub chatgpt_plan_type: Option, +} + +pub fn read_openai_api_key_from_env() -> Option { + env::var(OPENAI_API_KEY_ENV_VAR) + .ok() + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()) +} + +pub fn read_codex_api_key_from_env() -> Option { + env::var(CODEX_API_KEY_ENV_VAR) + .ok() + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()) +} + +pub fn logout( + codex_home: &Path, + auth_credentials_store_mode: AuthCredentialsStoreMode, +) -> std::io::Result { + let storage = create_auth_storage(codex_home.to_path_buf(), auth_credentials_store_mode); + storage.delete() +} + +pub fn login_with_api_key( + codex_home: &Path, + api_key: &str, + auth_credentials_store_mode: AuthCredentialsStoreMode, +) -> std::io::Result<()> { + let auth_dot_json = AuthDotJson { + auth_mode: Some(AuthMode::ApiKey), + openai_api_key: Some(api_key.to_string()), + tokens: None, + last_refresh: None, + }; + save_auth(codex_home, &auth_dot_json, auth_credentials_store_mode) +} + +pub fn login_with_chatgpt_auth_tokens( + codex_home: &Path, + access_token: &str, + chatgpt_account_id: &str, + chatgpt_plan_type: Option<&str>, +) -> std::io::Result<()> { + let auth_dot_json = AuthDotJson::from_external_access_token( + access_token, + chatgpt_account_id, + chatgpt_plan_type, + )?; + save_auth( + codex_home, + &auth_dot_json, + AuthCredentialsStoreMode::Ephemeral, + ) +} + +pub fn save_auth( + codex_home: &Path, + auth: &AuthDotJson, + auth_credentials_store_mode: AuthCredentialsStoreMode, +) -> std::io::Result<()> { + let storage = create_auth_storage(codex_home.to_path_buf(), auth_credentials_store_mode); + storage.save(auth) +} + +pub fn load_auth_dot_json( + codex_home: &Path, + auth_credentials_store_mode: AuthCredentialsStoreMode, +) -> std::io::Result> { + let storage = create_auth_storage(codex_home.to_path_buf(), auth_credentials_store_mode); + storage.load() +} diff --git a/codex-rs/auth/src/storage.rs b/codex-rs/auth/src/storage.rs new file mode 100644 index 0000000000..b9806588dd --- /dev/null +++ b/codex-rs/auth/src/storage.rs @@ -0,0 +1,371 @@ +use chrono::DateTime; +use chrono::Utc; +use schemars::JsonSchema; +use serde::Deserialize; +use serde::Serialize; +use sha2::Digest; +use sha2::Sha256; +use std::collections::HashMap; +use std::fmt::Debug; +use std::fs::File; +use std::fs::OpenOptions; +use std::io::Read; +use std::io::Write; +#[cfg(unix)] +use std::os::unix::fs::OpenOptionsExt; +use std::path::Path; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::Mutex; +use tracing::warn; + +use crate::PlanType; +use crate::TokenData; +use crate::parse_chatgpt_jwt_claims; +use codex_app_server_protocol::AuthMode; +use codex_keyring_store::DefaultKeyringStore; +use codex_keyring_store::KeyringStore; +use once_cell::sync::Lazy; + +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "lowercase")] +pub enum AuthCredentialsStoreMode { + #[default] + File, + Keyring, + Auto, + Ephemeral, +} + +#[derive(Deserialize, Serialize, Clone, Debug, PartialEq)] +pub struct AuthDotJson { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub auth_mode: Option, + #[serde(rename = "OPENAI_API_KEY")] + pub openai_api_key: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_refresh: Option>, +} + +impl AuthDotJson { + pub fn from_external_access_token( + access_token: &str, + chatgpt_account_id: &str, + chatgpt_plan_type: Option<&str>, + ) -> std::io::Result { + let mut token_info = + parse_chatgpt_jwt_claims(access_token).map_err(std::io::Error::other)?; + token_info.chatgpt_account_id = Some(chatgpt_account_id.to_string()); + token_info.chatgpt_plan_type = chatgpt_plan_type + .map(PlanType::from_raw_value) + .or(token_info.chatgpt_plan_type) + .or(Some(PlanType::Unknown("unknown".to_string()))); + let tokens = TokenData { + id_token: token_info, + access_token: access_token.to_string(), + refresh_token: String::new(), + account_id: Some(chatgpt_account_id.to_string()), + }; + + Ok(Self { + auth_mode: Some(AuthMode::ChatgptAuthTokens), + openai_api_key: None, + tokens: Some(tokens), + last_refresh: Some(Utc::now()), + }) + } + + pub fn resolved_mode(&self) -> AuthMode { + if let Some(mode) = self.auth_mode { + return mode; + } + if self.openai_api_key.is_some() { + return AuthMode::ApiKey; + } + AuthMode::Chatgpt + } + + pub fn storage_mode( + &self, + auth_credentials_store_mode: AuthCredentialsStoreMode, + ) -> AuthCredentialsStoreMode { + if self.resolved_mode() == AuthMode::ChatgptAuthTokens { + AuthCredentialsStoreMode::Ephemeral + } else { + auth_credentials_store_mode + } + } +} + +fn get_auth_file(codex_home: &Path) -> PathBuf { + codex_home.join("auth.json") +} + +fn delete_file_if_exists(codex_home: &Path) -> std::io::Result { + let auth_file = get_auth_file(codex_home); + match std::fs::remove_file(&auth_file) { + Ok(()) => Ok(true), + Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(err) => Err(err), + } +} + +pub trait AuthStorageBackend: Debug + Send + Sync { + fn load(&self) -> std::io::Result>; + fn save(&self, auth: &AuthDotJson) -> std::io::Result<()>; + fn delete(&self) -> std::io::Result; +} + +#[derive(Clone, Debug)] +struct FileAuthStorage { + codex_home: PathBuf, +} + +impl FileAuthStorage { + fn new(codex_home: PathBuf) -> Self { + Self { codex_home } + } + + fn try_read_auth_json(&self, auth_file: &Path) -> std::io::Result { + let mut file = File::open(auth_file)?; + let mut contents = String::new(); + file.read_to_string(&mut contents)?; + let auth_dot_json: AuthDotJson = serde_json::from_str(&contents)?; + Ok(auth_dot_json) + } +} + +impl AuthStorageBackend for FileAuthStorage { + fn load(&self) -> std::io::Result> { + let auth_file = get_auth_file(&self.codex_home); + let auth_dot_json = match self.try_read_auth_json(&auth_file) { + Ok(auth) => auth, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(err) => return Err(err), + }; + Ok(Some(auth_dot_json)) + } + + fn save(&self, auth_dot_json: &AuthDotJson) -> std::io::Result<()> { + let auth_file = get_auth_file(&self.codex_home); + if let Some(parent) = auth_file.parent() { + std::fs::create_dir_all(parent)?; + } + let json_data = serde_json::to_string_pretty(auth_dot_json)?; + let mut options = OpenOptions::new(); + options.truncate(true).write(true).create(true); + #[cfg(unix)] + { + options.mode(0o600); + } + let mut file = options.open(auth_file)?; + file.write_all(json_data.as_bytes())?; + file.flush()?; + Ok(()) + } + + fn delete(&self) -> std::io::Result { + delete_file_if_exists(&self.codex_home) + } +} + +const KEYRING_SERVICE: &str = "Codex Auth"; + +fn compute_store_key(codex_home: &Path) -> std::io::Result { + let canonical = codex_home + .canonicalize() + .unwrap_or_else(|_| codex_home.to_path_buf()); + let path_str = canonical.to_string_lossy(); + let mut hasher = Sha256::new(); + hasher.update(path_str.as_bytes()); + let digest = hasher.finalize(); + let hex = format!("{digest:x}"); + let truncated = hex.get(..16).unwrap_or(&hex); + Ok(format!("cli|{truncated}")) +} + +#[derive(Clone, Debug)] +struct KeyringAuthStorage { + codex_home: PathBuf, + keyring_store: Arc, +} + +impl KeyringAuthStorage { + fn new(codex_home: PathBuf, keyring_store: Arc) -> Self { + Self { + codex_home, + keyring_store, + } + } + + fn load_from_keyring(&self, key: &str) -> std::io::Result> { + match self.keyring_store.load(KEYRING_SERVICE, key) { + Ok(Some(serialized)) => serde_json::from_str(&serialized).map(Some).map_err(|err| { + std::io::Error::other(format!( + "failed to deserialize CLI auth from keyring: {err}" + )) + }), + Ok(None) => Ok(None), + Err(error) => Err(std::io::Error::other(format!( + "failed to load CLI auth from keyring: {}", + error.message() + ))), + } + } + + fn save_to_keyring(&self, key: &str, value: &str) -> std::io::Result<()> { + match self.keyring_store.save(KEYRING_SERVICE, key, value) { + Ok(()) => Ok(()), + Err(error) => { + let message = format!( + "failed to write OAuth tokens to keyring: {}", + error.message() + ); + warn!("{message}"); + Err(std::io::Error::other(message)) + } + } + } +} + +impl AuthStorageBackend for KeyringAuthStorage { + fn load(&self) -> std::io::Result> { + let key = compute_store_key(&self.codex_home)?; + self.load_from_keyring(&key) + } + + fn save(&self, auth: &AuthDotJson) -> std::io::Result<()> { + let key = compute_store_key(&self.codex_home)?; + let serialized = serde_json::to_string(auth).map_err(std::io::Error::other)?; + self.save_to_keyring(&key, &serialized)?; + if let Err(err) = delete_file_if_exists(&self.codex_home) { + warn!("failed to remove CLI auth fallback file: {err}"); + } + Ok(()) + } + + fn delete(&self) -> std::io::Result { + let key = compute_store_key(&self.codex_home)?; + let keyring_removed = self + .keyring_store + .delete(KEYRING_SERVICE, &key) + .map_err(|err| { + std::io::Error::other(format!("failed to delete auth from keyring: {err}")) + })?; + let file_removed = delete_file_if_exists(&self.codex_home)?; + Ok(keyring_removed || file_removed) + } +} + +#[derive(Clone, Debug)] +struct AutoAuthStorage { + keyring_storage: Arc, + file_storage: Arc, +} + +impl AutoAuthStorage { + fn new(codex_home: PathBuf, keyring_store: Arc) -> Self { + Self { + keyring_storage: Arc::new(KeyringAuthStorage::new(codex_home.clone(), keyring_store)), + file_storage: Arc::new(FileAuthStorage::new(codex_home)), + } + } +} + +impl AuthStorageBackend for AutoAuthStorage { + fn load(&self) -> std::io::Result> { + match self.keyring_storage.load() { + Ok(Some(auth)) => Ok(Some(auth)), + Ok(None) => self.file_storage.load(), + Err(err) => { + warn!("failed to load CLI auth from keyring, falling back to file storage: {err}"); + self.file_storage.load() + } + } + } + + fn save(&self, auth: &AuthDotJson) -> std::io::Result<()> { + match self.keyring_storage.save(auth) { + Ok(()) => Ok(()), + Err(err) => { + warn!("failed to save auth to keyring, falling back to file storage: {err}"); + self.file_storage.save(auth) + } + } + } + + fn delete(&self) -> std::io::Result { + self.keyring_storage.delete() + } +} + +static EPHEMERAL_AUTH_STORE: Lazy>> = + Lazy::new(|| Mutex::new(HashMap::new())); + +#[derive(Clone, Debug)] +struct EphemeralAuthStorage { + codex_home: PathBuf, +} + +impl EphemeralAuthStorage { + fn new(codex_home: PathBuf) -> Self { + Self { codex_home } + } + + fn with_store(&self, action: F) -> std::io::Result + where + F: FnOnce(&mut HashMap, String) -> std::io::Result, + { + let key = compute_store_key(&self.codex_home)?; + let mut store = EPHEMERAL_AUTH_STORE + .lock() + .map_err(|_| std::io::Error::other("failed to lock ephemeral auth storage"))?; + action(&mut store, key) + } +} + +impl AuthStorageBackend for EphemeralAuthStorage { + fn load(&self) -> std::io::Result> { + self.with_store(|store, key| Ok(store.get(&key).cloned())) + } + + fn save(&self, auth: &AuthDotJson) -> std::io::Result<()> { + self.with_store(|store, key| { + store.insert(key, auth.clone()); + Ok(()) + }) + } + + fn delete(&self) -> std::io::Result { + self.with_store(|store, key| Ok(store.remove(&key).is_some())) + } +} + +pub fn create_auth_storage( + codex_home: PathBuf, + mode: AuthCredentialsStoreMode, +) -> Arc { + let keyring_store: Arc = Arc::new(DefaultKeyringStore); + create_auth_storage_with_keyring_store(codex_home, mode, keyring_store) +} + +fn create_auth_storage_with_keyring_store( + codex_home: PathBuf, + mode: AuthCredentialsStoreMode, + keyring_store: Arc, +) -> Arc { + match mode { + AuthCredentialsStoreMode::File => Arc::new(FileAuthStorage::new(codex_home)), + AuthCredentialsStoreMode::Keyring => { + Arc::new(KeyringAuthStorage::new(codex_home, keyring_store)) + } + AuthCredentialsStoreMode::Auto => Arc::new(AutoAuthStorage::new(codex_home, keyring_store)), + AuthCredentialsStoreMode::Ephemeral => Arc::new(EphemeralAuthStorage::new(codex_home)), + } +} + +#[cfg(test)] +#[path = "storage_tests.rs"] +mod tests; diff --git a/codex-rs/auth/src/storage_tests.rs b/codex-rs/auth/src/storage_tests.rs new file mode 100644 index 0000000000..29b45fc1b2 --- /dev/null +++ b/codex-rs/auth/src/storage_tests.rs @@ -0,0 +1,289 @@ +use super::*; +use crate::token_data::IdTokenInfo; +use anyhow::Context; +use base64::Engine; +use codex_keyring_store::tests::MockKeyringStore; +use keyring::Error as KeyringError; +use pretty_assertions::assert_eq; +use serde::Serialize; +use serde_json::json; +use tempfile::tempdir; + +#[tokio::test] +async fn file_storage_load_returns_auth_dot_json() -> anyhow::Result<()> { + let codex_home = tempdir()?; + let storage = FileAuthStorage::new(codex_home.path().to_path_buf()); + let auth_dot_json = AuthDotJson { + auth_mode: Some(AuthMode::ApiKey), + openai_api_key: Some("test-key".to_string()), + tokens: None, + last_refresh: Some(Utc::now()), + }; + + storage + .save(&auth_dot_json) + .context("failed to save auth file")?; + + let loaded = storage.load().context("failed to load auth file")?; + assert_eq!(Some(auth_dot_json), loaded); + Ok(()) +} + +#[tokio::test] +async fn file_storage_save_persists_auth_dot_json() -> anyhow::Result<()> { + let codex_home = tempdir()?; + let storage = FileAuthStorage::new(codex_home.path().to_path_buf()); + let auth_dot_json = AuthDotJson { + auth_mode: Some(AuthMode::ApiKey), + openai_api_key: Some("test-key".to_string()), + tokens: None, + last_refresh: Some(Utc::now()), + }; + + let file = get_auth_file(codex_home.path()); + storage + .save(&auth_dot_json) + .context("failed to save auth file")?; + + let same_auth_dot_json = storage + .try_read_auth_json(&file) + .context("failed to read auth file after save")?; + assert_eq!(auth_dot_json, same_auth_dot_json); + Ok(()) +} + +#[test] +fn file_storage_delete_removes_auth_file() -> anyhow::Result<()> { + let dir = tempdir()?; + let auth_dot_json = AuthDotJson { + auth_mode: Some(AuthMode::ApiKey), + openai_api_key: Some("sk-test-key".to_string()), + tokens: None, + last_refresh: None, + }; + let storage = create_auth_storage(dir.path().to_path_buf(), AuthCredentialsStoreMode::File); + storage.save(&auth_dot_json)?; + assert!(dir.path().join("auth.json").exists()); + let storage = FileAuthStorage::new(dir.path().to_path_buf()); + let removed = storage.delete()?; + assert!(removed); + assert!(!dir.path().join("auth.json").exists()); + Ok(()) +} + +#[test] +fn ephemeral_storage_save_load_delete_is_in_memory_only() -> anyhow::Result<()> { + let dir = tempdir()?; + let storage = create_auth_storage( + dir.path().to_path_buf(), + AuthCredentialsStoreMode::Ephemeral, + ); + let auth_dot_json = AuthDotJson { + auth_mode: Some(AuthMode::ApiKey), + openai_api_key: Some("sk-ephemeral".to_string()), + tokens: None, + last_refresh: Some(Utc::now()), + }; + + storage.save(&auth_dot_json)?; + let loaded = storage.load()?; + assert_eq!(Some(auth_dot_json), loaded); + + let removed = storage.delete()?; + assert!(removed); + let loaded = storage.load()?; + assert_eq!(None, loaded); + assert!(!get_auth_file(dir.path()).exists()); + Ok(()) +} + +fn seed_keyring_and_fallback_auth_file_for_delete( + mock_keyring: &MockKeyringStore, + codex_home: &Path, + compute_key: F, +) -> anyhow::Result<(String, PathBuf)> +where + F: FnOnce() -> std::io::Result, +{ + let key = compute_key()?; + mock_keyring.save(KEYRING_SERVICE, &key, "{}")?; + let auth_file = get_auth_file(codex_home); + std::fs::write(&auth_file, "stale")?; + Ok((key, auth_file)) +} + +fn seed_keyring_with_auth( + mock_keyring: &MockKeyringStore, + compute_key: F, + auth: &AuthDotJson, +) -> anyhow::Result<()> +where + F: FnOnce() -> std::io::Result, +{ + let key = compute_key()?; + let serialized = serde_json::to_string(auth)?; + mock_keyring.save(KEYRING_SERVICE, &key, &serialized)?; + Ok(()) +} + +fn assert_keyring_saved_auth_and_removed_fallback( + mock_keyring: &MockKeyringStore, + key: &str, + codex_home: &Path, + expected: &AuthDotJson, +) { + let saved_value = mock_keyring + .saved_value(key) + .expect("keyring entry should exist"); + let expected_serialized = serde_json::to_string(expected).expect("serialize expected auth"); + assert_eq!(saved_value, expected_serialized); + let auth_file = get_auth_file(codex_home); + assert!( + !auth_file.exists(), + "fallback auth.json should be removed after keyring save" + ); +} + +fn id_token_with_prefix(prefix: &str) -> IdTokenInfo { + #[derive(Serialize)] + struct Header { + alg: &'static str, + typ: &'static str, + } + + let header = Header { + alg: "none", + typ: "JWT", + }; + let payload = json!({ + "email": format!("{prefix}@example.com"), + "https://api.openai.com/auth": { + "chatgpt_account_id": format!("{prefix}-account"), + }, + }); + let encode = |bytes: &[u8]| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes); + let header_b64 = encode(&serde_json::to_vec(&header).expect("serialize header")); + let payload_b64 = encode(&serde_json::to_vec(&payload).expect("serialize payload")); + let signature_b64 = encode(b"sig"); + let fake_jwt = format!("{header_b64}.{payload_b64}.{signature_b64}"); + + crate::token_data::parse_chatgpt_jwt_claims(&fake_jwt).expect("fake JWT should parse") +} + +fn auth_with_prefix(prefix: &str) -> AuthDotJson { + AuthDotJson { + auth_mode: Some(AuthMode::ApiKey), + openai_api_key: Some(format!("{prefix}-api-key")), + tokens: Some(TokenData { + id_token: id_token_with_prefix(prefix), + access_token: format!("{prefix}-access"), + refresh_token: format!("{prefix}-refresh"), + account_id: Some(format!("{prefix}-account-id")), + }), + last_refresh: None, + } +} + +#[test] +fn keyring_auth_storage_load_returns_deserialized_auth() -> anyhow::Result<()> { + let codex_home = tempdir()?; + let mock_keyring = MockKeyringStore::default(); + let storage = KeyringAuthStorage::new( + codex_home.path().to_path_buf(), + Arc::new(mock_keyring.clone()), + ); + let expected = AuthDotJson { + auth_mode: Some(AuthMode::ApiKey), + openai_api_key: Some("sk-test".to_string()), + tokens: None, + last_refresh: None, + }; + seed_keyring_with_auth( + &mock_keyring, + || compute_store_key(codex_home.path()), + &expected, + )?; + + let loaded = storage.load()?; + assert_eq!(Some(expected), loaded); + Ok(()) +} + +#[test] +fn keyring_auth_storage_compute_store_key_for_home_directory() -> anyhow::Result<()> { + let codex_home = PathBuf::from("~/.codex"); + + let key = compute_store_key(codex_home.as_path())?; + + assert_eq!(key, "cli|940db7b1d0e4eb40"); + Ok(()) +} + +#[test] +fn keyring_auth_storage_save_persists_and_removes_fallback_file() -> anyhow::Result<()> { + let codex_home = tempdir()?; + let mock_keyring = MockKeyringStore::default(); + let storage = KeyringAuthStorage::new( + codex_home.path().to_path_buf(), + Arc::new(mock_keyring.clone()), + ); + let auth_file = get_auth_file(codex_home.path()); + std::fs::write(&auth_file, "stale")?; + let auth = AuthDotJson { + auth_mode: Some(AuthMode::Chatgpt), + openai_api_key: None, + tokens: Some(TokenData { + id_token: Default::default(), + access_token: "access".to_string(), + refresh_token: "refresh".to_string(), + account_id: Some("account".to_string()), + }), + last_refresh: Some(Utc::now()), + }; + + storage.save(&auth)?; + + let key = compute_store_key(codex_home.path())?; + assert_keyring_saved_auth_and_removed_fallback(&mock_keyring, &key, codex_home.path(), &auth); + Ok(()) +} + +#[test] +fn keyring_auth_storage_delete_removes_keyring_and_file() -> anyhow::Result<()> { + let codex_home = tempdir()?; + let mock_keyring = MockKeyringStore::default(); + let storage = KeyringAuthStorage::new( + codex_home.path().to_path_buf(), + Arc::new(mock_keyring.clone()), + ); + let (key, auth_file) = + seed_keyring_and_fallback_auth_file_for_delete(&mock_keyring, codex_home.path(), || { + compute_store_key(codex_home.path()) + })?; + + let removed = storage.delete()?; + + assert!(removed); + assert!(!mock_keyring.contains(&key)); + assert!(!auth_file.exists()); + Ok(()) +} + +#[test] +fn auto_auth_storage_falls_back_to_file_on_keyring_load_error() -> anyhow::Result<()> { + let codex_home = tempdir()?; + let mock_keyring = MockKeyringStore::default(); + let key = compute_store_key(codex_home.path())?; + mock_keyring.set_error(&key, KeyringError::NoEntry); + let storage = AutoAuthStorage::new( + codex_home.path().to_path_buf(), + Arc::new(mock_keyring.clone()), + ); + let expected = auth_with_prefix("fallback"); + FileAuthStorage::new(codex_home.path().to_path_buf()).save(&expected)?; + + let loaded = storage.load()?; + + assert_eq!(Some(expected), loaded); + Ok(()) +} diff --git a/codex-rs/auth/src/token_data.rs b/codex-rs/auth/src/token_data.rs new file mode 100644 index 0000000000..8794548051 --- /dev/null +++ b/codex-rs/auth/src/token_data.rs @@ -0,0 +1,167 @@ +use base64::Engine; +use serde::Deserialize; +use serde::Serialize; +use thiserror::Error; + +#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Default)] +pub struct TokenData { + #[serde( + deserialize_with = "deserialize_id_token", + serialize_with = "serialize_id_token" + )] + pub id_token: IdTokenInfo, + pub access_token: String, + pub refresh_token: String, + pub account_id: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] +pub struct IdTokenInfo { + pub email: Option, + pub chatgpt_plan_type: Option, + pub chatgpt_user_id: Option, + pub chatgpt_account_id: Option, + pub raw_jwt: String, +} + +impl IdTokenInfo { + pub fn get_chatgpt_plan_type(&self) -> Option { + self.chatgpt_plan_type.as_ref().map(|t| match t { + PlanType::Known(plan) => format!("{plan:?}"), + PlanType::Unknown(s) => s.clone(), + }) + } + + pub fn is_workspace_account(&self) -> bool { + matches!( + self.chatgpt_plan_type, + Some(PlanType::Known( + KnownPlan::Team | KnownPlan::Business | KnownPlan::Enterprise | KnownPlan::Edu + )) + ) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum PlanType { + Known(KnownPlan), + Unknown(String), +} + +impl PlanType { + pub fn from_raw_value(raw: &str) -> Self { + match raw.to_ascii_lowercase().as_str() { + "free" => Self::Known(KnownPlan::Free), + "go" => Self::Known(KnownPlan::Go), + "plus" => Self::Known(KnownPlan::Plus), + "pro" => Self::Known(KnownPlan::Pro), + "team" => Self::Known(KnownPlan::Team), + "business" => Self::Known(KnownPlan::Business), + "enterprise" => Self::Known(KnownPlan::Enterprise), + "education" | "edu" => Self::Known(KnownPlan::Edu), + _ => Self::Unknown(raw.to_string()), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum KnownPlan { + Free, + Go, + Plus, + Pro, + Team, + Business, + Enterprise, + Edu, +} + +#[derive(Deserialize)] +struct IdClaims { + #[serde(default)] + email: Option, + #[serde(rename = "https://api.openai.com/profile", default)] + profile: Option, + #[serde(rename = "https://api.openai.com/auth", default)] + auth: Option, +} + +#[derive(Deserialize)] +struct ProfileClaims { + #[serde(default)] + email: Option, +} + +#[derive(Deserialize)] +struct AuthClaims { + #[serde(default)] + chatgpt_plan_type: Option, + #[serde(default)] + chatgpt_user_id: Option, + #[serde(default)] + user_id: Option, + #[serde(default)] + chatgpt_account_id: Option, +} + +#[derive(Debug, Error)] +pub enum IdTokenInfoError { + #[error("invalid ID token format")] + InvalidFormat, + #[error(transparent)] + Base64(#[from] base64::DecodeError), + #[error(transparent)] + Json(#[from] serde_json::Error), +} + +pub fn parse_chatgpt_jwt_claims(jwt: &str) -> Result { + let mut parts = jwt.split('.'); + let (_header_b64, payload_b64, _sig_b64) = match (parts.next(), parts.next(), parts.next()) { + (Some(h), Some(p), Some(s)) if !h.is_empty() && !p.is_empty() && !s.is_empty() => (h, p, s), + _ => return Err(IdTokenInfoError::InvalidFormat), + }; + + let payload_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(payload_b64)?; + let claims: IdClaims = serde_json::from_slice(&payload_bytes)?; + let email = claims + .email + .or_else(|| claims.profile.and_then(|profile| profile.email)); + + match claims.auth { + Some(auth) => Ok(IdTokenInfo { + email, + raw_jwt: jwt.to_string(), + chatgpt_plan_type: auth.chatgpt_plan_type, + chatgpt_user_id: auth.chatgpt_user_id.or(auth.user_id), + chatgpt_account_id: auth.chatgpt_account_id, + }), + None => Ok(IdTokenInfo { + email, + raw_jwt: jwt.to_string(), + chatgpt_plan_type: None, + chatgpt_user_id: None, + chatgpt_account_id: None, + }), + } +} + +fn deserialize_id_token<'de, D>(deserializer: D) -> Result +where + D: serde::Deserializer<'de>, +{ + let s = String::deserialize(deserializer)?; + parse_chatgpt_jwt_claims(&s).map_err(serde::de::Error::custom) +} + +fn serialize_id_token(id_token: &IdTokenInfo, serializer: S) -> Result +where + S: serde::Serializer, +{ + serializer.serialize_str(&id_token.raw_jwt) +} + +#[cfg(test)] +#[path = "token_data_tests.rs"] +mod tests; diff --git a/codex-rs/auth/src/token_data_tests.rs b/codex-rs/auth/src/token_data_tests.rs new file mode 100644 index 0000000000..6d72bb8a9e --- /dev/null +++ b/codex-rs/auth/src/token_data_tests.rs @@ -0,0 +1,20 @@ +use super::*; +use pretty_assertions::assert_eq; + +#[test] +fn parses_id_token_claims() { + let jwt = "eyJhbGciOiJub25lIn0.eyJlbWFpbCI6InVzZXJAZXhhbXBsZS5jb20iLCJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF9wbGFuX3R5cGUiOiJwcm8iLCJjaGF0Z3B0X3VzZXJfaWQiOiJ1c2VyLTEiLCJjaGF0Z3B0X2FjY291bnRfaWQiOiJ3cy0xIn19.c2ln"; + + let claims = parse_chatgpt_jwt_claims(jwt).expect("jwt should parse"); + + assert_eq!( + claims, + IdTokenInfo { + email: Some("user@example.com".to_string()), + chatgpt_plan_type: Some(PlanType::Known(KnownPlan::Pro)), + chatgpt_user_id: Some("user-1".to_string()), + chatgpt_account_id: Some("ws-1".to_string()), + raw_jwt: jwt.to_string(), + } + ); +} diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index 4b6f7c892b..4cd995dc8a 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -28,6 +28,7 @@ chardetng = { workspace = true } chrono = { workspace = true, features = ["serde"] } clap = { workspace = true, features = ["derive"] } codex-api = { workspace = true } +codex-auth = { workspace = true } codex-app-server-protocol = { workspace = true } codex-apply-patch = { workspace = true } codex-async-utils = { workspace = true } diff --git a/codex-rs/core/src/auth.rs b/codex-rs/core/src/auth.rs index 90f0dcfdaf..8c157b0242 100644 --- a/codex-rs/core/src/auth.rs +++ b/codex-rs/core/src/auth.rs @@ -7,7 +7,6 @@ use serde::Deserialize; use serde::Serialize; #[cfg(test)] use serial_test::serial; -use std::env; use std::fmt::Debug; use std::path::Path; use std::path::PathBuf; @@ -16,6 +15,8 @@ use std::sync::Mutex; use std::sync::RwLock; use codex_app_server_protocol::AuthMode as ApiAuthMode; +use codex_auth::CODEX_API_KEY_ENV_VAR; +use codex_auth::OPENAI_API_KEY_ENV_VAR; use codex_otel::TelemetryAuthMode; use codex_protocol::config_types::ForcedLoginMethod; @@ -31,6 +32,14 @@ use crate::token_data::PlanType as InternalPlanType; use crate::token_data::TokenData; use crate::token_data::parse_chatgpt_jwt_claims; use crate::util::try_parse_error_message; +pub use codex_auth::REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR; +pub use codex_auth::load_auth_dot_json; +pub use codex_auth::login_with_api_key; +pub use codex_auth::login_with_chatgpt_auth_tokens; +pub use codex_auth::logout; +pub use codex_auth::read_codex_api_key_from_env; +pub use codex_auth::read_openai_api_key_from_env; +pub use codex_auth::save_auth; use codex_client::CodexHttpClient; use codex_protocol::account::PlanType as AccountPlanType; use serde_json::Value; @@ -102,7 +111,6 @@ const REFRESH_TOKEN_UNKNOWN_MESSAGE: &str = "Your access token could not be refreshed. Please log out and sign in again."; const REFRESH_TOKEN_ACCOUNT_MISMATCH_MESSAGE: &str = "Your access token could not be refreshed because you have since logged out or signed in to another account. Please sign in again."; const REFRESH_TOKEN_URL: &str = "https://auth.openai.com/oauth/token"; -pub const REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR: &str = "CODEX_REFRESH_TOKEN_URL_OVERRIDE"; #[derive(Debug, Error)] pub enum RefreshTokenError { @@ -112,12 +120,7 @@ pub enum RefreshTokenError { Transient(#[from] std::io::Error), } -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct ExternalAuthTokens { - pub access_token: String, - pub chatgpt_account_id: String, - pub chatgpt_plan_type: Option, -} +pub use codex_auth::ExternalAuthTokens; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ExternalAuthRefreshReason { @@ -374,90 +377,6 @@ impl ChatgptAuth { } } -pub const OPENAI_API_KEY_ENV_VAR: &str = "OPENAI_API_KEY"; -pub const CODEX_API_KEY_ENV_VAR: &str = "CODEX_API_KEY"; - -pub fn read_openai_api_key_from_env() -> Option { - env::var(OPENAI_API_KEY_ENV_VAR) - .ok() - .map(|value| value.trim().to_string()) - .filter(|value| !value.is_empty()) -} - -pub fn read_codex_api_key_from_env() -> Option { - env::var(CODEX_API_KEY_ENV_VAR) - .ok() - .map(|value| value.trim().to_string()) - .filter(|value| !value.is_empty()) -} - -/// Delete the auth.json file inside `codex_home` if it exists. Returns `Ok(true)` -/// if a file was removed, `Ok(false)` if no auth file was present. -pub fn logout( - codex_home: &Path, - auth_credentials_store_mode: AuthCredentialsStoreMode, -) -> std::io::Result { - let storage = create_auth_storage(codex_home.to_path_buf(), auth_credentials_store_mode); - storage.delete() -} - -/// Writes an `auth.json` that contains only the API key. -pub fn login_with_api_key( - codex_home: &Path, - api_key: &str, - auth_credentials_store_mode: AuthCredentialsStoreMode, -) -> std::io::Result<()> { - let auth_dot_json = AuthDotJson { - auth_mode: Some(ApiAuthMode::ApiKey), - openai_api_key: Some(api_key.to_string()), - tokens: None, - last_refresh: None, - }; - save_auth(codex_home, &auth_dot_json, auth_credentials_store_mode) -} - -/// Writes an in-memory auth payload for externally managed ChatGPT tokens. -pub fn login_with_chatgpt_auth_tokens( - codex_home: &Path, - access_token: &str, - chatgpt_account_id: &str, - chatgpt_plan_type: Option<&str>, -) -> std::io::Result<()> { - let auth_dot_json = AuthDotJson::from_external_access_token( - access_token, - chatgpt_account_id, - chatgpt_plan_type, - )?; - save_auth( - codex_home, - &auth_dot_json, - AuthCredentialsStoreMode::Ephemeral, - ) -} - -/// Persist the provided auth payload using the specified backend. -pub fn save_auth( - codex_home: &Path, - auth: &AuthDotJson, - auth_credentials_store_mode: AuthCredentialsStoreMode, -) -> std::io::Result<()> { - let storage = create_auth_storage(codex_home.to_path_buf(), auth_credentials_store_mode); - storage.save(auth) -} - -/// Load CLI auth data using the configured credential store backend. -/// Returns `None` when no credentials are stored. This function is -/// provided only for tests. Production code should not directly load -/// from the auth.json storage. It should use the AuthManager abstraction -/// instead. -pub fn load_auth_dot_json( - codex_home: &Path, - auth_credentials_store_mode: AuthCredentialsStoreMode, -) -> std::io::Result> { - let storage = create_auth_storage(codex_home.to_path_buf(), auth_credentials_store_mode); - storage.load() -} - pub fn enforce_login_restrictions(config: &Config) -> std::io::Result<()> { let Some(auth) = load_auth( &config.codex_home, @@ -752,67 +671,6 @@ fn refresh_token_endpoint() -> String { .unwrap_or_else(|_| REFRESH_TOKEN_URL.to_string()) } -impl AuthDotJson { - fn from_external_tokens(external: &ExternalAuthTokens) -> std::io::Result { - let mut token_info = - parse_chatgpt_jwt_claims(&external.access_token).map_err(std::io::Error::other)?; - token_info.chatgpt_account_id = Some(external.chatgpt_account_id.clone()); - token_info.chatgpt_plan_type = external - .chatgpt_plan_type - .as_deref() - .map(InternalPlanType::from_raw_value) - .or(token_info.chatgpt_plan_type) - .or(Some(InternalPlanType::Unknown("unknown".to_string()))); - let tokens = TokenData { - id_token: token_info, - access_token: external.access_token.clone(), - refresh_token: String::new(), - account_id: Some(external.chatgpt_account_id.clone()), - }; - - Ok(Self { - auth_mode: Some(ApiAuthMode::ChatgptAuthTokens), - openai_api_key: None, - tokens: Some(tokens), - last_refresh: Some(Utc::now()), - }) - } - - fn from_external_access_token( - access_token: &str, - chatgpt_account_id: &str, - chatgpt_plan_type: Option<&str>, - ) -> std::io::Result { - let external = ExternalAuthTokens { - access_token: access_token.to_string(), - chatgpt_account_id: chatgpt_account_id.to_string(), - chatgpt_plan_type: chatgpt_plan_type.map(str::to_string), - }; - Self::from_external_tokens(&external) - } - - fn resolved_mode(&self) -> ApiAuthMode { - if let Some(mode) = self.auth_mode { - return mode; - } - if self.openai_api_key.is_some() { - return ApiAuthMode::ApiKey; - } - ApiAuthMode::Chatgpt - } - - fn storage_mode( - &self, - auth_credentials_store_mode: AuthCredentialsStoreMode, - ) -> AuthCredentialsStoreMode { - if self.resolved_mode() == ApiAuthMode::ChatgptAuthTokens { - AuthCredentialsStoreMode::Ephemeral - } else { - auth_credentials_store_mode - } - } -} - /// Internal cached auth state. #[derive(Clone)] struct CachedAuth { diff --git a/codex-rs/core/src/auth/storage.rs b/codex-rs/core/src/auth/storage.rs index b1e04b8685..a3b02c8a7c 100644 --- a/codex-rs/core/src/auth/storage.rs +++ b/codex-rs/core/src/auth/storage.rs @@ -1,336 +1,4 @@ -use chrono::DateTime; -use chrono::Utc; -use schemars::JsonSchema; -use serde::Deserialize; -use serde::Serialize; -use sha2::Digest; -use sha2::Sha256; -use std::collections::HashMap; -use std::fmt::Debug; -use std::fs::File; -use std::fs::OpenOptions; -use std::io::Read; -use std::io::Write; -#[cfg(unix)] -use std::os::unix::fs::OpenOptionsExt; -use std::path::Path; -use std::path::PathBuf; -use std::sync::Arc; -use std::sync::Mutex; -use tracing::warn; - -use crate::token_data::TokenData; -use codex_app_server_protocol::AuthMode; -use codex_keyring_store::DefaultKeyringStore; -use codex_keyring_store::KeyringStore; -use once_cell::sync::Lazy; - -/// Determine where Codex should store CLI auth credentials. -#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] -#[serde(rename_all = "lowercase")] -pub enum AuthCredentialsStoreMode { - #[default] - /// Persist credentials in CODEX_HOME/auth.json. - File, - /// Persist credentials in the keyring. Fail if unavailable. - Keyring, - /// Use keyring when available; otherwise, fall back to a file in CODEX_HOME. - Auto, - /// Store credentials in memory only for the current process. - Ephemeral, -} - -/// Expected structure for $CODEX_HOME/auth.json. -#[derive(Deserialize, Serialize, Clone, Debug, PartialEq)] -pub struct AuthDotJson { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub auth_mode: Option, - - #[serde(rename = "OPENAI_API_KEY")] - pub openai_api_key: Option, - - #[serde(default, skip_serializing_if = "Option::is_none")] - pub tokens: Option, - - #[serde(default, skip_serializing_if = "Option::is_none")] - pub last_refresh: Option>, -} - -pub(super) fn get_auth_file(codex_home: &Path) -> PathBuf { - codex_home.join("auth.json") -} - -pub(super) fn delete_file_if_exists(codex_home: &Path) -> std::io::Result { - let auth_file = get_auth_file(codex_home); - match std::fs::remove_file(&auth_file) { - Ok(()) => Ok(true), - Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(false), - Err(err) => Err(err), - } -} - -pub(super) trait AuthStorageBackend: Debug + Send + Sync { - fn load(&self) -> std::io::Result>; - fn save(&self, auth: &AuthDotJson) -> std::io::Result<()>; - fn delete(&self) -> std::io::Result; -} - -#[derive(Clone, Debug)] -pub(super) struct FileAuthStorage { - codex_home: PathBuf, -} - -impl FileAuthStorage { - pub(super) fn new(codex_home: PathBuf) -> Self { - Self { codex_home } - } - - /// Attempt to read and parse the `auth.json` file in the given `CODEX_HOME` directory. - /// Returns the full AuthDotJson structure. - pub(super) fn try_read_auth_json(&self, auth_file: &Path) -> std::io::Result { - let mut file = File::open(auth_file)?; - let mut contents = String::new(); - file.read_to_string(&mut contents)?; - let auth_dot_json: AuthDotJson = serde_json::from_str(&contents)?; - - Ok(auth_dot_json) - } -} - -impl AuthStorageBackend for FileAuthStorage { - fn load(&self) -> std::io::Result> { - let auth_file = get_auth_file(&self.codex_home); - let auth_dot_json = match self.try_read_auth_json(&auth_file) { - Ok(auth) => auth, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(err) => return Err(err), - }; - Ok(Some(auth_dot_json)) - } - - fn save(&self, auth_dot_json: &AuthDotJson) -> std::io::Result<()> { - let auth_file = get_auth_file(&self.codex_home); - - if let Some(parent) = auth_file.parent() { - std::fs::create_dir_all(parent)?; - } - let json_data = serde_json::to_string_pretty(auth_dot_json)?; - let mut options = OpenOptions::new(); - options.truncate(true).write(true).create(true); - #[cfg(unix)] - { - options.mode(0o600); - } - let mut file = options.open(auth_file)?; - file.write_all(json_data.as_bytes())?; - file.flush()?; - Ok(()) - } - - fn delete(&self) -> std::io::Result { - delete_file_if_exists(&self.codex_home) - } -} - -const KEYRING_SERVICE: &str = "Codex Auth"; - -// turns codex_home path into a stable, short key string -fn compute_store_key(codex_home: &Path) -> std::io::Result { - let canonical = codex_home - .canonicalize() - .unwrap_or_else(|_| codex_home.to_path_buf()); - let path_str = canonical.to_string_lossy(); - let mut hasher = Sha256::new(); - hasher.update(path_str.as_bytes()); - let digest = hasher.finalize(); - let hex = format!("{digest:x}"); - let truncated = hex.get(..16).unwrap_or(&hex); - Ok(format!("cli|{truncated}")) -} - -#[derive(Clone, Debug)] -struct KeyringAuthStorage { - codex_home: PathBuf, - keyring_store: Arc, -} - -impl KeyringAuthStorage { - fn new(codex_home: PathBuf, keyring_store: Arc) -> Self { - Self { - codex_home, - keyring_store, - } - } - - fn load_from_keyring(&self, key: &str) -> std::io::Result> { - match self.keyring_store.load(KEYRING_SERVICE, key) { - Ok(Some(serialized)) => serde_json::from_str(&serialized).map(Some).map_err(|err| { - std::io::Error::other(format!( - "failed to deserialize CLI auth from keyring: {err}" - )) - }), - Ok(None) => Ok(None), - Err(error) => Err(std::io::Error::other(format!( - "failed to load CLI auth from keyring: {}", - error.message() - ))), - } - } - - fn save_to_keyring(&self, key: &str, value: &str) -> std::io::Result<()> { - match self.keyring_store.save(KEYRING_SERVICE, key, value) { - Ok(()) => Ok(()), - Err(error) => { - let message = format!( - "failed to write OAuth tokens to keyring: {}", - error.message() - ); - warn!("{message}"); - Err(std::io::Error::other(message)) - } - } - } -} - -impl AuthStorageBackend for KeyringAuthStorage { - fn load(&self) -> std::io::Result> { - let key = compute_store_key(&self.codex_home)?; - self.load_from_keyring(&key) - } - - fn save(&self, auth: &AuthDotJson) -> std::io::Result<()> { - let key = compute_store_key(&self.codex_home)?; - // Simpler error mapping per style: prefer method reference over closure - let serialized = serde_json::to_string(auth).map_err(std::io::Error::other)?; - self.save_to_keyring(&key, &serialized)?; - if let Err(err) = delete_file_if_exists(&self.codex_home) { - warn!("failed to remove CLI auth fallback file: {err}"); - } - Ok(()) - } - - fn delete(&self) -> std::io::Result { - let key = compute_store_key(&self.codex_home)?; - let keyring_removed = self - .keyring_store - .delete(KEYRING_SERVICE, &key) - .map_err(|err| { - std::io::Error::other(format!("failed to delete auth from keyring: {err}")) - })?; - let file_removed = delete_file_if_exists(&self.codex_home)?; - Ok(keyring_removed || file_removed) - } -} - -#[derive(Clone, Debug)] -struct AutoAuthStorage { - keyring_storage: Arc, - file_storage: Arc, -} - -impl AutoAuthStorage { - fn new(codex_home: PathBuf, keyring_store: Arc) -> Self { - Self { - keyring_storage: Arc::new(KeyringAuthStorage::new(codex_home.clone(), keyring_store)), - file_storage: Arc::new(FileAuthStorage::new(codex_home)), - } - } -} - -impl AuthStorageBackend for AutoAuthStorage { - fn load(&self) -> std::io::Result> { - match self.keyring_storage.load() { - Ok(Some(auth)) => Ok(Some(auth)), - Ok(None) => self.file_storage.load(), - Err(err) => { - warn!("failed to load CLI auth from keyring, falling back to file storage: {err}"); - self.file_storage.load() - } - } - } - - fn save(&self, auth: &AuthDotJson) -> std::io::Result<()> { - match self.keyring_storage.save(auth) { - Ok(()) => Ok(()), - Err(err) => { - warn!("failed to save auth to keyring, falling back to file storage: {err}"); - self.file_storage.save(auth) - } - } - } - - fn delete(&self) -> std::io::Result { - // Keyring storage will delete from disk as well - self.keyring_storage.delete() - } -} - -// A global in-memory store for mapping codex_home -> AuthDotJson. -static EPHEMERAL_AUTH_STORE: Lazy>> = - Lazy::new(|| Mutex::new(HashMap::new())); - -#[derive(Clone, Debug)] -struct EphemeralAuthStorage { - codex_home: PathBuf, -} - -impl EphemeralAuthStorage { - fn new(codex_home: PathBuf) -> Self { - Self { codex_home } - } - - fn with_store(&self, action: F) -> std::io::Result - where - F: FnOnce(&mut HashMap, String) -> std::io::Result, - { - let key = compute_store_key(&self.codex_home)?; - let mut store = EPHEMERAL_AUTH_STORE - .lock() - .map_err(|_| std::io::Error::other("failed to lock ephemeral auth storage"))?; - action(&mut store, key) - } -} - -impl AuthStorageBackend for EphemeralAuthStorage { - fn load(&self) -> std::io::Result> { - self.with_store(|store, key| Ok(store.get(&key).cloned())) - } - - fn save(&self, auth: &AuthDotJson) -> std::io::Result<()> { - self.with_store(|store, key| { - store.insert(key, auth.clone()); - Ok(()) - }) - } - - fn delete(&self) -> std::io::Result { - self.with_store(|store, key| Ok(store.remove(&key).is_some())) - } -} - -pub(super) fn create_auth_storage( - codex_home: PathBuf, - mode: AuthCredentialsStoreMode, -) -> Arc { - let keyring_store: Arc = Arc::new(DefaultKeyringStore); - create_auth_storage_with_keyring_store(codex_home, mode, keyring_store) -} - -fn create_auth_storage_with_keyring_store( - codex_home: PathBuf, - mode: AuthCredentialsStoreMode, - keyring_store: Arc, -) -> Arc { - match mode { - AuthCredentialsStoreMode::File => Arc::new(FileAuthStorage::new(codex_home)), - AuthCredentialsStoreMode::Keyring => { - Arc::new(KeyringAuthStorage::new(codex_home, keyring_store)) - } - AuthCredentialsStoreMode::Auto => Arc::new(AutoAuthStorage::new(codex_home, keyring_store)), - AuthCredentialsStoreMode::Ephemeral => Arc::new(EphemeralAuthStorage::new(codex_home)), - } -} - -#[cfg(test)] -#[path = "storage_tests.rs"] -mod tests; +pub use codex_auth::AuthCredentialsStoreMode; +pub use codex_auth::AuthDotJson; +pub use codex_auth::AuthStorageBackend; +pub use codex_auth::create_auth_storage; diff --git a/codex-rs/core/src/auth_env_telemetry.rs b/codex-rs/core/src/auth_env_telemetry.rs index 85cd23fe06..c93e09d249 100644 --- a/codex-rs/core/src/auth_env_telemetry.rs +++ b/codex-rs/core/src/auth_env_telemetry.rs @@ -1,8 +1,5 @@ use codex_otel::AuthEnvTelemetryMetadata; -use crate::auth::CODEX_API_KEY_ENV_VAR; -use crate::auth::OPENAI_API_KEY_ENV_VAR; -use crate::auth::REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR; use crate::model_provider_info::ModelProviderInfo; #[derive(Debug, Clone, Default, PartialEq, Eq)] @@ -32,55 +29,17 @@ pub(crate) fn collect_auth_env_telemetry( provider: &ModelProviderInfo, codex_api_key_env_enabled: bool, ) -> AuthEnvTelemetry { - AuthEnvTelemetry { - openai_api_key_env_present: env_var_present(OPENAI_API_KEY_ENV_VAR), - codex_api_key_env_present: env_var_present(CODEX_API_KEY_ENV_VAR), + let telemetry = codex_auth::collect_auth_env_telemetry( + provider.env_key.is_some(), + provider.env_key.as_deref(), codex_api_key_env_enabled, - // Custom provider `env_key` is arbitrary config text, so emit only a safe bucket. - provider_env_key_name: provider.env_key.as_ref().map(|_| "configured".to_string()), - provider_env_key_present: provider.env_key.as_deref().map(env_var_present), - refresh_token_url_override_present: env_var_present(REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR), - } -} - -fn env_var_present(name: &str) -> bool { - match std::env::var(name) { - Ok(value) => !value.trim().is_empty(), - Err(std::env::VarError::NotUnicode(_)) => true, - Err(std::env::VarError::NotPresent) => false, - } -} - -#[cfg(test)] -mod tests { - use super::*; - use pretty_assertions::assert_eq; - - #[test] - fn collect_auth_env_telemetry_buckets_provider_env_key_name() { - let provider = ModelProviderInfo { - name: "Custom".to_string(), - base_url: None, - env_key: Some("sk-should-not-leak".to_string()), - env_key_instructions: None, - experimental_bearer_token: None, - wire_api: crate::model_provider_info::WireApi::Responses, - query_params: None, - http_headers: None, - env_http_headers: None, - request_max_retries: None, - stream_max_retries: None, - stream_idle_timeout_ms: None, - websocket_connect_timeout_ms: None, - requires_openai_auth: false, - supports_websockets: false, - }; - - let telemetry = collect_auth_env_telemetry(&provider, false); - - assert_eq!( - telemetry.provider_env_key_name, - Some("configured".to_string()) - ); + ); + AuthEnvTelemetry { + openai_api_key_env_present: telemetry.openai_api_key_env_present, + codex_api_key_env_present: telemetry.codex_api_key_env_present, + codex_api_key_env_enabled: telemetry.codex_api_key_env_enabled, + provider_env_key_name: telemetry.provider_env_key_name, + provider_env_key_present: telemetry.provider_env_key_present, + refresh_token_url_override_present: telemetry.refresh_token_url_override_present, } } diff --git a/codex-rs/core/src/token_data.rs b/codex-rs/core/src/token_data.rs index 5952d5940d..b194d0a2eb 100644 --- a/codex-rs/core/src/token_data.rs +++ b/codex-rs/core/src/token_data.rs @@ -1,178 +1,9 @@ -use base64::Engine; -use serde::Deserialize; -use serde::Serialize; -use thiserror::Error; - -#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Default)] -pub struct TokenData { - /// Flat info parsed from the JWT in auth.json. - #[serde( - deserialize_with = "deserialize_id_token", - serialize_with = "serialize_id_token" - )] - pub id_token: IdTokenInfo, - - /// This is a JWT. - pub access_token: String, - - pub refresh_token: String, - - pub account_id: Option, -} - -/// Flat subset of useful claims in id_token from auth.json. -#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] -pub struct IdTokenInfo { - pub email: Option, - /// The ChatGPT subscription plan type - /// (e.g., "free", "plus", "pro", "business", "enterprise", "edu"). - /// (Note: values may vary by backend.) - pub(crate) chatgpt_plan_type: Option, - /// ChatGPT user identifier associated with the token, if present. - pub chatgpt_user_id: Option, - /// Organization/workspace identifier associated with the token, if present. - pub chatgpt_account_id: Option, - pub raw_jwt: String, -} - -impl IdTokenInfo { - pub fn get_chatgpt_plan_type(&self) -> Option { - self.chatgpt_plan_type.as_ref().map(|t| match t { - PlanType::Known(plan) => format!("{plan:?}"), - PlanType::Unknown(s) => s.clone(), - }) - } - - pub fn is_workspace_account(&self) -> bool { - matches!( - self.chatgpt_plan_type, - Some(PlanType::Known( - KnownPlan::Team | KnownPlan::Business | KnownPlan::Enterprise | KnownPlan::Edu - )) - ) - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(untagged)] -pub(crate) enum PlanType { - Known(KnownPlan), - Unknown(String), -} - -impl PlanType { - pub(crate) fn from_raw_value(raw: &str) -> Self { - match raw.to_ascii_lowercase().as_str() { - "free" => Self::Known(KnownPlan::Free), - "go" => Self::Known(KnownPlan::Go), - "plus" => Self::Known(KnownPlan::Plus), - "pro" => Self::Known(KnownPlan::Pro), - "team" => Self::Known(KnownPlan::Team), - "business" => Self::Known(KnownPlan::Business), - "enterprise" => Self::Known(KnownPlan::Enterprise), - "education" | "edu" => Self::Known(KnownPlan::Edu), - _ => Self::Unknown(raw.to_string()), - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub(crate) enum KnownPlan { - Free, - Go, - Plus, - Pro, - Team, - Business, - Enterprise, - Edu, -} - -#[derive(Deserialize)] -struct IdClaims { - #[serde(default)] - email: Option, - #[serde(rename = "https://api.openai.com/profile", default)] - profile: Option, - #[serde(rename = "https://api.openai.com/auth", default)] - auth: Option, -} - -#[derive(Deserialize)] -struct ProfileClaims { - #[serde(default)] - email: Option, -} - -#[derive(Deserialize)] -struct AuthClaims { - #[serde(default)] - chatgpt_plan_type: Option, - #[serde(default)] - chatgpt_user_id: Option, - #[serde(default)] - user_id: Option, - #[serde(default)] - chatgpt_account_id: Option, -} - -#[derive(Debug, Error)] -pub enum IdTokenInfoError { - #[error("invalid ID token format")] - InvalidFormat, - #[error(transparent)] - Base64(#[from] base64::DecodeError), - #[error(transparent)] - Json(#[from] serde_json::Error), -} - -pub fn parse_chatgpt_jwt_claims(jwt: &str) -> Result { - // JWT format: header.payload.signature - let mut parts = jwt.split('.'); - let (_header_b64, payload_b64, _sig_b64) = match (parts.next(), parts.next(), parts.next()) { - (Some(h), Some(p), Some(s)) if !h.is_empty() && !p.is_empty() && !s.is_empty() => (h, p, s), - _ => return Err(IdTokenInfoError::InvalidFormat), - }; - - let payload_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(payload_b64)?; - let claims: IdClaims = serde_json::from_slice(&payload_bytes)?; - let email = claims - .email - .or_else(|| claims.profile.and_then(|profile| profile.email)); - - match claims.auth { - Some(auth) => Ok(IdTokenInfo { - email, - raw_jwt: jwt.to_string(), - chatgpt_plan_type: auth.chatgpt_plan_type, - chatgpt_user_id: auth.chatgpt_user_id.or(auth.user_id), - chatgpt_account_id: auth.chatgpt_account_id, - }), - None => Ok(IdTokenInfo { - email, - raw_jwt: jwt.to_string(), - chatgpt_plan_type: None, - chatgpt_user_id: None, - chatgpt_account_id: None, - }), - } -} - -fn deserialize_id_token<'de, D>(deserializer: D) -> Result -where - D: serde::Deserializer<'de>, -{ - let s = String::deserialize(deserializer)?; - parse_chatgpt_jwt_claims(&s).map_err(serde::de::Error::custom) -} - -fn serialize_id_token(id_token: &IdTokenInfo, serializer: S) -> Result -where - S: serde::Serializer, -{ - serializer.serialize_str(&id_token.raw_jwt) -} +pub use codex_auth::IdTokenInfo; +pub use codex_auth::IdTokenInfoError; +pub use codex_auth::KnownPlan; +pub use codex_auth::PlanType; +pub use codex_auth::TokenData; +pub use codex_auth::parse_chatgpt_jwt_claims; #[cfg(test)] #[path = "token_data_tests.rs"] diff --git a/codex-rs/login/Cargo.toml b/codex-rs/login/Cargo.toml index 5524fec7c1..93a3cd953e 100644 --- a/codex-rs/login/Cargo.toml +++ b/codex-rs/login/Cargo.toml @@ -11,6 +11,7 @@ workspace = true base64 = { workspace = true } chrono = { workspace = true, features = ["serde"] } codex-client = { workspace = true } +codex-auth = { workspace = true } codex-core = { workspace = true } codex-app-server-protocol = { workspace = true } rand = { workspace = true } diff --git a/codex-rs/login/src/lib.rs b/codex-rs/login/src/lib.rs index 60b0c57f28..fa40c7426e 100644 --- a/codex-rs/login/src/lib.rs +++ b/codex-rs/login/src/lib.rs @@ -2,6 +2,13 @@ mod device_code_auth; mod pkce; mod server; +pub use codex_auth::AuthDotJson; +pub use codex_auth::CODEX_API_KEY_ENV_VAR; +pub use codex_auth::OPENAI_API_KEY_ENV_VAR; +pub use codex_auth::TokenData; +pub use codex_auth::login_with_api_key; +pub use codex_auth::logout; +pub use codex_auth::save_auth; pub use codex_client::BuildCustomCaTransportError as BuildLoginHttpClientError; pub use device_code_auth::DeviceCode; pub use device_code_auth::complete_device_code_login; @@ -16,11 +23,4 @@ pub use server::run_login_server; pub use codex_app_server_protocol::AuthMode; pub use codex_core::AuthManager; pub use codex_core::CodexAuth; -pub use codex_core::auth::AuthDotJson; pub use codex_core::auth::CLIENT_ID; -pub use codex_core::auth::CODEX_API_KEY_ENV_VAR; -pub use codex_core::auth::OPENAI_API_KEY_ENV_VAR; -pub use codex_core::auth::login_with_api_key; -pub use codex_core::auth::logout; -pub use codex_core::auth::save_auth; -pub use codex_core::token_data::TokenData; diff --git a/codex-rs/login/src/server.rs b/codex-rs/login/src/server.rs index a51e038dc1..513bb2ebc5 100644 --- a/codex-rs/login/src/server.rs +++ b/codex-rs/login/src/server.rs @@ -28,13 +28,13 @@ use crate::pkce::generate_pkce; use base64::Engine; use chrono::Utc; use codex_app_server_protocol::AuthMode; +use codex_auth::AuthCredentialsStoreMode; +use codex_auth::AuthDotJson; +use codex_auth::TokenData; +use codex_auth::parse_chatgpt_jwt_claims; +use codex_auth::save_auth; use codex_client::build_reqwest_client_with_custom_ca; -use codex_core::auth::AuthCredentialsStoreMode; -use codex_core::auth::AuthDotJson; -use codex_core::auth::save_auth; use codex_core::default_client::originator; -use codex_core::token_data::TokenData; -use codex_core::token_data::parse_chatgpt_jwt_claims; use rand::RngCore; use serde_json::Value as JsonValue; use tiny_http::Header;