aKode fase 2b-2: rimosso login ChatGPT e tutti i sottosistemi solo-ChatGPT

- Login: resta solo chiave API (+ header, Bedrock). Rimossi OAuth/browser,
  device code, refresh/revoke su auth.openai.com, PAT, agent/workload identity,
  runtime agent instance, backend-client e openapi-models, workspace routing.
- Rimossi: generazione immagini (ext + skill imagegen), history notes, plugin
  remoti (catalogo, sync, share), cyber access program, daybreak, cloud config
  e requirements (config_server ora fail-closed), attestation, frozen cloud
  skills, EMA MCP auth, Codex Apps/connettori, ricerca ospitata, header/zstd/
  routing/cookie del backend Codex, fallback OPENAI_API_KEY del realtime.
- Messaggi d'errore senza link a chatgpt.com.
- Chiavi di config legacy accettate e ignorate; feature rimosse = Stage::Removed.
- Test: cancellati solo quelli del codice rimosso; test di sicurezza
  (sandbox estensioni, permessi, redazione, auth storage, requirements)
  adattati. Restano solo fallimenti d'ambiente (code-mode-host/V8, ~/.agents).
- Istruzioni di sistema invariate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-10 16:20:15 +01:00
parent 82347a58ed
commit 6089fbde91
1573 changed files with 10289 additions and 177679 deletions

View File

