Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions codex-rs/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions codex-rs/rmcp-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ codex-api = { workspace = true }
codex-config = { workspace = true }
codex-exec-server = { workspace = true }
codex-keyring-store = { workspace = true }
codex-otel = { workspace = true }
codex-protocol = { workspace = true }
codex-secrets = { workspace = true }
codex-utils-path = { workspace = true }
codex-utils-path-uri = { workspace = true }
codex-utils-pty = { workspace = true }
codex-utils-home-dir = { workspace = true }
Expand Down
111 changes: 86 additions & 25 deletions codex-rs/rmcp-client/src/oauth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@

mod persistor;
mod refresh_lock;
mod resolution_state;
mod resolved_store;
mod store_lock;

use anyhow::Context;
use anyhow::Error;
Expand Down Expand Up @@ -53,6 +55,11 @@ use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use tracing::warn;

use self::resolution_state::StoreResolutionReason;
use self::resolution_state::record_store_resolution;
use self::store_lock::OAuthStore;
use self::store_lock::OAuthStoreLock;

use codex_keyring_store::DefaultKeyringStore;
use codex_keyring_store::KeyringStore;
use codex_utils_home_dir::find_codex_home;
Expand Down Expand Up @@ -194,6 +201,7 @@ fn load_oauth_tokens_from_secrets_keyring<K: KeyringStore + Clone + 'static>(
server_name: &str,
url: &str,
) -> Result<Option<StoredOAuthTokens>> {
let _store_lock = OAuthStoreLock::acquire(OAuthStore::Secrets)?;
let codex_home = find_codex_home()?;
let manager = SecretsManager::new_with_keyring_store_and_namespace(
codex_home.to_path_buf(),
Expand Down Expand Up @@ -276,21 +284,53 @@ fn save_oauth_tokens_with_keyring_store<K: KeyringStore + Clone + 'static>(
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
) -> Result<()> {
match store_mode {
OAuthCredentialsStoreMode::Auto => save_oauth_tokens_with_keyring_with_fallback_to_file(
keyring_store,
keyring_backend_kind,
server_name,
tokens,
),
OAuthCredentialsStoreMode::File => save_oauth_tokens_to_file(tokens),
OAuthCredentialsStoreMode::Keyring => save_oauth_tokens_with_keyring_and_cleanup_file(
keyring_store,
keyring_backend_kind,
server_name,
tokens,
),
}
let (resolved_store, reason) = match store_mode {
OAuthCredentialsStoreMode::Auto => {
let resolved_store = save_oauth_tokens_with_keyring_with_fallback_to_file(
keyring_store,
keyring_backend_kind,
server_name,
tokens,
)?;
let reason = match resolved_store {
ResolvedOAuthCredentialStore::File => {
StoreResolutionReason::AutoSaveToFileAfterKeyringError
}
ResolvedOAuthCredentialStore::Keyring(_) => {
StoreResolutionReason::AutoSaveToKeyring
}
};
(resolved_store, reason)
}
OAuthCredentialsStoreMode::File => {
save_oauth_tokens_to_file(tokens)?;
(
ResolvedOAuthCredentialStore::File,
StoreResolutionReason::ConfiguredSave,
)
}
OAuthCredentialsStoreMode::Keyring => {
save_oauth_tokens_with_keyring_and_cleanup_file(
keyring_store,
keyring_backend_kind,
server_name,
tokens,
)?;
(
ResolvedOAuthCredentialStore::Keyring(keyring_backend_kind),
StoreResolutionReason::ConfiguredSave,
)
}
};
record_store_resolution(
server_name,
&tokens.url,
store_mode,
keyring_backend_kind,
resolved_store,
reason,
);
Ok(())
}

fn save_oauth_tokens_with_keyring<K: KeyringStore + Clone + 'static>(
Expand Down Expand Up @@ -319,6 +359,8 @@ fn save_oauth_tokens_with_keyring_and_cleanup_file<K: KeyringStore + Clone + 'st
server_name: &str,
tokens: &StoredOAuthTokens,
) -> Result<()> {
// Cross-store cleanup belongs to login-time store selection. Refresh persistence calls the
// raw keyring writer above so a client pinned to keyring never mutates fallback File state.
save_oauth_tokens_with_keyring(keyring_store, keyring_backend_kind, server_name, tokens)?;
let key = compute_store_key(server_name, &tokens.url)?;
if let Err(error) = delete_oauth_tokens_from_file(&key) {
Expand Down Expand Up @@ -354,6 +396,16 @@ fn save_oauth_tokens_to_secrets_keyring<K: KeyringStore + Clone + 'static>(
tokens: &StoredOAuthTokens,
) -> Result<()> {
let serialized = serde_json::to_string(tokens).context("failed to serialize OAuth tokens")?;
let _store_lock = OAuthStoreLock::acquire(OAuthStore::Secrets)?;
save_oauth_tokens_to_secrets_keyring_unlocked(keyring_store, server_name, tokens, &serialized)
}

fn save_oauth_tokens_to_secrets_keyring_unlocked<K: KeyringStore + Clone + 'static>(
keyring_store: &K,
server_name: &str,
tokens: &StoredOAuthTokens,
serialized: &str,
) -> Result<()> {
let codex_home = find_codex_home()?;
let manager = SecretsManager::new_with_keyring_store_and_namespace(
codex_home.to_path_buf(),
Expand All @@ -363,7 +415,7 @@ fn save_oauth_tokens_to_secrets_keyring<K: KeyringStore + Clone + 'static>(
);
let secret_name = compute_secret_name(server_name, &tokens.url)?;
manager
.set(&SecretScope::Global, &secret_name, &serialized)
.set(&SecretScope::Global, &secret_name, serialized)
.context("failed to write OAuth tokens to encrypted storage")
}

