Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Recheck account login ownership for enterprise MCP (#55680)

jif2623f206bd40
diff --git a/codex-rs/app-server/src/request_processors/account_processor/enterprise_login.rs b/codex-rs/app-server/src/request_processors/account_processor/enterprise_login.rs
index 6837fc4467..18a7621d70 100644
--- a/codex-rs/app-server/src/request_processors/account_processor/enterprise_login.rs
+++ b/codex-rs/app-server/src/request_processors/account_processor/enterprise_login.rs
@@ -191,6 +191,26 @@ impl EnterpriseLoginState {
};
self.clear(&login_id).await;
}
+ let login_generation = self
+ .auth_manager
+ .auth_change_state_receiver()
+ .borrow()
+ .login_generation;
+ let account = self
+ .auth_manager
+ .auth_cached()
+ .filter(|auth| ema_auth_scope(Some(auth)).as_ref() == Some(&scope))
+ .ok_or_else(|| internal_error("Codex account changed during enterprise sign-in"))?;
+ if !self
+ .auth_manager
+ .account_login_is_current(&account)
+ .await
+ .unwrap_or(false)
+ {
+ return Err(internal_error(
+ "Codex account changed during enterprise sign-in",
+ ));
+ }
let keyring_backend = request.keyring_backend_kind;
// Keep commit cancellation under `active`; cancelling the setup epoch must
// not race an already-admitted synchronous credential write.
@@ -230,11 +250,12 @@ impl EnterpriseLoginState {
callback_closed.clone().await;
let mut active = credentials.commit_if(|| async {
lifecycle.auth_manager.reload().await;
- let eligible = lifecycle.configuration_is_current(&target, keyring_backend).await;
+ let eligible = lifecycle.auth_manager.account_login_is_current(&account).await.unwrap_or(false)
+ && lifecycle.configuration_is_current(&target, keyring_backend).await;
// Reread persisted account authority after acquiring the credential
// lock, including changes made by another app-server process.
lifecycle.auth_manager.reload().await;
- if !eligible {
+ if !eligible || !lifecycle.auth_manager.account_login_is_current(&account).await.unwrap_or(false) {
return None;
}
// Keep cancellation responsive during the async checks above.
@@ -243,6 +264,7 @@ impl EnterpriseLoginState {
let current = active.as_ref().is_some_and(|attempt| {
attempt.login_id == completion_id && !attempt.cancel.is_cancelled()
})
+ && lifecycle.auth_manager.auth_change_state_receiver().borrow().login_generation == login_generation
&& ema_auth_scope(lifecycle.auth_manager.auth_cached().as_ref()).as_ref() == Some(&scope);
if !current {
return None;
diff --git a/codex-rs/app-server/tests/common/auth_fixtures.rs b/codex-rs/app-server/tests/common/auth_fixtures.rs
index ac519a00ce..825745e1df 100644
--- a/codex-rs/app-server/tests/common/auth_fixtures.rs
+++ b/codex-rs/app-server/tests/common/auth_fixtures.rs
@@ -40,6 +40,7 @@ pub async fn mount_workspace_routing(server: &wiremock::MockServer) {
pub struct ChatGptAuthFixture {
access_token: String,
refresh_token: String,
+ login_owner_id: Option<String>,
account_id: Option<String>,
claims: ChatGptIdTokenClaims,
last_refresh: Option<Option<DateTime<Utc>>>,
@@ -50,6 +51,7 @@ impl ChatGptAuthFixture {
Self {
access_token: access_token.into(),
refresh_token: "refresh-token".to_string(),
+ login_owner_id: None,
account_id: None,
claims: ChatGptIdTokenClaims::default(),
last_refresh: None,
@@ -61,6 +63,11 @@ impl ChatGptAuthFixture {
self
}
+ pub fn login_owner_id(mut self, login_owner_id: impl Into<String>) -> Self {
+ self.login_owner_id = Some(login_owner_id.into());
+ self
+ }
+
pub fn account_id(mut self, account_id: impl Into<String>) -> Self {
self.account_id = Some(account_id.into());
self
@@ -179,7 +186,7 @@ pub fn write_chatgpt_auth(
access_token: fixture.access_token,
refresh_token: fixture.refresh_token,
oauth_provenance: None,
- login_owner_id: None,
+ login_owner_id: fixture.login_owner_id,
account_id: fixture.account_id,
};
diff --git a/codex-rs/app-server/tests/suite/v2/account_enterprise_tests.rs b/codex-rs/app-server/tests/suite/v2/account_enterprise_tests.rs
index 912a64845b..01dd50b903 100644
--- a/codex-rs/app-server/tests/suite/v2/account_enterprise_tests.rs
+++ b/codex-rs/app-server/tests/suite/v2/account_enterprise_tests.rs
@@ -204,7 +204,9 @@ async fn enterprise_login_attempt_lifecycle() -> Result<()> {
return Ok(());
}
- keyring::set_default_credential_builder(Box::<TestKeyring>::default());
+ let keyring = TestKeyring::default();
+ let account_read = Arc::clone(&keyring.account_read);
+ keyring::set_default_credential_builder(Box::new(keyring));
let server = MockServer::builder().start().await;
let idp_server = MockServer::start().await;
let origin = server.uri();
@@ -394,20 +396,22 @@ oauth = {{ client_id = "mcp-client", authorization_server_issuer = "{origin}/as"
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new("account-access")
+ .login_owner_id("original-account-login")
.account_id(WORKSPACE_ID_INITIAL)
.chatgpt_user_id("enterprise-user")
.plan_type("business"),
AuthCredentialsStoreMode::File,
)?;
let loader_overrides = LoaderOverrides::without_managed_config_for_tests();
- let config = Arc::new(
- ConfigBuilder::default()
- .codex_home(home.path().to_path_buf())
- .fallback_cwd(Some(home.path().to_path_buf()))
- .loader_overrides(loader_overrides.clone())
- .build()
- .await?,
- );
+ let mut config = ConfigBuilder::default()
+ .codex_home(home.path().to_path_buf())
+ .fallback_cwd(Some(home.path().to_path_buf()))
+ .loader_overrides(loader_overrides.clone())
+ .build()
+ .await?;
+ // Development builds otherwise force file storage, bypassing the mock keyring.
+ config.cli_auth_credentials_store_mode = AuthCredentialsStoreMode::Auto;
+ let config = Arc::new(config);
let mut client = in_process::start(InProcessStartArgs {
arg0_paths: Arg0DispatchPaths::default(),
config,
@@ -511,6 +515,7 @@ oauth = {{ client_id = "mcp-client", authorization_server_issuer = "{origin}/as"
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new("account-access")
+ .login_owner_id("original-account-login")
.account_id(WORKSPACE_ID_REFRESHED)
.chatgpt_user_id("enterprise-user")
.plan_type("business"),
@@ -737,6 +742,66 @@ oauth = {{ client_id = "mcp-client", authorization_server_issuer = "{origin}/as"
ordinary_result
);
+ // A same-account login replacement refuses EMA without adopting the new owner.
+ let auth_path = home.path().join("auth.json");
+ let saved_auth = std::fs::read_to_string(&auth_path)?;
+ let mut replaced_auth: Value = serde_json::from_str(&saved_auth)?;
+ replaced_auth["tokens"]["login_owner_id"] = json!("replacement-account-login");
+ std::fs::write(&auth_path, serde_json::to_string(&replaced_auth)?)?;
+ let refused = enterprise_rpc(&client, "thread/start", json!({})).await?;
+ let refused_call = |server: &str| {
+ json!({
+ "threadId": refused["thread"]["id"], "server": server,
+ "tool": "calendar_list_events", "arguments": {"query": "hello"},
+ })
+ };
+ assert!(
+ enterprise_rpc(&client, "mcpServer/tool/call", refused_call("enterprise"))
+ .await
+ .is_err()
+ );
+ assert_eq!(
+ enterprise_rpc(&client, "mcpServer/tool/call", refused_call("ordinary")).await?,
+ ordinary_result
+ );
+ assert_eq!(
+ resource_exchanges.load(std::sync::atomic::Ordering::SeqCst),
+ 2
+ );
+ std::fs::write(&auth_path, saved_auth)?;
+
+ // An EMA account read stays inside that server's startup, leaving ordinary MCP usable.
+ let (arrived, read_started) = tokio::sync::oneshot::channel();
+ let (release, read_release) = std::sync::mpsc::channel();
+ *account_read.lock().unwrap() = Some((arrived, read_release));
+ let startup = async {
+ let thread = enterprise_rpc(&client, "thread/start", json!({})).await?;
+ read_started.await?;
+ let result = enterprise_rpc(
+ &client,
+ "mcpServer/tool/call",
+ json!({
+ "threadId": thread["thread"]["id"], "server": "ordinary",
+ "tool": "calendar_list_events", "arguments": {"query":"hello"},
+ }),
+ )
+ .await?;
+ enterprise_rpc(
+ &client,
+ "thread/archive",
+ json!({"threadId": thread["thread"]["id"]}),
+ )
+ .await?;
+ anyhow::Ok(result)
+ };
+ let result = timeout(DEFAULT_READ_TIMEOUT, startup).await;
+ // Release even on failure so the blocking worker cannot hang child shutdown.
+ let _ = release.send(());
+ assert_eq!(
+ result.context("account read blocked ordinary MCP")??,
+ ordinary_result
+ );
+
let stalled = enterprise_rpc(
&client,
"mcpServer/oauth/login",
@@ -892,16 +957,36 @@ async fn enterprise_completion(client: &mut InProcessClientHandle) -> Result<Val
.context("timed out waiting for enterprise login completion")?
}
+type AccountReadGate = Arc<
+ Mutex<
+ Option<(
+ tokio::sync::oneshot::Sender<()>,
+ std::sync::mpsc::Receiver<()>,
+ )>,
+ >,
+>;
+
#[derive(Default)]
-struct TestKeyring(Mutex<HashMap<(String, String), Arc<MockCredential>>>);
+struct TestKeyring {
+ credentials: Mutex<HashMap<(String, String), Arc<MockCredential>>>,
+ account_read: AccountReadGate,
+}
-struct TestCredential(Arc<MockCredential>);
+struct TestCredential(Arc<MockCredential>, Option<AccountReadGate>);
impl CredentialApi for TestCredential {
fn set_secret(&self, secret: &[u8]) -> keyring::Result<()> {
self.0.set_secret(secret)
}
fn get_secret(&self) -> keyring::Result<Vec<u8>> {
+ let pending = self
+ .1
+ .as_ref()
+ .and_then(|gate| gate.lock().expect("account read gate").take());
+ if let Some((arrived, release)) = pending {
+ let _ = arrived.send(());
+ let _ = release.recv();
+ }
self.0.get_secret()
}
fn delete_credential(&self) -> keyring::Result<()> {
@@ -920,13 +1005,16 @@ impl CredentialBuilderApi for TestKeyring {
user: &str,
) -> keyring::Result<Box<Credential>> {
let credential = self
- .0
+ .credentials
.lock()
.expect("mock keyring")
.entry((service.into(), user.into()))
.or_default()
.clone();
- Ok(Box::new(TestCredential(credential)))
+ Ok(Box::new(TestCredential(
+ credential,
+ (service == "Codex Auth").then(|| Arc::clone(&self.account_read)),
+ )))
}
fn as_any(&self) -> &dyn Any {
self
@@ -1058,6 +1146,7 @@ oauth = {{ client_id = "mcp-client", authorization_server_issuer = "{origin}/as"
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new("account-access")
+ .login_owner_id("original-account-login")
.account_id(WORKSPACE_ID_INITIAL)
.chatgpt_user_id("enterprise-user")
.plan_type("business"),
diff --git a/codex-rs/codex-mcp/src/ema_auth.rs b/codex-rs/codex-mcp/src/ema_auth.rs
index 5caa12b50f..3039c7d25b 100644
--- a/codex-rs/codex-mcp/src/ema_auth.rs
+++ b/codex-rs/codex-mcp/src/ema_auth.rs
@@ -60,6 +60,8 @@ pub fn ema_auth_scope(auth: Option<&CodexAuth>) -> Option<McpEmaAuthScope> {
pub(crate) struct EmaAuth {
scope: McpEmaAuthScope,
config: Arc<McpConfig>,
+ manager: Arc<AuthManager>,
+ account: CodexAuth,
authority: EmaRequestAuthority,
_revocation: AbortOnDropHandle<()>,
}
@@ -116,11 +118,25 @@ impl EmaAuth {
Ok(Arc::new(Self {
scope,
config,
+ manager: Arc::clone(manager),
+ account: auth
+ .context("enterprise MCP requires an account owner")?
+ .clone(),
authority,
_revocation: AbortOnDropHandle::new(revocation),
}))
}
+ pub(crate) async fn check_account(&self) -> Result<()> {
+ self.authority.check()?;
+ if !self.manager.account_login_is_current(&self.account).await? {
+ self.authority.revoke();
+ bail!(EmaAuthFailure::ReauthenticationRequired);
+ }
+ self.authority.check()?;
+ Ok(())
+ }
+
pub(crate) async fn connect(
self: &Arc<Self>,
server_name: &str,
@@ -128,7 +144,7 @@ impl EmaAuth {
http_client: Arc<dyn HttpClient>,
protocol_mode: McpProtocolMode,
) -> Result<RmcpClient> {
- self.authority.check()?;
+ self.check_account().await?;
let config = server.config();
config
.validate_ema_auth_transport()
@@ -283,7 +299,7 @@ impl EmaTokenSource for EnterpriseTokenSource {
}
async fn access_token(&self) -> Result<EmaAccessToken> {
- self.auth.authority.check()?;
+ self.auth.check_account().await?;
let idp = self.registration.idp();
let exchange = exchange_ema_auth_token(EmaAuthTokenExchangeRequest {
server_url: self.registration.server_url(),
@@ -294,7 +310,7 @@ impl EmaTokenSource for EnterpriseTokenSource {
idp_issuer: &idp.issuer,
idp_client_id: &idp.client_id,
idp_identity: Box::pin(async {
- self.auth.authority.check()?;
+ self.auth.check_account().await?;
resolve_ema_idp_identity(EmaIdpIdentityRequest {
issuer: &idp.issuer,
client_id: &idp.client_id,
@@ -314,11 +330,11 @@ impl EmaTokenSource for EnterpriseTokenSource {
}
result = exchange => result,
};
- self.auth.authority.check()?;
+ self.auth.check_account().await?;
match result {
Ok((token, _credentials)) => {
self.credentials.acquire_current_ema_credentials().await?;
- self.auth.authority.check()?;
+ self.auth.check_account().await?;
Ok(token)
}
Err(error) => {
diff --git a/codex-rs/login/src/auth/account_grant.rs b/codex-rs/login/src/auth/account_grant.rs
index 0b0faf9dd8..217828f052 100644
--- a/codex-rs/login/src/auth/account_grant.rs
+++ b/codex-rs/login/src/auth/account_grant.rs
@@ -51,6 +51,15 @@ impl AccountOAuthGrantLease {
}
impl AccountOAuthGrant {
+ pub fn tokens(&self) -> &TokenData {
+ &self.tokens
+ }
+
+ /// Compare credential revisions without exposing the refresh token to state holders.
+ pub fn same_credential(&self, other: &Self) -> bool {
+ self.tokens == other.tokens
+ }
+
pub(super) fn owner_is_current(&self) -> bool {
let Ok(cached) = self.manager.inner.read() else {
return false;
@@ -71,11 +80,7 @@ impl AccountOAuthGrant {
return Ok(false);
}
let stored = self.manager.read_account_grant_tokens().await?;
- Ok(self.owner_is_current()
- && stored.as_ref().is_some_and(|tokens| {
- same_account_grant(&self.tokens, tokens)
- && self.tokens.refresh_token == tokens.refresh_token
- }))
+ Ok(self.owner_is_current() && stored.as_ref().is_some_and(|tokens| self.tokens == *tokens))
}
}
diff --git a/codex-rs/login/src/auth/manager.rs b/codex-rs/login/src/auth/manager.rs
index 4ce0329d99..f8a5d76036 100644
--- a/codex-rs/login/src/auth/manager.rs
+++ b/codex-rs/login/src/auth/manager.rs
@@ -2587,26 +2587,43 @@ impl AuthManager {
Ok(Some(AccountOAuthGrantLease { grant, permit }))
}
- async fn read_account_grant_tokens(&self) -> std::io::Result<Option<TokenData>> {
- if self.has_external_auth()
- || self.auth_credentials_store_mode == AuthCredentialsStoreMode::Ephemeral
+ /// Checks the persisted account owner without requiring an EMA-eligible account grant.
+ /// Dedicated enterprise credentials still belong to this account login.
+ pub async fn account_login_is_current(&self, expected: &CodexAuth) -> std::io::Result<bool> {
+ if !matches!(expected, CodexAuth::Chatgpt(_)) {
+ return Ok(self.auth_cached().is_some_and(|current| {
+ !matches!(current, CodexAuth::Chatgpt(_))
+ && current.get_account_id() == expected.get_account_id()
+ && current.get_chatgpt_user_id() == expected.get_chatgpt_user_id()
+ }));
+ }
+ let expected = expected.get_token_data()?;
+ if expected
+ .login_owner_id
+ .as_ref()
+ .is_none_or(String::is_empty)
{
- return Ok(None);
- }
- let Some(auth @ CodexAuth::Chatgpt(_)) = self.auth_cached() else {
- return Ok(None);
+ return Ok(false);
+ }
+ let matches_owner = || {
+ self.auth_cached().is_some_and(|auth| {
+ matches!(auth, CodexAuth::Chatgpt(_))
+ && auth
+ .get_token_data()
+ .is_ok_and(|tokens| account_grant::same_account_login(&expected, &tokens))
+ })
};
- let allowed = self.allowed_login_methods();
- if validate_auth_restrictions(
- Some(&allowed),
- self.effective_chatgpt_workspaces().as_deref(),
- &auth,
- )
- .is_err()
- {
- return Ok(None);
+ if !matches_owner() {
+ return Ok(false);
}
- let cached = auth.get_token_data()?;
+ let stored = self.read_persisted_account_tokens().await?;
+ Ok(matches_owner()
+ && stored
+ .as_ref()
+ .is_some_and(|tokens| account_grant::same_account_login(&expected, tokens)))
+ }
+
+ async fn read_persisted_account_tokens(&self) -> std::io::Result<Option<TokenData>> {
let home = self.codex_home.clone();
let mode = self.auth_credentials_store_mode;
let backend = self.keyring_backend_kind;
@@ -2622,10 +2639,33 @@ impl AuthManager {
.map_err(|_: std::io::Error| {
std::io::Error::other("Account credential storage is unavailable.")
})?;
- let Some(stored) = stored.filter(|auth| auth.resolved_mode() == AuthMode::Chatgpt) else {
+ Ok(stored
+ .filter(|auth| auth.resolved_mode() == AuthMode::Chatgpt)
+ .and_then(|auth| auth.tokens))
+ }
+
+ async fn read_account_grant_tokens(&self) -> std::io::Result<Option<TokenData>> {
+ if self.has_external_auth()
+ || self.auth_credentials_store_mode == AuthCredentialsStoreMode::Ephemeral
+ {
+ return Ok(None);
+ }
+ let Some(auth @ CodexAuth::Chatgpt(_)) = self.auth_cached() else {
return Ok(None);
};
- Ok(stored.tokens.filter(|tokens| {
+ let allowed = self.allowed_login_methods();
+ if validate_auth_restrictions(
+ Some(&allowed),
+ self.effective_chatgpt_workspaces().as_deref(),
+ &auth,
+ )
+ .is_err()
+ {
+ return Ok(None);
+ }
+ let cached = auth.get_token_data()?;
+ let stored = self.read_persisted_account_tokens().await?;
+ Ok(stored.filter(|tokens| {
tokens.oauth_provenance.as_ref().is_some_and(|provenance| {
!provenance.issuer.trim().is_empty() && !provenance.client_id.trim().is_empty()
}) && tokens
diff --git a/codex-rs/login/tests/suite/auth_refresh.rs b/codex-rs/login/tests/suite/auth_refresh.rs
index 1dd40d3b73..303ac14c58 100644
--- a/codex-rs/login/tests/suite/auth_refresh.rs
+++ b/codex-rs/login/tests/suite/auth_refresh.rs
@@ -359,7 +359,28 @@ async fn account_grant_tracks_refresh_replacement_and_logout() -> Result<()> {
AuthKeyringBackendKind::default(),
)?;
assert!(!grant.check_current().await?);
+ assert!(
+ !ctx.auth_manager
+ .account_login_is_current(&cached_auth)
+ .await?
+ );
+ assert_eq!(
+ ctx.auth_manager
+ .auth_cached()
+ .context("original cached auth")?
+ .get_token_data()?,
+ cached,
+ );
ctx.auth_manager.reload().await;
+ assert!(
+ ctx.auth_manager
+ .account_login_is_current(
+ &ctx.auth_manager
+ .auth_cached()
+ .context("replacement cached")?
+ )
+ .await?
+ );
let after = *changes.borrow();
assert_eq!(after.owner_generation, before.owner_generation + 1);
assert_eq!(after.login_generation, before.login_generation + 1);