Isolate saved account session storage

This commit is contained in:
Dhruv
2026-06-02 01:41:20 +05:30
parent 62190604cf
commit fd36ea04e2
6 changed files with 355 additions and 180 deletions
+37 -43
View File
@@ -199,51 +199,11 @@ impl From<RefreshTokenError> 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> {
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<Self> {
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<Arc<dyn AuthStorageBackend>>,
) -> std::io::Result<Self> {
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<Self> {
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,
+1 -1
View File
@@ -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;
+3 -1
View File
@@ -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(());
};
+28 -134
View File
@@ -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<bool> {
match std::fs::remove_file(path) {
pub(super) fn delete_file_if_exists(codex_home: &Path) -> std::io::Result<bool> {
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<Option<AuthDotJson>> {
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<bool> {
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<String> {
Ok(format!("cli|{truncated}"))
}
fn compute_account_session_store_key(
codex_home: &Path,
session_id: &str,
) -> std::io::Result<String> {
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<String>,
keyring_store: Arc<dyn KeyringStore>,
}
impl KeyringAuthStorage {
fn new(codex_home: PathBuf, keyring_store: Arc<dyn KeyringStore>) -> 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<dyn KeyringStore>,
) -> 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<String> {
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<Option<AuthDotJson>> {
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<Option<AuthDotJson>> {
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<bool> {
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<dyn KeyringStore>,
) -> 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<Mutex<HashMap<String, AuthDotJson>>> =
#[derive(Clone, Debug)]
struct EphemeralAuthStorage {
codex_home: PathBuf,
account_session_id: Option<String>,
}
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<F, T>(&self, action: F) -> std::io::Result<T>
where
F: FnOnce(&mut HashMap<String, AuthDotJson>, String) -> std::io::Result<T>,
{
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<Arc<dyn AuthStorageBackend>> {
validate_account_session_id(session_id)?;
let keyring_store: Arc<dyn KeyringStore> = 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,
@@ -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<Arc<dyn AuthStorageBackend>> {
validate_session_id(session_id)?;
let keyring_store: Arc<dyn KeyringStore> = 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<String> {
Ok(format!(
"{}|account-session|{session_id}",
compute_store_key(codex_home)?
))
}
fn delete_file_if_exists(path: &Path) -> std::io::Result<bool> {
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<Option<AuthDotJson>> {
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<bool> {
delete_file_if_exists(&self.auth_file)
}
}
#[derive(Clone, Debug)]
struct KeyringAuthStorage {
auth_file: PathBuf,
store_key: String,
keyring_store: Arc<dyn KeyringStore>,
}
impl KeyringAuthStorage {
fn new(
codex_home: &Path,
session_id: &str,
keyring_store: Arc<dyn KeyringStore>,
) -> std::io::Result<Self> {
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<Option<AuthDotJson>> {
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<bool> {
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<KeyringAuthStorage>,
file_storage: Arc<FileAuthStorage>,
}
impl AutoAuthStorage {
fn new(
codex_home: &Path,
session_id: &str,
keyring_store: Arc<dyn KeyringStore>,
) -> std::io::Result<Self> {
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<Option<AuthDotJson>> {
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<bool> {
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<Self> {
Ok(Self {
store_key: store_key(codex_home, session_id)?,
})
}
fn with_store<F, T>(&self, action: F) -> std::io::Result<T>
where
F: FnOnce(&mut HashMap<String, AuthDotJson>, String) -> std::io::Result<T>,
{
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<Option<AuthDotJson>> {
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<bool> {
self.with_store(|store, key| Ok(store.remove(&key).is_some()))
}
}
+1 -1
View File
@@ -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;