Expand All @@ -372,19 +424,20 @@ fn save_oauth_tokens_with_keyring_with_fallback_to_file<K: KeyringStore + Clone
keyring_backend_kind: AuthKeyringBackendKind,
server_name: &str,
tokens: &StoredOAuthTokens,
) -> Result<()> {
) -> Result<ResolvedOAuthCredentialStore> {
match save_oauth_tokens_with_keyring_and_cleanup_file(
keyring_store,
keyring_backend_kind,
server_name,
tokens,
) {
Ok(()) => Ok(()),
Ok(()) => Ok(ResolvedOAuthCredentialStore::Keyring(keyring_backend_kind)),
Err(error) => {
let message = error.to_string();
warn!("falling back to file storage for OAuth tokens: {message}");
save_oauth_tokens_to_file(tokens)
.with_context(|| format!("failed to write OAuth tokens to keyring: {message}"))
.with_context(|| format!("failed to write OAuth tokens to keyring: {message}"))?;
Ok(ResolvedOAuthCredentialStore::File)
}
}
}
Expand Down Expand Up @@ -505,6 +558,7 @@ fn delete_oauth_tokens_from_secrets_keyring<K: KeyringStore + Clone + 'static>(
server_name: &str,
url: &str,
) -> Result<bool> {
let _store_lock = OAuthStoreLock::acquire(OAuthStore::Secrets)?;
let codex_home = find_codex_home()?;
let manager = SecretsManager::new_with_keyring_store_and_namespace(
codex_home.to_path_buf(),
Expand Down Expand Up @@ -539,7 +593,8 @@ struct FallbackTokenEntry {
}

fn load_oauth_tokens_from_file(server_name: &str, url: &str) -> Result<Option<StoredOAuthTokens>> {
let Some(store) = read_fallback_file()? else {
let _store_lock = OAuthStoreLock::acquire(OAuthStore::File)?;
let Some(store) = read_fallback_file_unlocked()? else {
return Ok(None);
};

Expand Down Expand Up @@ -582,8 +637,13 @@ fn load_oauth_tokens_from_file(server_name: &str, url: &str) -> Result<Option<St
}

fn save_oauth_tokens_to_file(tokens: &StoredOAuthTokens) -> Result<()> {
let _store_lock = OAuthStoreLock::acquire(OAuthStore::File)?;
save_oauth_tokens_to_file_unlocked(tokens)
}

fn save_oauth_tokens_to_file_unlocked(tokens: &StoredOAuthTokens) -> Result<()> {
let key = compute_store_key(&tokens.server_name, &tokens.url)?;
let mut store = read_fallback_file()?.unwrap_or_default();
let mut store = read_fallback_file_unlocked()?.unwrap_or_default();

let token_response = &tokens.token_response.0;
let expires_at = tokens
Expand Down Expand Up @@ -611,7 +671,8 @@ fn save_oauth_tokens_to_file(tokens: &StoredOAuthTokens) -> Result<()> {
}

fn delete_oauth_tokens_from_file(key: &str) -> Result<bool> {
let mut store = match read_fallback_file()? {
let _store_lock = OAuthStoreLock::acquire(OAuthStore::File)?;
let mut store = match read_fallback_file_unlocked()? {
Some(store) => store,
None => return Ok(false),
};
Expand Down Expand Up @@ -697,7 +758,7 @@ fn fallback_file_path() -> Result<PathBuf> {
Ok(find_codex_home()?.join(FALLBACK_FILENAME).to_path_buf())
}

fn read_fallback_file() -> Result<Option<FallbackFile>> {
fn read_fallback_file_unlocked() -> Result<Option<FallbackFile>> {
let path = fallback_file_path()?;
let contents = match fs::read_to_string(&path) {
Ok(contents) => contents,
Expand Down Expand Up @@ -913,7 +974,7 @@ mod tests {

let fallback_path = super::fallback_file_path()?;
assert!(fallback_path.exists(), "fallback file should be created");
let saved = super::read_fallback_file()?.expect("fallback file should load");
let saved = super::read_fallback_file_unlocked()?.expect("fallback file should load");
let key = super::compute_store_key(&tokens.server_name, &tokens.url)?;
let entry = saved.get(&key).expect("entry for key");
assert_eq!(entry.server_name, tokens.server_name);
Expand Down Expand Up @@ -1025,7 +1086,7 @@ mod tests {
&tokens,
)?;

let saved = super::read_fallback_file()?.expect("fallback file should load");
let saved = super::read_fallback_file_unlocked()?.expect("fallback file should load");
let key = super::compute_store_key(&tokens.server_name, &tokens.url)?;
assert!(saved.contains_key(&key));
Ok(())
Expand Down
Loading
Loading