From fd36ea04e24626e891a78c9c5ee0e535798a715b Mon Sep 17 00:00:00 2001 From: Dhruv Date: Mon, 1 Jun 2026 22:30:21 +0530 Subject: [PATCH] Isolate saved account session storage --- codex-rs/login/src/auth/manager.rs | 80 +++-- codex-rs/login/src/auth/mod.rs | 2 +- codex-rs/login/src/auth/revoke.rs | 4 +- codex-rs/login/src/auth/storage.rs | 162 ++-------- .../login/src/auth/storage/account_session.rs | 285 ++++++++++++++++++ codex-rs/login/src/lib.rs | 2 +- 6 files changed, 355 insertions(+), 180 deletions(-) create mode 100644 codex-rs/login/src/auth/storage/account_session.rs diff --git a/codex-rs/login/src/auth/manager.rs b/codex-rs/login/src/auth/manager.rs index 6ea81da491..a6478f9aab 100644 --- a/codex-rs/login/src/auth/manager.rs +++ b/codex-rs/login/src/auth/manager.rs @@ -199,51 +199,11 @@ impl From for std::io::Error { } impl CodexAuth { - pub(crate) async fn from_auth_dot_json( + async fn from_auth_dot_json( codex_home: &Path, auth_dot_json: AuthDotJson, auth_credentials_store_mode: AuthCredentialsStoreMode, chatgpt_base_url: Option<&str>, - ) -> std::io::Result { - Self::from_auth_dot_json_with_chatgpt_storage( - codex_home, - auth_dot_json, - auth_credentials_store_mode, - chatgpt_base_url, - /*chatgpt_storage*/ None, - ) - .await - } - - pub async fn from_account_session_auth_dot_json( - codex_home: &Path, - session_id: &str, - auth_dot_json: AuthDotJson, - auth_credentials_store_mode: AuthCredentialsStoreMode, - chatgpt_base_url: Option<&str>, - ) -> std::io::Result { - let storage_mode = auth_dot_json.storage_mode(auth_credentials_store_mode); - let storage = create_account_session_auth_storage( - codex_home.to_path_buf(), - session_id, - storage_mode, - )?; - Self::from_auth_dot_json_with_chatgpt_storage( - codex_home, - auth_dot_json, - auth_credentials_store_mode, - chatgpt_base_url, - Some(storage), - ) - .await - } - - async fn from_auth_dot_json_with_chatgpt_storage( - codex_home: &Path, - auth_dot_json: AuthDotJson, - auth_credentials_store_mode: AuthCredentialsStoreMode, - chatgpt_base_url: Option<&str>, - chatgpt_storage: Option>, ) -> std::io::Result { let auth_mode = auth_dot_json.resolved_mode(); let client = create_client(); @@ -270,8 +230,7 @@ impl CodexAuth { match auth_mode { ApiAuthMode::Chatgpt => { - let storage = chatgpt_storage - .unwrap_or_else(|| create_auth_storage(codex_home.to_path_buf(), storage_mode)); + let storage = create_auth_storage(codex_home.to_path_buf(), storage_mode); Ok(Self::Chatgpt(ChatgptAuth { state, storage })) } ApiAuthMode::ChatgptAuthTokens => { @@ -282,6 +241,31 @@ impl CodexAuth { } } + pub async fn from_account_session_auth_dot_json( + codex_home: &Path, + session_id: &str, + auth_dot_json: AuthDotJson, + auth_credentials_store_mode: AuthCredentialsStoreMode, + chatgpt_base_url: Option<&str>, + ) -> std::io::Result { + let storage_mode = auth_dot_json.storage_mode(auth_credentials_store_mode); + let mut auth = Self::from_auth_dot_json( + codex_home, + auth_dot_json, + auth_credentials_store_mode, + chatgpt_base_url, + ) + .await?; + if let Self::Chatgpt(chatgpt_auth) = &mut auth { + chatgpt_auth.storage = create_account_session_auth_storage( + codex_home.to_path_buf(), + session_id, + storage_mode, + )?; + } + Ok(auth) + } + pub async fn from_auth_storage( codex_home: &Path, auth_credentials_store_mode: AuthCredentialsStoreMode, @@ -678,6 +662,16 @@ pub fn load_account_session_auth( storage.load() } +/// Revoke a saved account session without changing the active auth payload. +pub async fn revoke_account_session_auth( + codex_home: &Path, + session_id: &str, + auth_credentials_store_mode: AuthCredentialsStoreMode, +) -> std::io::Result<()> { + let auth = load_account_session_auth(codex_home, session_id, auth_credentials_store_mode)?; + revoke_auth_tokens(auth.as_ref()).await +} + /// Delete a saved account session without changing the active auth payload. pub fn delete_account_session_auth( codex_home: &Path, diff --git a/codex-rs/login/src/auth/mod.rs b/codex-rs/login/src/auth/mod.rs index 96ee6fd4a0..167ccd3f75 100644 --- a/codex-rs/login/src/auth/mod.rs +++ b/codex-rs/login/src/auth/mod.rs @@ -11,5 +11,5 @@ mod revoke; pub use error::RefreshTokenFailedError; pub use error::RefreshTokenFailedReason; pub use manager::*; -pub use revoke::revoke_auth_tokens; +pub(crate) use revoke::revoke_auth_tokens; pub(crate) use revoke::should_revoke_auth_tokens; diff --git a/codex-rs/login/src/auth/revoke.rs b/codex-rs/login/src/auth/revoke.rs index e696ea9e1d..b6a9fef4bb 100644 --- a/codex-rs/login/src/auth/revoke.rs +++ b/codex-rs/login/src/auth/revoke.rs @@ -52,7 +52,9 @@ struct RevokeTokenRequest<'a> { client_id: Option<&'static str>, } -pub async fn revoke_auth_tokens(auth_dot_json: Option<&AuthDotJson>) -> Result<(), std::io::Error> { +pub(crate) async fn revoke_auth_tokens( + auth_dot_json: Option<&AuthDotJson>, +) -> Result<(), std::io::Error> { let Some((token, kind)) = auth_dot_json.and_then(revocable_token) else { return Ok(()); }; diff --git a/codex-rs/login/src/auth/storage.rs b/codex-rs/login/src/auth/storage.rs index 6ec2b5cb39..16470c4536 100644 --- a/codex-rs/login/src/auth/storage.rs +++ b/codex-rs/login/src/auth/storage.rs @@ -12,7 +12,6 @@ use std::io::Read; use std::io::Write; #[cfg(unix)] use std::os::unix::fs::OpenOptionsExt; -use std::path::Component; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; @@ -29,6 +28,10 @@ use codex_keyring_store::KeyringStore; use codex_protocol::account::PlanType as AccountPlanType; use once_cell::sync::Lazy; +mod account_session; + +pub(super) use account_session::create_account_session_auth_storage; + /// Expected structure for $CODEX_HOME/auth.json. #[derive(Deserialize, Serialize, Clone, Debug, PartialEq)] pub struct AuthDotJson { @@ -86,14 +89,9 @@ pub(super) fn get_auth_file(codex_home: &Path) -> PathBuf { codex_home.join("auth.json") } -fn get_account_session_auth_file(codex_home: &Path, session_id: &str) -> PathBuf { - codex_home - .join("account-sessions") - .join(format!("{session_id}.json")) -} - -fn delete_file_if_exists(path: &Path) -> std::io::Result { - match std::fs::remove_file(path) { +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), @@ -108,20 +106,12 @@ pub(super) trait AuthStorageBackend: Debug + Send + Sync { #[derive(Clone, Debug)] pub(super) struct FileAuthStorage { - auth_file: PathBuf, + codex_home: PathBuf, } impl FileAuthStorage { pub(super) fn new(codex_home: PathBuf) -> Self { - Self { - auth_file: get_auth_file(&codex_home), - } - } - - fn for_account_session(codex_home: PathBuf, session_id: &str) -> Self { - Self { - auth_file: get_account_session_auth_file(&codex_home, session_id), - } + Self { codex_home } } /// Attempt to read and parse the `auth.json` file in the given `CODEX_HOME` directory. @@ -138,7 +128,8 @@ impl FileAuthStorage { impl AuthStorageBackend for FileAuthStorage { fn load(&self) -> std::io::Result> { - let auth_dot_json = match self.try_read_auth_json(&self.auth_file) { + 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), @@ -147,7 +138,9 @@ impl AuthStorageBackend for FileAuthStorage { } fn save(&self, auth_dot_json: &AuthDotJson) -> std::io::Result<()> { - if let Some(parent) = self.auth_file.parent() { + 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)?; @@ -157,14 +150,14 @@ impl AuthStorageBackend for FileAuthStorage { { options.mode(0o600); } - let mut file = options.open(&self.auth_file)?; + 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.auth_file) + delete_file_if_exists(&self.codex_home) } } @@ -184,54 +177,20 @@ fn compute_store_key(codex_home: &Path) -> std::io::Result { Ok(format!("cli|{truncated}")) } -fn compute_account_session_store_key( - codex_home: &Path, - session_id: &str, -) -> std::io::Result { - Ok(format!( - "{}|account-session|{session_id}", - compute_store_key(codex_home)? - )) -} - #[derive(Clone, Debug)] struct KeyringAuthStorage { - auth_file: PathBuf, codex_home: PathBuf, - account_session_id: Option, keyring_store: Arc, } impl KeyringAuthStorage { fn new(codex_home: PathBuf, keyring_store: Arc) -> Self { Self { - auth_file: get_auth_file(&codex_home), codex_home, - account_session_id: None, keyring_store, } } - fn for_account_session( - codex_home: PathBuf, - session_id: &str, - keyring_store: Arc, - ) -> Self { - Self { - auth_file: get_account_session_auth_file(&codex_home, session_id), - codex_home, - account_session_id: Some(session_id.to_string()), - keyring_store, - } - } - - fn store_key(&self) -> std::io::Result { - match self.account_session_id.as_deref() { - Some(session_id) => compute_account_session_store_key(&self.codex_home, session_id), - None => compute_store_key(&self.codex_home), - } - } - 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| { @@ -264,28 +223,30 @@ impl KeyringAuthStorage { impl AuthStorageBackend for KeyringAuthStorage { fn load(&self) -> std::io::Result> { - self.load_from_keyring(&self.store_key()?) + 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(&self.store_key()?, &serialized)?; - if let Err(err) = delete_file_if_exists(&self.auth_file) { + 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 store_key = self.store_key()?; + let key = compute_store_key(&self.codex_home)?; let keyring_removed = self .keyring_store - .delete(KEYRING_SERVICE, &store_key) + .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.auth_file); - Ok(keyring_removed? || file_removed?) + })?; + let file_removed = delete_file_if_exists(&self.codex_home)?; + Ok(keyring_removed || file_removed) } } @@ -302,21 +263,6 @@ impl AutoAuthStorage { file_storage: Arc::new(FileAuthStorage::new(codex_home)), } } - - fn for_account_session( - codex_home: PathBuf, - session_id: &str, - keyring_store: Arc, - ) -> Self { - Self { - keyring_storage: Arc::new(KeyringAuthStorage::for_account_session( - codex_home.clone(), - session_id, - keyring_store, - )), - file_storage: Arc::new(FileAuthStorage::for_account_session(codex_home, session_id)), - } - } } impl AuthStorageBackend for AutoAuthStorage { @@ -354,32 +300,18 @@ static EPHEMERAL_AUTH_STORE: Lazy>> = #[derive(Clone, Debug)] struct EphemeralAuthStorage { codex_home: PathBuf, - account_session_id: Option, } impl EphemeralAuthStorage { fn new(codex_home: PathBuf) -> Self { - Self { - codex_home, - account_session_id: None, - } - } - - fn for_account_session(codex_home: PathBuf, session_id: &str) -> Self { - Self { - codex_home, - account_session_id: Some(session_id.to_string()), - } + Self { codex_home } } fn with_store(&self, action: F) -> std::io::Result where F: FnOnce(&mut HashMap, String) -> std::io::Result, { - let key = match self.account_session_id.as_deref() { - Some(session_id) => compute_account_session_store_key(&self.codex_home, session_id)?, - None => compute_store_key(&self.codex_home)?, - }; + 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"))?; @@ -412,44 +344,6 @@ pub(super) fn create_auth_storage( create_auth_storage_with_keyring_store(codex_home, mode, keyring_store) } -pub(super) fn create_account_session_auth_storage( - codex_home: PathBuf, - session_id: &str, - mode: AuthCredentialsStoreMode, -) -> std::io::Result> { - validate_account_session_id(session_id)?; - let keyring_store: Arc = Arc::new(DefaultKeyringStore); - Ok(match mode { - AuthCredentialsStoreMode::File => { - Arc::new(FileAuthStorage::for_account_session(codex_home, session_id)) - } - AuthCredentialsStoreMode::Keyring => Arc::new(KeyringAuthStorage::for_account_session( - codex_home, - session_id, - keyring_store, - )), - AuthCredentialsStoreMode::Auto => Arc::new(AutoAuthStorage::for_account_session( - codex_home, - session_id, - keyring_store, - )), - AuthCredentialsStoreMode::Ephemeral => Arc::new(EphemeralAuthStorage::for_account_session( - codex_home, session_id, - )), - }) -} - -fn validate_account_session_id(session_id: &str) -> std::io::Result<()> { - let mut components = Path::new(session_id).components(); - if matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none() { - return Ok(()); - } - Err(std::io::Error::new( - std::io::ErrorKind::InvalidInput, - "account session ID must be a single path component", - )) -} - fn create_auth_storage_with_keyring_store( codex_home: PathBuf, mode: AuthCredentialsStoreMode, diff --git a/codex-rs/login/src/auth/storage/account_session.rs b/codex-rs/login/src/auth/storage/account_session.rs new file mode 100644 index 0000000000..c124fbbce9 --- /dev/null +++ b/codex-rs/login/src/auth/storage/account_session.rs @@ -0,0 +1,285 @@ +use super::AuthDotJson; +use super::AuthStorageBackend; +use super::EPHEMERAL_AUTH_STORE; +use super::KEYRING_SERVICE; +use super::compute_store_key; +use codex_config::types::AuthCredentialsStoreMode; +use codex_keyring_store::DefaultKeyringStore; +use codex_keyring_store::KeyringStore; +use std::collections::HashMap; +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::Component; +use std::path::Path; +use std::path::PathBuf; +use std::sync::Arc; +use tracing::warn; + +pub(in crate::auth) fn create_account_session_auth_storage( + codex_home: PathBuf, + session_id: &str, + mode: AuthCredentialsStoreMode, +) -> std::io::Result> { + validate_session_id(session_id)?; + let keyring_store: Arc = Arc::new(DefaultKeyringStore); + Ok(match mode { + AuthCredentialsStoreMode::File => Arc::new(FileAuthStorage::new(&codex_home, session_id)), + AuthCredentialsStoreMode::Keyring => Arc::new(KeyringAuthStorage::new( + &codex_home, + session_id, + keyring_store, + )?), + AuthCredentialsStoreMode::Auto => Arc::new(AutoAuthStorage::new( + &codex_home, + session_id, + keyring_store, + )?), + AuthCredentialsStoreMode::Ephemeral => { + Arc::new(EphemeralAuthStorage::new(&codex_home, session_id)?) + } + }) +} + +fn validate_session_id(session_id: &str) -> std::io::Result<()> { + let mut components = Path::new(session_id).components(); + if matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none() { + return Ok(()); + } + Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "account session ID must be a single path component", + )) +} + +fn auth_file(codex_home: &Path, session_id: &str) -> PathBuf { + codex_home + .join("account-sessions") + .join(format!("{session_id}.json")) +} + +fn store_key(codex_home: &Path, session_id: &str) -> std::io::Result { + Ok(format!( + "{}|account-session|{session_id}", + compute_store_key(codex_home)? + )) +} + +fn delete_file_if_exists(path: &Path) -> std::io::Result { + match std::fs::remove_file(path) { + Ok(()) => Ok(true), + Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(err) => Err(err), + } +} + +#[derive(Clone, Debug)] +struct FileAuthStorage { + auth_file: PathBuf, +} + +impl FileAuthStorage { + fn new(codex_home: &Path, session_id: &str) -> Self { + Self { + auth_file: auth_file(codex_home, session_id), + } + } +} + +impl AuthStorageBackend for FileAuthStorage { + fn load(&self) -> std::io::Result> { + let mut file = match File::open(&self.auth_file) { + Ok(file) => file, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(err) => return Err(err), + }; + let mut contents = String::new(); + file.read_to_string(&mut contents)?; + serde_json::from_str(&contents) + .map(Some) + .map_err(Into::into) + } + + fn save(&self, auth: &AuthDotJson) -> std::io::Result<()> { + if let Some(parent) = self.auth_file.parent() { + std::fs::create_dir_all(parent)?; + } + let mut options = OpenOptions::new(); + options.truncate(true).write(true).create(true); + #[cfg(unix)] + { + options.mode(0o600); + } + let mut file = options.open(&self.auth_file)?; + file.write_all(serde_json::to_string_pretty(auth)?.as_bytes())?; + file.flush() + } + + fn delete(&self) -> std::io::Result { + delete_file_if_exists(&self.auth_file) + } +} + +#[derive(Clone, Debug)] +struct KeyringAuthStorage { + auth_file: PathBuf, + store_key: String, + keyring_store: Arc, +} + +impl KeyringAuthStorage { + fn new( + codex_home: &Path, + session_id: &str, + keyring_store: Arc, + ) -> std::io::Result { + Ok(Self { + auth_file: auth_file(codex_home, session_id), + store_key: store_key(codex_home, session_id)?, + keyring_store, + }) + } +} + +impl AuthStorageBackend for KeyringAuthStorage { + fn load(&self) -> std::io::Result> { + match self.keyring_store.load(KEYRING_SERVICE, &self.store_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(&self, auth: &AuthDotJson) -> std::io::Result<()> { + let serialized = serde_json::to_string(auth).map_err(std::io::Error::other)?; + match self + .keyring_store + .save(KEYRING_SERVICE, &self.store_key, &serialized) + { + Ok(()) => {} + Err(error) => { + let message = format!( + "failed to write OAuth tokens to keyring: {}", + error.message() + ); + warn!("{message}"); + return Err(std::io::Error::other(message)); + } + } + if let Err(err) = delete_file_if_exists(&self.auth_file) { + warn!("failed to remove CLI auth fallback file: {err}"); + } + Ok(()) + } + + fn delete(&self) -> std::io::Result { + let keyring_removed = self + .keyring_store + .delete(KEYRING_SERVICE, &self.store_key) + .map_err(|err| { + std::io::Error::other(format!("failed to delete auth from keyring: {err}")) + }); + let file_removed = delete_file_if_exists(&self.auth_file); + Ok(keyring_removed? || file_removed?) + } +} + +#[derive(Clone, Debug)] +struct AutoAuthStorage { + keyring_storage: Arc, + file_storage: Arc, +} + +impl AutoAuthStorage { + fn new( + codex_home: &Path, + session_id: &str, + keyring_store: Arc, + ) -> std::io::Result { + Ok(Self { + keyring_storage: Arc::new(KeyringAuthStorage::new( + codex_home, + session_id, + keyring_store, + )?), + file_storage: Arc::new(FileAuthStorage::new(codex_home, session_id)), + }) + } +} + +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() + } +} + +#[derive(Clone, Debug)] +struct EphemeralAuthStorage { + store_key: String, +} + +impl EphemeralAuthStorage { + fn new(codex_home: &Path, session_id: &str) -> std::io::Result { + Ok(Self { + store_key: store_key(codex_home, session_id)?, + }) + } + + fn with_store(&self, action: F) -> std::io::Result + where + F: FnOnce(&mut HashMap, String) -> std::io::Result, + { + let mut store = EPHEMERAL_AUTH_STORE + .lock() + .map_err(|_| std::io::Error::other("failed to lock ephemeral auth storage"))?; + action(&mut store, self.store_key.clone()) + } +} + +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())) + } +} diff --git a/codex-rs/login/src/lib.rs b/codex-rs/login/src/lib.rs index 61061cdf9c..e61180ffd0 100644 --- a/codex-rs/login/src/lib.rs +++ b/codex-rs/login/src/lib.rs @@ -46,7 +46,7 @@ pub use auth::logout; pub use auth::logout_with_revoke; pub use auth::read_codex_access_token_from_env; pub use auth::read_openai_api_key_from_env; -pub use auth::revoke_auth_tokens; +pub use auth::revoke_account_session_auth; pub use auth::save_account_session_auth; pub use auth::save_auth; pub use auth_env_telemetry::AuthEnvTelemetry;