Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Avoid blocking EMA auth status checks on account refresh (#56127)

jifc260087efe8c
diff --git a/codex-rs/codex-mcp/src/mcp/auth.rs b/codex-rs/codex-mcp/src/mcp/auth.rs
index 4abc7c7d5b..d193f1e608 100644
--- a/codex-rs/codex-mcp/src/mcp/auth.rs
+++ b/codex-rs/codex-mcp/src/mcp/auth.rs
@@ -8,6 +8,7 @@ use codex_config::McpServerTransportConfig;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_exec_server::HttpClient;
+use codex_login::AccountOAuthGrant;
use codex_login::CodexAuth;
use codex_rmcp_client::McpAuthState;
use codex_rmcp_client::McpLoginRequirement;
@@ -21,6 +22,7 @@ use codex_rmcp_client::discover_streamable_http_oauth;
use codex_rmcp_client::resolve_mcp_oauth_callback_url;
use futures::FutureExt;
use futures::future::join_all;
+use tokio::sync::OnceCell;
use tracing::warn;
use crate::runtime::McpRuntimeContext;
@@ -207,7 +209,10 @@ pub async fn compute_auth_statuses<'a, I>(
where
I: IntoIterator<Item = (&'a String, &'a EffectiveMcpServer)>,
{
+ // Share successful, missing, and failed reads without starting storage work for non-EMA servers.
+ let account_grant = OnceCell::new();
let futures = servers.into_iter().map(|(name, server)| {
+ let account_grant = &account_grant;
let name = name.clone();
let redirect_mode = if server.is_agent_plugin() {
StreamableHttpRedirectMode::AgentPluginV1
@@ -224,6 +229,7 @@ where
keyring_backend_kind,
auth,
auth_manager,
+ account_grant,
ema_state,
&runtime_context,
redirect_mode,
@@ -255,6 +261,7 @@ async fn compute_auth_status(
keyring_backend_kind: AuthKeyringBackendKind,
auth: Option<&CodexAuth>,
auth_manager: Option<&std::sync::Arc<codex_login::AuthManager>>,
+ account_grant: &OnceCell<std::io::Result<Option<AccountOAuthGrant>>>,
ema_state: &crate::EmaState,
runtime_context: &McpRuntimeContext,
redirect_mode: StreamableHttpRedirectMode,
@@ -280,10 +287,15 @@ async fn compute_auth_status(
return Ok(McpAuthState::LoggedOut(McpLoginRequirement::Login));
}
let account_usable = match auth_manager {
- Some(manager) => match manager.lease_account_oauth_grant().await? {
- Some(lease) => {
- crate::ema_account::account_grant_is_usable(lease.tokens(), registration.idp())
- && !ema_state.requires_sign_in(registration, lease.tokens())
+ Some(manager) => match account_grant
+ .get_or_init(|| manager.account_oauth_grant())
+ .await
+ .as_ref()
+ .map_err(|error| anyhow::anyhow!("{error}"))?
+ {
+ Some(grant) => {
+ crate::ema_account::account_grant_is_usable(grant.tokens(), registration.idp())
+ && !ema_state.requires_sign_in(registration, grant.tokens())
}
None => false,
},
diff --git a/codex-rs/codex-mcp/src/mcp/mod_tests.rs b/codex-rs/codex-mcp/src/mcp/mod_tests.rs
index acd97b9e4a..cb52fe4585 100644
--- a/codex-rs/codex-mcp/src/mcp/mod_tests.rs
+++ b/codex-rs/codex-mcp/src/mcp/mod_tests.rs
@@ -5,9 +5,13 @@ use crate::connection_manager::tests::create_ready_async_managed_client;
use crate::mcp::auth::McpAuthStatusEntry;
use crate::rmcp_client::StartupOutcomeError;
use crate::server::McpCredentialPolicy;
+use anyhow::Context;
use codex_config::Constrained;
use codex_config::types::AppToolApproval;
use codex_config::types::AuthKeyringBackendKind;
+use codex_exec_server_test_support::environment_manager_without_environments;
+use codex_login::AuthCredentialsStoreMode;
+use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_plugin::AppConnectorId;
use codex_plugin::PluginCapabilitySummary;
@@ -23,6 +27,100 @@ use std::collections::HashMap;
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;
+use std::time::Duration;
+
+#[tokio::test]
+async fn ema_auth_statuses_do_not_wait_for_account_refresh() -> anyhow::Result<()> {
+ let home = tempfile::tempdir()?;
+ // Account ID token for user/workspace, issued by idp.example to account-client.
+ let id_token = concat!(
+ "eyJhbGciOiJFUzI1NiJ9.",
+ "eyJpc3MiOiJodHRwczovL2lkcC5leGFtcGxlIiwic3ViIjoidXNlciIsImF1ZCI6ImFjY291bnQt",
+ "Y2xpZW50IiwiZXhwIjoxLCJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF91",
+ "c2VyX2lkIjoidXNlciIsImNoYXRncHRfYWNjb3VudF9pZCI6IndvcmtzcGFjZSJ9fQ",
+ ".signature",
+ );
+ std::fs::write(
+ home.path().join("auth.json"),
+ serde_json::to_vec(&serde_json::json!({
+ "auth_mode": "chatgpt",
+ "tokens": {
+ "id_token": id_token,
+ "access_token": "account-access",
+ "refresh_token": "account-refresh",
+ "account_id": "workspace",
+ "login_owner_id": "completed-login",
+ "oauth_provenance": {
+ "issuer": "https://idp.example",
+ "client_id": "account-client"
+ }
+ },
+ "last_refresh": "2099-01-01T00:00:00Z"
+ }))?,
+ )?;
+ let manager = AuthManager::shared(
+ home.path().to_path_buf(),
+ /*enable_codex_api_key_env*/ false,
+ AuthCredentialsStoreMode::File,
+ /*forced_chatgpt_workspace_id*/ None,
+ /*chatgpt_base_url*/ None,
+ AuthKeyringBackendKind::default(),
+ codex_login::test_support::transport_default_auth_route_config(),
+ )
+ .await;
+ let auth = manager.auth_cached().context("account auth")?;
+ let lease = manager
+ .lease_account_oauth_grant()
+ .await?
+ .context("account grant")?;
+ let mut servers = HashMap::new();
+ for name in ["first", "second"] {
+ let mut server: McpServerConfig = serde_json::from_value(serde_json::json!({
+ "url": format!("https://resource.example/{name}"),
+ "auth": "ema_auth"
+ }))?;
+ server
+ .resolve_ema_registration(&codex_config::McpServerIdpOAuthConfig {
+ issuer: "https://idp.example".into(),
+ client_id: "enterprise-client".into(),
+ })
+ .map_err(anyhow::Error::msg)?;
+ servers.insert(
+ name.to_string(),
+ EffectiveMcpServer::from_host_config(server),
+ );
+ }
+ let runtime_context = McpRuntimeContext::new(
+ Arc::new(environment_manager_without_environments()),
+ home.path().to_path_buf(),
+ );
+ let statuses = tokio::time::timeout(
+ Duration::from_secs(5),
+ compute_auth_statuses(
+ servers.iter(),
+ OAuthCredentialsStoreMode::File,
+ AuthKeyringBackendKind::default(),
+ Some(&auth),
+ Some(&manager),
+ &crate::EmaState::default(),
+ &runtime_context,
+ ),
+ )
+ .await
+ .context("MCP auth status waited for the held account lease")?;
+ assert_eq!(
+ statuses
+ .into_iter()
+ .map(|(name, entry)| (name, entry.auth_state))
+ .collect::<HashMap<_, _>>(),
+ HashMap::from([
+ ("first".to_string(), McpAuthState::BearerToken),
+ ("second".to_string(), McpAuthState::BearerToken),
+ ]),
+ );
+ drop(lease);
+ Ok(())
+}
#[tokio::test]
async fn status_snapshot_only_downgrades_oauth_and_ema_authentication_failures() {
diff --git a/codex-rs/login/src/auth/manager.rs b/codex-rs/login/src/auth/manager.rs
index ff60c13865..a496ee35d3 100644
--- a/codex-rs/login/src/auth/manager.rs
+++ b/codex-rs/login/src/auth/manager.rs
@@ -2573,6 +2573,17 @@ impl AuthManager {
.acquire_owned()
.await
.map_err(|_| std::io::Error::other("Account refresh coordination is unavailable."))?;
+ Ok(self
+ .account_oauth_grant()
+ .await?
+ .map(|grant| AccountOAuthGrantLease { grant, permit }))
+ }
+
+ /// Reads an owner-checked grant without waiting for or excluding account refresh.
+ /// Use this for inspection; lease the grant again before exchanging its refresh token.
+ pub async fn account_oauth_grant(
+ self: &Arc<Self>,
+ ) -> std::io::Result<Option<AccountOAuthGrant>> {
let login_generation = self.auth_change_state_tx.borrow().login_generation;
let Some(tokens) = self.read_account_grant_tokens().await? else {
return Ok(None);
@@ -2585,7 +2596,7 @@ impl AuthManager {
if !grant.owner_is_current() {
return Ok(None);
}
- Ok(Some(AccountOAuthGrantLease { grant, permit }))
+ Ok(Some(grant))
}
/// Checks the persisted account owner without requiring an EMA-eligible account grant.
diff --git a/codex-rs/login/tests/suite/auth_refresh.rs b/codex-rs/login/tests/suite/auth_refresh.rs
index 0ccd7d4ca1..42662f405f 100644
--- a/codex-rs/login/tests/suite/auth_refresh.rs
+++ b/codex-rs/login/tests/suite/auth_refresh.rs
@@ -281,6 +281,14 @@ async fn account_grant_tracks_refresh_replacement_and_logout() -> Result<()> {
.unwrap_or_default()
.is_empty()
);
+ // Inspection must complete even with an IdP lease held and a refresh queued.
+ // Unlike inspection, the exchange above must still exclude refresh.
+ let inspected = ctx
+ .auth_manager
+ .account_oauth_grant()
+ .await?
+ .context("account inspection during refresh exclusion")?;
+ assert_eq!(inspected.tokens(), &initial_tokens);
// No await between clearing the flag and release: this wake must come from the lease.
refresh_wake.0.store(false, Ordering::SeqCst);
let grant = lease.release();
@@ -385,6 +393,7 @@ async fn account_grant_tracks_refresh_replacement_and_logout() -> Result<()> {
AuthKeyringBackendKind::default(),
)?;
assert!(grant.current_tokens().await?.is_none());
+ assert!(ctx.auth_manager.account_oauth_grant().await?.is_none());
assert!(
!ctx.auth_manager
.account_login_is_current(&cached_auth)