Enable enterprise MCP sign-in and account-scoped grant cleanup (#49276)

## Why

The app server previously rejected OAuth login for enterprise-managed MCP servers. These servers need an explicit sign-in flow that ties saved authorization to the active Codex user and workspace and prevents canceled or superseded attempts from saving credentials.

## What changed

- Enable enterprise sign-in through `mcpServer/oauth/login` for configured servers with a connected thread, trusted IdP registration, and `features.use_xaa` enabled. Scope shared enterprise credentials by user, workspace, issuer, and client ID.
- Add `loginId` to MCP OAuth login responses and completion notifications, preserving compatibility with older servers that omit it.
- Support enterprise login replacement and `account/login/cancel`, wait for callback listener shutdown before replacement, and recheck account and configuration before saving grants. Fence stale attempts across processes and account changes.
- Remove shared enterprise authorization during account logout and `codex mcp logout`, including when the feature is disabled. Continue account logout if enterprise cleanup fails, and invalidate MCP runtimes on account changes.

Start a fresh session after successful enterprise sign-in to use the saved grant.

## Testing

Add regression coverage for login replacement and cancellation, callback port reuse, account changes during setup, cross-process logout invalidation, persisted workspace policy selection, cleanup failures, and responses from older servers without `loginId`.

GitOrigin-RevId: 7ed4caaab4659ed1e67064262cf5cee48e3a26ac
This commit is contained in:
Nick Steele
2026-09-29 14:46:33 +00:00
committed by copyberry
parent 677b07eca0
commit 4994306e9f
43 changed files with 1994 additions and 147 deletions
+34
View File
@@ -22,8 +22,10 @@ use codex_login::login_with_api_key;
use codex_login::logout_with_revoke;
use codex_login::run_device_code_login;
use codex_login::run_login_server;
use codex_mcp::ema_auth_scope;
use codex_protocol::auth::AuthMode;
use codex_protocol::config_types::ForcedLoginMethod;
use codex_rmcp_client::EnterpriseOAuthCredentialGuard;
use codex_utils_cli::CliConfigOverrides;
use std::fs::OpenOptions;
use std::io::IsTerminal;
@@ -511,6 +513,37 @@ pub async fn run_logout(cli_config_overrides: CliConfigOverrides) -> ! {
let config = load_config_or_exit(cli_config_overrides).await;
let auth_route_config = config.auth_route_config();
// Cleanup is independent of the current feature gate. Retain the grant lock
// through account removal so another process cannot commit a late login.
let enterprise_guard = async {
let Some(profile) = &config.mcp_enterprise_managed_auth else {
return Ok::<_, anyhow::Error>(None);
};
let auth = config
.auth_config()
.load_auth(/*enable_codex_api_key_env*/ false)
.await?;
let Some(scope) = ema_auth_scope(auth.as_ref()) else {
return Ok(None);
};
EnterpriseOAuthCredentialGuard::acquire(
&profile.idp.credential_name(&scope),
&profile.idp.issuer,
config.auth_keyring_backend_kind(),
)
.await
.map(Some)
}
.await;
let cleanup_failed = match &enterprise_guard {
Ok(Some(guard)) => guard.delete_tokens().is_err(),
Ok(None) => false,
Err(_) => true,
};
if cleanup_failed {
eprintln!("Warning: failed to remove enterprise authorization; continuing account logout");
}
let logged_out = match logout_with_revoke(
&config.codex_home,
config.cli_auth_credentials_store_mode,
@@ -525,6 +558,7 @@ pub async fn run_logout(cli_config_overrides: CliConfigOverrides) -> ! {
std::process::exit(1);
}
};
drop(enterprise_guard);
let cleared_bedrock_config =
if let Some(paths) = ConfigEditsBuilder::bedrock_provider_config_paths_to_clear(&config) {
+33
View File
@@ -8,6 +8,7 @@ use anyhow::bail;
use clap::ArgGroup;
use clap::builder::TypedValueParser;
use codex_config::types::AppToolApproval;
use codex_config::types::McpServerAuth;
use codex_config::types::McpServerConfig;
use codex_config::types::McpServerOAuthConfig;
use codex_config::types::McpServerTransportConfig;
@@ -28,6 +29,7 @@ use codex_mcp::McpRuntimeContext;
use codex_mcp::apply_http_headers_helper;
use codex_mcp::compute_auth_statuses;
use codex_mcp::discover_supported_scopes;
use codex_mcp::ema_auth_scope;
use codex_mcp::oauth_login_support;
use codex_mcp::resolve_oauth_callback;
use codex_mcp::resolve_oauth_scopes;
@@ -36,6 +38,7 @@ use codex_rmcp_client::McpOAuthCallbackMode;
use codex_rmcp_client::McpOAuthClientRegistration;
use codex_rmcp_client::OAuthDiscoveryTimeout;
use codex_rmcp_client::StreamableHttpRedirectMode;
use codex_rmcp_client::delete_enterprise_oauth_tokens;
use codex_rmcp_client::delete_oauth_tokens;
use codex_rmcp_client::resolve_mcp_oauth_callback_url;
use codex_utils_cli::CliConfigOverrides;
@@ -639,6 +642,36 @@ async fn run_logout(config: &Config, logout_args: LogoutArgs) -> Result<()> {
.get(&name)
.ok_or_else(|| anyhow!("No MCP server named '{name}' found in configuration."))?;
if matches!(server.auth, McpServerAuth::EmaAuth) {
let auth_manager =
AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ true).await?;
let auth = auth_manager.auth().await;
let scope = ema_auth_scope(auth.as_ref())
.context("Sign in to your Codex account before removing enterprise authorization")?;
// Cleanup must remain available even when this server is no longer eligible
// for EMA (for example, after disabling the feature or changing its transport).
let profile = config
.mcp_enterprise_managed_auth
.as_ref()
.context("EMA logout requires a trusted enterprise IdP profile")?;
let idp = &profile.idp;
let credential_name = idp.credential_name(&scope);
match delete_enterprise_oauth_tokens(
&credential_name,
&idp.issuer,
config.auth_keyring_backend_kind(),
)
.await
{
Ok(true) => println!(
"Removed the shared enterprise authorization used by EMA MCP servers (selected via '{name}')."
),
Ok(false) => println!("No shared enterprise authorization is stored."),
Err(_) => return Err(anyhow!("failed to delete enterprise authorization")),
}
return Ok(());
}
let url = match &server.transport {
McpServerTransportConfig::StreamableHttp { url, .. } => url.clone(),
_ => bail!("OAuth logout is only supported for streamable_http transports."),
+73
View File
@@ -183,6 +183,79 @@ fn logout_clears_only_the_selected_bedrock_provider() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn logout_survives_enterprise_cleanup_failure_with_xaa_disabled() -> Result<()> {
let server = MockServer::start().await;
Mock::given(path("/backend-api/wham/config/bundle"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"config_toml": {"enterprise_managed": []},
"requirements_toml": {"enterprise_managed": []},
})))
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/oauth/revoke"))
.respond_with(ResponseTemplate::new(200))
.expect(1)
.mount(&server)
.await;
let home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
format!(
"cli_auth_credentials_store = \"file\"\nchatgpt_base_url = \"{}/backend-api\"\n[features]\nuse_xaa = false\n[mcp_enterprise_managed_auth.idp]\nissuer = \"https://idp.example\"\nclient_id = \"enterprise-client\"\n[mcp_servers.enterprise]\nurl = \"https://resource.example/mcp\"\nauth = \"ema_auth\"\nbearer_token_env_var = \"UNUSED_TOKEN\"\n",
server.uri()
),
)?;
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new("account-access")
.account_id("workspace")
.chatgpt_user_id("user"),
AuthCredentialsStoreMode::File,
)?;
// Fail before touching the real keyring; the subprocess owns this isolated home.
std::fs::write(home.path().join("mcp-oauth-locks"), "not a directory")?;
for enabled in [false, true] {
codex_command(home.path())?
.current_dir(home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove(CODEX_ACCESS_TOKEN_ENV_VAR)
.args([
"-c",
&format!("features.use_xaa={enabled}"),
"mcp",
"logout",
"enterprise",
])
.assert()
.failure()
.stderr(contains("failed to delete enterprise authorization"));
assert!(home.path().join("auth.json").exists());
}
codex_command(home.path())?
.current_dir(home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env(
REVOKE_TOKEN_URL_OVERRIDE_ENV_VAR,
format!("{}/oauth/revoke", server.uri()),
)
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove(CODEX_ACCESS_TOKEN_ENV_VAR)
.args(["logout"])
.assert()
.success()
.stderr(contains("continuing account logout"))
.stderr(contains("Successfully logged out"));
assert!(!home.path().join("auth.json").exists());
Ok(())
}
#[test]
fn login_with_access_token_rejects_invalid_jwt() -> Result<()> {
let codex_home = TempDir::new()?;