@@ -8,10 +8,8 @@ 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;
use codex_rmcp_client::McpOAuthCallbackMode;
use codex_rmcp_client::OAuthDiscoveryTimeout;
use codex_rmcp_client::OAuthProviderError;
@@ -22,7 +20,6 @@ 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;
@@ -202,17 +199,12 @@ pub async fn compute_auth_statuses<'a, I>(
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
auth: Option<&CodexAuth>,
auth_manager: Option<&std::sync::Arc<codex_login::AuthManager>>,
ema_state: &crate::EmaState,
runtime_context: &McpRuntimeContext,
) -> HashMap<String, McpAuthStatusEntry>
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
@@ -228,9 +220,6 @@ where
store_mode,
keyring_backend_kind,
auth,
auth_manager,
account_grant,
ema_state,
&runtime_context,
redirect_mode,
)
@@ -259,10 +248,7 @@ async fn compute_auth_status(
config: &McpServerConfig,
store_mode: OAuthCredentialsStoreMode,
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,
_auth: Option<&CodexAuth>,
runtime_context: &McpRuntimeContext,
redirect_mode: StreamableHttpRedirectMode,
) -> Result<McpAuthState> {
@@ -270,73 +256,10 @@ async fn compute_auth_status(
return Ok(McpAuthState::Unsupported);
}
if matches!(config.auth, McpServerAuth::EmaAuth) {
let Some(registration) = config.ema_registration() else {
return Ok(McpAuthState::Unsupported);
};
config
.validate_ema_auth_transport()
.map_err(anyhow::Error::msg)?;
let Some(scope) = crate::ema_auth_scope(auth) else {
return Ok(McpAuthState::LoggedOut(McpLoginRequirement::Login));
};
if matches!(auth, Some(CodexAuth::Chatgpt(_)))
&& auth
.and_then(|auth| auth.get_token_data().ok())
.is_none_or(|tokens| tokens.login_owner_id.as_ref().is_none_or(String::is_empty))
{
return Ok(McpAuthState::LoggedOut(McpLoginRequirement::Login));
}
let account_usable = match auth_manager {
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,
},
None => auth.is_some_and(|auth| ema_state.account_is_usable(auth, registration)),
};
if account_usable {
return Ok(McpAuthState::BearerToken);
}
return Ok(
match crate::ema_auth::stored_ema_credentials(
registration.idp(),
&scope,
keyring_backend_kind,
)
.await?
{
Some(snapshot)
if codex_rmcp_client::stored_ema_identity_is_usable(
snapshot.credentials(),
&registration.idp().issuer,
&registration.idp().client_id,
) =>
{
McpAuthState::OAuth
}
Some(_) => McpAuthState::LoggedOut(McpLoginRequirement::Reauthentication),
None => McpAuthState::LoggedOut(McpLoginRequirement::Login),
},
);
// Enterprise-managed authorization was removed; these servers never start.
return Ok(McpAuthState::Unsupported);
}
let has_runtime_auth = matches!(config.auth, McpServerAuth::ChatGpt)
&& auth.is_some_and(CodexAuth::uses_codex_backend)
&& matches!(
&config.transport,
McpServerTransportConfig::StreamableHttp {
bearer_token_env_var: None,
..
}
);
if matches!(config.auth, McpServerAuth::ChatGpt) && !config.is_local_environment() {
return Ok(if has_explicit_http_authorization(config) {
McpAuthState::BearerToken
@@ -345,10 +268,6 @@ async fn compute_auth_status(
});
}
if has_runtime_auth {
return Ok(McpAuthState::BearerToken);
}
match &config.transport {
McpServerTransportConfig::Stdio { .. } => Ok(McpAuthState::Unsupported),
McpServerTransportConfig::StreamableHttp {

View File

@@ -20,20 +20,14 @@ use std::time::Duration;
use codex_config::ConfigLayerStack;
use codex_config::Constrained;
use codex_config::McpEnterpriseManagedAuthConfig;
use codex_config::McpServerAuth;
use codex_config::McpServerConfig;
use codex_config::McpServerTransportConfig;
use codex_config::types::AppToolApproval;
use codex_config::types::ApprovalsReviewer;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_connectors::ConnectorRuntimeManager;
use codex_connectors::ConnectorSnapshot;
use codex_connectors::connector_runtime_context_key;
use codex_exec_server::FileSystemSandboxContext;
use codex_login::CodexAuth;
use codex_model_provider::CHATGPT_CODEX_BASE_URL;
use codex_protocol::mcp::ClientMcpExtensions;
use codex_protocol::mcp::McpServerInfo;
use codex_protocol::mcp::Resource;
@@ -60,10 +54,9 @@ use crate::runtime::McpRuntimeContext;
use crate::runtime::McpRuntimeInput;
use crate::runtime::McpStartupPolicy;
use crate::server::EffectiveMcpServer;
use crate::tools::ToolInfo;
pub const CODEX_APPS_MCP_SERVER_NAME: &str = "codex_apps";
pub(crate) const DEFAULT_CODEX_APPS_MCP_PRODUCT_SKU: &str = "codex";
/// Product SKU reported in MCP catalog telemetry.
pub(crate) const MCP_CATALOG_PRODUCT_SKU: &str = "codex";
const MCP_TOOL_NAME_PREFIX: &str = "mcp";
const MCP_TOOL_NAME_DELIMITER: &str = "__";
@@ -129,21 +122,10 @@ pub enum McpServerPermissions {
/// runtime entry points such as [`effective_mcp_servers`].
#[derive(Debug, Clone)]
pub struct McpConfig {
/// Base URL for ChatGPT-hosted app MCP servers, copied from the root config.
pub chatgpt_base_url: String,
/// Optional product SKU forwarded to the host-owned apps MCP server.
pub apps_mcp_product_sku: Option<String>,
/// Requests server-side read-only filtering and invocation checks for MCP tools.
pub requires_read_only_mcp_tools: bool,
/// Codex home directory used for MCP OAuth state and app-tool cache files.
pub codex_home: PathBuf,
/// Trusted enterprise IdP inherited after normal catalog and policy resolution.
pub mcp_enterprise_managed_auth: Option<McpEnterpriseManagedAuthConfig>,
/// Retires only EMA connections and pending exchanges for this config snapshot.
pub mcp_ema_cancellation: codex_config::McpEmaCancellation,
pub xaa_enabled: bool,
/// Shared sign-in requirements for account-backed enterprise MCP.
pub ema_state: Arc<crate::EmaState>,
/// Preferred credential store for MCP OAuth tokens.
pub mcp_oauth_credentials_store_mode: OAuthCredentialsStoreMode,
/// OAuth refresh ownership selected for new MCP connections.
@@ -187,33 +169,21 @@ pub struct McpConfig {
// TODO(anp): Reconcile this runtime-wide copy with TurnEnvironment::sandbox_context
// for the environment that owns each MCP server.
pub use_legacy_landlock: bool,
/// Whether the app MCP integration is enabled by config.
///
/// ChatGPT auth is checked separately before a materialized host-owned Apps
/// server can be used.
pub apps_enabled: bool,
/// Allow hosted Apps catalog reads after MCP initialization, before tools are ready.
pub apps_early_resource_discovery: bool,
/// Whether model-visible MCP tool namespaces should keep the legacy
/// `mcp__` prefix.
pub prefix_mcp_tool_names: bool,
/// MCP servers whose model-visible tool namespaces omit the `mcp__` prefix.
pub non_prefixed_mcp_tool_servers: Vec<String>,
/// Protocol mode for servers other than the host-owned Codex Apps registration.
/// Protocol mode for MCP servers.
pub protocol_mode: McpProtocolMode,
/// Try protocol discovery before initializing eligible local stdio servers.
pub discover_local_stdio: bool,
/// Refresh ordinary server catalogs after tools/list_changed notifications.
pub mcp_tool_list_changed: bool,
/// Independent protocol mode for the trusted, HTTP Codex Apps registration.
pub host_owned_apps_protocol_mode: McpProtocolMode,
/// Client-side elicitation capabilities advertised during MCP initialization.
pub client_elicitation_capability: ElicitationCapability,
/// Resolved MCP registrations keyed by logical server name.
pub mcp_server_catalog: ResolvedMcpCatalog,
/// Plugin declarations used to attribute connector tools to plugin display names.
/// MCP registrations retain their own package attribution in the catalog.
pub connector_snapshot: ConnectorSnapshot,
}
/// Default amount of time a tool catalog capture waits for optional MCP servers.
@@ -232,12 +202,7 @@ impl McpConfig {
.filter(|(_, server)| server.enabled())
.filter_map(|(server_name, _)| {
let server = self.mcp_server_catalog.server(server_name)?;
let permissions = if server
.source()
.is_host_owned_apps(server_name, server.config())
{
McpServerPermissions::Thread
} else if let Some(sandbox) =
let permissions = if let Some(sandbox) =
environment_sandboxes.get(&server.config().environment_id)
{
McpServerPermissions::Environment(Arc::clone(sandbox))
@@ -277,25 +242,12 @@ impl McpConfig {
/// Plugin attribution and selection data derived from the current MCP configuration.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ToolPluginContext {
plugin_display_names_by_connector_id: HashMap<String, Vec<String>>,
disabled_connector_ids: HashSet<String>,
plugin_display_names_by_mcp_server_name: HashMap<String, Vec<String>>,
plugin_ids_by_mcp_server_name: HashMap<String, String>,
selected_plugin_mcp_server_names: HashSet<String>,
}
impl ToolPluginContext {
pub(crate) fn allows_connector_id(&self, connector_id: Option<&str>) -> bool {
connector_id.is_none_or(|id| !self.disabled_connector_ids.contains(id))
}
pub fn plugin_display_names_for_connector_id(&self, connector_id: &str) -> &[String] {
self.plugin_display_names_by_connector_id
.get(connector_id)
.map(Vec::as_slice)
.unwrap_or(&[])
}
pub fn plugin_display_names_for_mcp_server_name(&self, server_name: &str) -> &[String] {
self.plugin_display_names_by_mcp_server_name
.get(server_name)
@@ -314,21 +266,7 @@ impl ToolPluginContext {
}
fn from_config(config: &McpConfig) -> Self {
let mut tool_plugin_context = Self {
disabled_connector_ids: config.connector_snapshot.disabled_connector_ids().clone(),
..Self::default()
};
for connector_id in config.connector_snapshot.connector_ids() {
tool_plugin_context
.plugin_display_names_by_connector_id
.insert(
connector_id.0.clone(),
config
.connector_snapshot
.plugin_display_names_for_connector_id(&connector_id.0)
.to_vec(),
);
}
let mut tool_plugin_context = Self::default();
for (server_name, attribution) in config
.mcp_server_catalog
@@ -352,13 +290,8 @@ impl ToolPluginContext {
);
for plugin_names in tool_plugin_context
.plugin_display_names_by_connector_id
.plugin_display_names_by_mcp_server_name
.values_mut()
.chain(
tool_plugin_context
.plugin_display_names_by_mcp_server_name
.values_mut(),
)
{
plugin_names.sort_unstable();
plugin_names.dedup();
@@ -378,39 +311,6 @@ pub fn effective_mcp_servers(
effective_mcp_servers_from_configured(configured_mcp_servers(config), config, auth)
}
pub(crate) fn is_trusted_chatgpt_mcp_server(
transport: &McpServerTransportConfig,
chatgpt_base_url: &str,
) -> bool {
let McpServerTransportConfig::StreamableHttp { url, .. } = transport else {
return false;
};
let Ok(server_url) = url::Url::parse(url) else {
return false;
};
if !matches!(server_url.scheme(), "http" | "https") {
return false;
}
if [CHATGPT_CODEX_BASE_URL, "https://gov.chatgpt.com"]
.into_iter()
.filter_map(|base_url| url::Url::parse(base_url).ok())
.any(|trusted_url| server_url.origin() == trusted_url.origin())
{
return true;
}
url::Url::parse(chatgpt_base_url)
.ok()
.is_some_and(|staging_url| {
staging_url.scheme() == "https"
&& staging_url.domain().is_some_and(|host| {
host == "chatgpt-staging.com" || host.ends_with(".chatgpt-staging.com")
})
&& server_url.origin() == staging_url.origin()
})
}
/// Converts a materialized server map to its auth-gated runtime view.
///
/// Compatibility built-ins and extension overlays must already be reflected in
@@ -424,7 +324,7 @@ pub fn effective_mcp_servers_from_configured(
config: &McpConfig,
_auth: Option<&CodexAuth>,
) -> HashMap<String, EffectiveMcpServer> {
let mut servers = configured_servers
configured_servers
.into_iter()
.map(|(name, mut server)| {
#[expect(
@@ -435,13 +335,11 @@ pub fn effective_mcp_servers_from_configured(
.mcp_server_catalog
.server(&name)
.expect("materialized MCP server must have a catalog registration");
match server.auth.clone() {
McpServerAuth::ChatGpt => {
if !is_trusted_chatgpt_mcp_server(&server.transport, &config.chatgpt_base_url) {
server.auth = McpServerAuth::OAuth;
}
}
McpServerAuth::OAuth | McpServerAuth::EmaAuth => {}
// ChatGPT credentials are never available, so local servers that ask for them use
// their own OAuth flow. Executor-owned servers keep `ChatGpt` so they never consult
// orchestrator OAuth stores and are rejected unless they carry explicit authorization.
if matches!(server.auth, McpServerAuth::ChatGpt) && server.is_local_environment() {
server.auth = McpServerAuth::OAuth;
}
(
name,
@@ -452,10 +350,7 @@ pub fn effective_mcp_servers_from_configured(
.with_agent_plugin(registration.source().is_agent_plugin()),
)
})
.collect::<HashMap<_, _>>();
// aKode never connects to the ChatGPT-hosted apps MCP server.
servers.remove(CODEX_APPS_MCP_SERVER_NAME);
servers
.collect::<HashMap<_, _>>()
}
pub fn tool_plugin_context(config: &McpConfig) -> ToolPluginContext {
@@ -466,12 +361,7 @@ pub fn tool_plugin_context(config: &McpConfig) -> ToolPluginContext {
pub async fn read_mcp_resource(
config: &McpConfig,
auth: Option<&CodexAuth>,
runtime_auth: Option<(
codex_runtime_agent_instance::RuntimeAuthSlot,
codex_features::RuntimeAuthMode,
)>,
runtime_context: McpRuntimeContext,
codex_apps_tools_cache: ConnectorRuntimeManager<ToolInfo>,
tool_catalog_cache: crate::McpToolCatalogCache,
server: &str,
params: ReadResourceRequestParams,
@@ -481,13 +371,11 @@ pub async fn read_mcp_resource(
let cancel_token = CancellationToken::new();
let runtime_config = config.for_threadless_operations(&mcp_servers);
let manager = McpConnectionSet::new(
/*ema_auth*/ None,
/*existing_ema*/ None,
/*predecessor*/ None,
/*previous*/ None,
McpPublicationGate::already_published(),
McpRuntimeInput {
network_policy_metadata: None,
runtime_auth,
startup_policy: McpStartupPolicy::Eager,
config: Arc::new(runtime_config),
plugins_available: false,
@@ -497,9 +385,7 @@ pub async fn read_mcp_resource(
tx_event: None,
startup_cancellation_token: cancel_token.clone(),
runtime_context,
codex_apps_tools_cache,
tool_catalog_cache,
codex_apps_tools_cache_key: connector_runtime_context_key(auth),
client_mcp_extensions: ClientMcpExtensions::default(),
auth: auth.cloned(),
auth_manager: None,
@@ -532,13 +418,7 @@ pub struct McpServerStatusSnapshot {
pub async fn collect_mcp_server_status_snapshot_with_detail(
config: &McpConfig,
auth: Option<&CodexAuth>,
auth_manager: Option<&Arc<codex_login::AuthManager>>,
runtime_auth: Option<(
codex_runtime_agent_instance::RuntimeAuthSlot,
codex_features::RuntimeAuthMode,
)>,
runtime_context: McpRuntimeContext,
codex_apps_tools_cache: ConnectorRuntimeManager<ToolInfo>,
tool_catalog_cache: crate::McpToolCatalogCache,
detail: McpSnapshotDetail,
server_name: Option<&str>,
@@ -564,8 +444,6 @@ pub async fn collect_mcp_server_status_snapshot_with_detail(
config.mcp_oauth_credentials_store_mode,
config.auth_keyring_backend_kind,
auth,
auth_manager,
&config.ema_state,
&runtime_context,
)
.await;
@@ -575,13 +453,11 @@ pub async fn collect_mcp_server_status_snapshot_with_detail(
let cancel_token = CancellationToken::new();
let runtime_config = config.for_threadless_operations(&mcp_servers);
let mcp_connection_manager = McpConnectionSet::new(
/*ema_auth*/ None,
/*existing_ema*/ None,
/*predecessor*/ None,
/*previous*/ None,
McpPublicationGate::already_published(),
McpRuntimeInput {
network_policy_metadata: None,
runtime_auth,
startup_policy: McpStartupPolicy::Eager,
config: Arc::new(runtime_config),
plugins_available: false,
@@ -591,9 +467,7 @@ pub async fn collect_mcp_server_status_snapshot_with_detail(
tx_event: None,
startup_cancellation_token: cancel_token.clone(),
runtime_context,
codex_apps_tools_cache,
tool_catalog_cache,
codex_apps_tools_cache_key: connector_runtime_context_key(auth),
client_mcp_extensions: ClientMcpExtensions::default(),
auth: auth.cloned(),
auth_manager: None,
@@ -794,16 +668,11 @@ pub(crate) async fn collect_mcp_server_status_snapshot_from_manager(
.insert(tool_name, tool);
}
// Status-only discovery has no event channel. Report OAuth and EMA failures from the completed
// Status-only discovery has no event channel. Report OAuth failures from the completed
// connection attempt instead of retaining the credential-presence status read beforehand.
let mut auth_statuses = auth_statuses_from_entries(&auth_status_entries);
for server_name in mcp_connection_manager.authentication_failed_servers().await {
if auth_statuses.get(&server_name) == Some(&McpAuthStatus::OAuth)
|| auth_status_entries
.get(&server_name)
.and_then(|entry| entry.config.as_ref())
.is_some_and(|config| matches!(config.auth, McpServerAuth::EmaAuth))
{
if auth_statuses.get(&server_name) == Some(&McpAuthStatus::OAuth) {
auth_statuses.insert(server_name, McpAuthStatus::NotLoggedIn);
}
}
@@ -829,7 +698,7 @@ pub(crate) mod tests;
#[cfg(test)]
pub(crate) fn test_http_mcp_server_config(url: &str) -> McpServerConfig {
McpServerConfig {
transport: McpServerTransportConfig::StreamableHttp {
transport: codex_config::McpServerTransportConfig::StreamableHttp {
url: url.to_string(),
bearer_token_env_var: None,
http_headers: None,

View File

@@ -11,16 +11,13 @@ 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;
use codex_protocol::models::ManagedFileSystemPermissions;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::GranularApprovalConfig;
use codex_config::McpServerTransportConfig;
use codex_rmcp_client::McpAuthState;
use futures::FutureExt;
use pretty_assertions::assert_eq;
@@ -31,63 +28,15 @@ use std::sync::Arc;
use std::time::Duration;
#[tokio::test]
async fn ema_auth_statuses_do_not_wait_for_account_refresh() -> anyhow::Result<()> {
async fn removed_ema_auth_servers_report_unsupported_auth() -> 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 auth = CodexAuth::from_api_key("test-api-key");
let mut servers = HashMap::new();
for name in ["first", "second"] {
let mut server: McpServerConfig = serde_json::from_value(serde_json::json!({
let 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(),
client_secret: None,
token_endpoint_auth_method: None,
})
.map_err(anyhow::Error::msg)?;
servers.insert(
name.to_string(),
EffectiveMcpServer::from_host_config(server),
@@ -104,33 +53,30 @@ async fn ema_auth_statuses_do_not_wait_for_account_refresh() -> anyhow::Result<(
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
Some(&auth),
Some(&manager),
&crate::EmaState::default(),
&runtime_context,
),
)
.await
.context("MCP auth status waited for the held account lease")?;
.context("MCP auth status should not block")?;
// Enterprise-managed authorization was removed; never borrow another credential.
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),
("first".to_string(), McpAuthState::Unsupported),
("second".to_string(), McpAuthState::Unsupported),
]),
);
drop(lease);
Ok(())
}
#[tokio::test]
async fn status_snapshot_only_downgrades_oauth_and_ema_authentication_failures() {
async fn status_snapshot_only_downgrades_oauth_authentication_failures() {
let auth_failure = StartupOutcomeError::Failed {
error: "OAuth refresh token was rejected".to_string(),
is_authentication_required: true,
is_ema_authentication_required: false,
shutdown: None,
};
let mut manager = McpConnectionSet::empty(/*prefix_mcp_tool_names*/ true);
@@ -148,21 +94,9 @@ async fn status_snapshot_only_downgrades_oauth_and_ema_authentication_failures()
Some(StartupOutcomeError::Failed {
error: "provider temporarily unavailable".to_string(),
is_authentication_required: false,
is_ema_authentication_required: false,
shutdown: None,
}),
),
(
"ema-failed",
McpAuthState::BearerToken,
Some(auth_failure.clone()),
),
("ema-ready", McpAuthState::BearerToken, None),
(
"ema-provider-error",
McpAuthState::BearerToken,
Some(anyhow::anyhow!("provider temporarily unavailable").into()),
),
("bearer", McpAuthState::BearerToken, Some(auth_failure)),
] {
let mut client = create_ready_async_managed_client(Vec::new()).await;
@@ -173,12 +107,7 @@ async fn status_snapshot_only_downgrades_oauth_and_ema_authentication_failures()
auth_status_entries.insert(
name.to_string(),
McpAuthStatusEntry {
config: name.starts_with("ema-").then(|| {
serde_json::from_value(serde_json::json!({
"url": "https://example.com/mcp", "auth": "ema_auth",
}))
.expect("EMA config")
}),
config: None,
auth_state,
},
);
@@ -199,9 +128,6 @@ async fn status_snapshot_only_downgrades_oauth_and_ema_authentication_failures()
("oauth-failed".to_string(), McpAuthStatus::NotLoggedIn),
("oauth-ready".to_string(), McpAuthStatus::OAuth),
("oauth-provider-error".to_string(), McpAuthStatus::OAuth),
("ema-failed".to_string(), McpAuthStatus::NotLoggedIn),
("ema-ready".to_string(), McpAuthStatus::BearerToken),
("ema-provider-error".to_string(), McpAuthStatus::BearerToken),
("bearer".to_string(), McpAuthStatus::BearerToken),
]),
);
@@ -209,14 +135,8 @@ async fn status_snapshot_only_downgrades_oauth_and_ema_authentication_failures()
pub(crate) fn test_mcp_config(codex_home: PathBuf) -> McpConfig {
McpConfig {
chatgpt_base_url: "https://chatgpt.com".to_string(),
apps_mcp_product_sku: None,
requires_read_only_mcp_tools: false,
codex_home,
mcp_enterprise_managed_auth: None,
ema_state: Default::default(),
mcp_ema_cancellation: codex_config::McpEmaCancellation::default(),
xaa_enabled: false,
mcp_oauth_credentials_store_mode: OAuthCredentialsStoreMode::default(),
oauth_refresh_mode: McpOAuthRefreshMode::Legacy,
auth_keyring_backend_kind: AuthKeyringBackendKind::default(),
@@ -236,17 +156,13 @@ pub(crate) fn test_mcp_config(codex_home: PathBuf) -> McpConfig {
codex_self_exe: None,
codex_linux_sandbox_exe: None,
use_legacy_landlock: false,
apps_enabled: false,
apps_early_resource_discovery: false,
prefix_mcp_tool_names: true,
non_prefixed_mcp_tool_servers: Vec::new(),
protocol_mode: McpProtocolMode::Legacy,
discover_local_stdio: false,
mcp_tool_list_changed: true,
host_owned_apps_protocol_mode: McpProtocolMode::Legacy,
client_elicitation_capability: ElicitationCapability::default(),
mcp_server_catalog: ResolvedMcpCatalog::default(),
connector_snapshot: codex_connectors::ConnectorSnapshot::default(),
}
}
@@ -265,7 +181,7 @@ pub(crate) fn test_elicitation_config(
}
#[test]
fn ema_catalog_allows_only_configured_servers_without_widening_policy() {
fn removed_ema_auth_servers_stay_disabled_for_every_source_and_policy() {
let server: McpServerConfig = serde_json::from_value(serde_json::json!({
"url": "https://resource.example/mcp", "auth": "ema_auth",
"oauth": { "client_id": "resource-client", "authorization_server_issuer": "https://as.example" }
@@ -290,21 +206,12 @@ fn ema_catalog_allows_only_configured_servers_without_widening_policy() {
server,
));
let mut config = test_mcp_config(PathBuf::new());
let idp = codex_config::McpServerIdpOAuthConfig {
issuer: "https://idp.example".into(),
client_secret: None,
token_endpoint_auth_method: None,
client_id: "enterprise-client".into(),
};
let deny_all = codex_protocol::mcp_policy::EnvironmentMcpPolicy {
servers: Some(Default::default()),
plugins: None,
};
for (xaa_enabled, denied) in [(true, false), (true, true), (false, false)] {
let mut catalog = catalog.clone();
if xaa_enabled {
catalog.enable_ema(idp.clone());
}
for denied in [false, true] {
let catalog = catalog.clone();
config.mcp_server_catalog = catalog.build_with_environment_authority(|_| {
if denied {
crate::McpEnvironmentAuthority::Restricted(&deny_all)
@@ -314,9 +221,7 @@ fn ema_catalog_allows_only_configured_servers_without_widening_policy() {
});
let servers = effective_mcp_servers(&config, /*auth*/ None);
for name in ["configured", "installed", "selected"] {
let eligible = name == "configured" && xaa_enabled;
assert_eq!(servers[name].enabled(), eligible && !denied, "{name}");
assert_eq!(servers[name].config().oauth_idp(), eligible.then_some(&idp));
assert!(!servers[name].enabled(), "{name}");
assert_eq!(servers[name].config().auth, McpServerAuth::EmaAuth);
}
}
@@ -434,7 +339,7 @@ fn mcp_prompt_auto_approval_honors_approved_tools_in_all_permission_modes() {
}
#[test]
fn tool_plugin_context_collects_app_and_mcp_sources() {
fn tool_plugin_context_collects_mcp_sources() {
let mut config = test_mcp_config(PathBuf::new());
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_plugin(
@@ -444,44 +349,11 @@ fn tool_plugin_context_collects_app_and_mcp_sources() {
test_http_mcp_server_config("https://alpha.example"),
));
config.mcp_server_catalog = catalog.build();
config.connector_snapshot =
codex_connectors::ConnectorSnapshot::from_plugin_capability_summaries(&[
PluginCapabilitySummary {
config_name: "alpha@test".to_string(),
display_name: "alpha-plugin".to_string(),
plugin_namespace: None,
app_connector_ids: vec![AppConnectorId("connector_example".to_string())],
mcp_server_names: vec!["alpha".to_string()],
..PluginCapabilitySummary::default()
},
PluginCapabilitySummary {
config_name: "beta@test".to_string(),
display_name: "beta-plugin".to_string(),
plugin_namespace: None,
app_connector_ids: vec![
AppConnectorId("connector_example".to_string()),
AppConnectorId("connector_gmail".to_string()),
],
mcp_server_names: vec!["beta".to_string()],
..PluginCapabilitySummary::default()
},
]);
let provenance = tool_plugin_context(&config);
assert_eq!(
provenance,
ToolPluginContext {
disabled_connector_ids: HashSet::new(),
plugin_display_names_by_connector_id: HashMap::from([
(
"connector_example".to_string(),
vec!["alpha-plugin".to_string(), "beta-plugin".to_string()],
),
(
"connector_gmail".to_string(),
vec!["beta-plugin".to_string()],
),
]),
plugin_display_names_by_mcp_server_name: HashMap::from([(
"alpha".to_string(),
vec!["alpha-plugin".to_string()],
@@ -515,24 +387,12 @@ fn selected_mcp_attribution_does_not_join_an_unrelated_local_summary() {
test_http_mcp_server_config("https://github.example"),
));
config.mcp_server_catalog = catalog.build();
config.connector_snapshot =
codex_connectors::ConnectorSnapshot::from_plugin_capability_summaries(&[
PluginCapabilitySummary {
config_name: "shared-plugin-id".to_string(),
display_name: "Local GitHub".to_string(),
plugin_namespace: None,
mcp_server_names: vec!["github".to_string()],
..PluginCapabilitySummary::default()
},
]);
let provenance = tool_plugin_context(&config);
assert_eq!(
provenance,
ToolPluginContext {
disabled_connector_ids: HashSet::new(),
plugin_display_names_by_connector_id: HashMap::new(),
plugin_display_names_by_mcp_server_name: HashMap::from([(
"github".to_string(),
vec!["Executor GitHub".to_string()],
@@ -597,7 +457,7 @@ fn effective_mcp_servers_require_catalog_registration() {
}
#[test]
fn effective_mcp_servers_preserve_chatgpt_auth_for_trusted_origins() {
fn effective_mcp_servers_never_grant_chatgpt_auth_even_for_chatgpt_origins() {
for (base_url, server_url) in [
("https://chatgpt-staging.com", "https://chatgpt-staging.com"),
(
@@ -612,7 +472,6 @@ fn effective_mcp_servers_preserve_chatgpt_auth_for_trusted_origins() {
("https://chatgpt.com", "https://GOV.CHATGPT.COM:443"),
] {
let mut config = test_mcp_config(PathBuf::new());
config.chatgpt_base_url = base_url.to_string();
let mut server = test_http_mcp_server_config(server_url);
server.auth = McpServerAuth::ChatGpt;
let mut catalog = ResolvedMcpCatalog::builder();
@@ -626,7 +485,7 @@ fn effective_mcp_servers_preserve_chatgpt_auth_for_trusted_origins() {
assert_eq!(
effective["trusted"].config().auth,
McpServerAuth::ChatGpt,
McpServerAuth::OAuth,
"backend {base_url}, server {server_url}",
);
}
@@ -644,7 +503,6 @@ fn effective_mcp_servers_reject_untrusted_origins_for_chatgpt_auth() {
"https://example.com",
] {
let mut config = test_mcp_config(PathBuf::new());
config.chatgpt_base_url = url.to_string();
let mut server = test_http_mcp_server_config(url);
server.auth = McpServerAuth::ChatGpt;
let mut catalog = ResolvedMcpCatalog::builder();
@@ -668,8 +526,7 @@ fn effective_mcp_servers_reject_untrusted_origins_for_chatgpt_auth() {
async fn effective_mcp_servers_preserve_runtime_servers() {
let codex_home = tempfile::tempdir().expect("tempdir");
let mut config = test_mcp_config(codex_home.path().to_path_buf());
config.apps_enabled = true;
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let auth = CodexAuth::from_api_key("test-api-key");
let mut catalog = ResolvedMcpCatalog::builder();
catalog.register(McpServerRegistration::from_config(
@@ -733,8 +590,8 @@ async fn effective_mcp_servers_preserve_runtime_servers() {
},
));
catalog.register(McpServerRegistration::from_config(
CODEX_APPS_MCP_SERVER_NAME.to_string(),
test_http_mcp_server_config("https://chatgpt.com/backend-api/ps/mcp"),
"codex_apps".to_string(),
test_http_mcp_server_config("https://apps.example/mcp"),
));
config.mcp_server_catalog = catalog.build();
@@ -744,8 +601,8 @@ async fn effective_mcp_servers_preserve_runtime_servers() {
let docs = effective
.get("docs")
.expect("configured server should exist");
// aKode never connects to the ChatGPT-hosted apps MCP server.
assert!(!effective.contains_key(CODEX_APPS_MCP_SERVER_NAME));
// The formerly reserved hosted Apps name is now an ordinary configured server.
assert!(effective.contains_key("codex_apps"));
let sample = sample.config();
let docs = docs.config();