WIP fase 2b-2: rimosso login ChatGPT/OAuth/device code, agent/workload identity, backend-client; resta solo chiave API (test non tutti verdi)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -17,20 +17,16 @@ anyhow = { workspace = true }
|
||||
arc-swap = { workspace = true }
|
||||
async-channel = { workspace = true }
|
||||
codex-async-utils = { workspace = true }
|
||||
codex-api = { workspace = true }
|
||||
codex-config = { workspace = true }
|
||||
codex-connectors = { workspace = true }
|
||||
codex-diagnostics = { workspace = true }
|
||||
codex-exec-server = { workspace = true }
|
||||
codex-features = { workspace = true }
|
||||
codex-http-client = { workspace = true }
|
||||
codex-login = { workspace = true }
|
||||
codex-model-provider = { workspace = true }
|
||||
codex-network-proxy = { workspace = true }
|
||||
codex-otel = { workspace = true }
|
||||
codex-protocol = { workspace = true }
|
||||
codex-rmcp-client = { workspace = true }
|
||||
codex-runtime-agent-instance = { workspace = true }
|
||||
codex-utils-absolute-path = { workspace = true }
|
||||
codex-utils-path-uri = { workspace = true }
|
||||
codex-utils-plugins = { workspace = true }
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
//! Authentication shared by requests on an MCP connection.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_api::AuthError;
|
||||
use codex_api::SharedAuthProvider;
|
||||
use codex_exec_server::RouteAwareHttpClient;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider::ClientAuth;
|
||||
use codex_rmcp_client::AuthProviderResolver;
|
||||
use codex_runtime_agent_instance::RuntimeAuthSlot;
|
||||
use futures::future::BoxFuture;
|
||||
use http::HeaderMap;
|
||||
use tokio::sync::OnceCell;
|
||||
|
||||
use crate::McpRuntimeContext;
|
||||
|
||||
/// A connection keeps its credential source across retries and reconnects. Initial runtime
|
||||
/// selection happens inside the startup deadline; each HTTP request then selects fresh auth.
|
||||
#[derive(Clone)]
|
||||
pub(crate) enum McpAuthProvider {
|
||||
Credentials(SharedAuthProvider),
|
||||
Runtime(Arc<RuntimeMcpAuth>),
|
||||
}
|
||||
|
||||
pub(crate) struct RuntimeMcpAuth {
|
||||
slot: RuntimeAuthSlot,
|
||||
mode: RuntimeAuthMode,
|
||||
auth: CodexAuth,
|
||||
client_auth: OnceCell<ClientAuth>,
|
||||
}
|
||||
|
||||
struct RuntimeMcpRequestAuth {
|
||||
auth: ClientAuth,
|
||||
http_client_factory: HttpClientFactory,
|
||||
}
|
||||
|
||||
impl McpAuthProvider {
|
||||
pub(crate) fn runtime(
|
||||
(slot, mode): (RuntimeAuthSlot, RuntimeAuthMode),
|
||||
auth: CodexAuth,
|
||||
) -> Self {
|
||||
Self::Runtime(Arc::new(RuntimeMcpAuth {
|
||||
slot,
|
||||
mode,
|
||||
auth,
|
||||
client_auth: OnceCell::new(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) async fn resolve(
|
||||
&self,
|
||||
mut context: McpRuntimeContext,
|
||||
url: &str,
|
||||
) -> anyhow::Result<(Arc<dyn AuthProviderResolver>, McpRuntimeContext)> {
|
||||
match self {
|
||||
Self::Credentials(provider) => Ok((Arc::new(Arc::clone(provider)), context)),
|
||||
Self::Runtime(runtime) => {
|
||||
codex_model_provider::validate_runtime_destination(Some(url))?;
|
||||
let manager = runtime.slot.get().ok_or_else(|| {
|
||||
AuthError::Build("runtime authentication is not initialized".to_string())
|
||||
})?;
|
||||
let auth = runtime
|
||||
.client_auth
|
||||
.get_or_try_init(|| async {
|
||||
ClientAuth::for_auth(
|
||||
&runtime.auth,
|
||||
Some(&(Arc::clone(manager), runtime.mode)),
|
||||
context.http_client_factory(),
|
||||
&HeaderMap::new(),
|
||||
)
|
||||
.await
|
||||
.map(|(auth, _)| auth)
|
||||
})
|
||||
.await?;
|
||||
let selected = auth.resolve(&HeaderMap::new()).await?;
|
||||
let factory = selected.bind_http_client_factory(context.http_client_factory())?;
|
||||
context.set_local_http_client(Arc::new(
|
||||
RouteAwareHttpClient::new(factory.clone()).with_tls_backend_fallback(),
|
||||
));
|
||||
Ok((
|
||||
Arc::new(RuntimeMcpRequestAuth {
|
||||
auth: auth.clone(),
|
||||
http_client_factory: factory,
|
||||
}),
|
||||
context,
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthProviderResolver for RuntimeMcpRequestAuth {
|
||||
fn resolve<'a>(
|
||||
&'a self,
|
||||
headers: &'a HeaderMap,
|
||||
) -> BoxFuture<'a, Result<SharedAuthProvider, AuthError>> {
|
||||
Box::pin(async move {
|
||||
let selected = self.auth.resolve(headers).await?;
|
||||
let factory = selected.bind_http_client_factory(self.http_client_factory.clone())?;
|
||||
// Reuse the connection's transport, including its original account-policy binding.
|
||||
// A newly selected policy must not revive a connection that was already revoked.
|
||||
if factory != self.http_client_factory {
|
||||
return Err(AuthError::Build(
|
||||
"runtime authentication changed the MCP connection's network policy"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
Ok(selected.auth)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "auth_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,203 +0,0 @@
|
||||
use super::*;
|
||||
|
||||
use base64::Engine;
|
||||
use codex_config::types::AuthKeyringBackendKind;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_exec_server::HttpRedirectPolicy;
|
||||
use codex_exec_server::HttpRequestParams;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_http_client::DestinationPolicy;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::NetworkPolicyController;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_login::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::AuthRouteConfig;
|
||||
use codex_runtime_agent_instance::AgentHostAuthorization;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
|
||||
use codex_runtime_agent_instance::RuntimeRole;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
struct RotatingAuth(std::sync::RwLock<CodexAuth>);
|
||||
|
||||
impl codex_login::ExternalAuth for RotatingAuth {
|
||||
fn resolve(&self) -> codex_login::ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async { Ok(self.0.read().unwrap().clone()) })
|
||||
}
|
||||
|
||||
fn refresh(
|
||||
&self,
|
||||
_: codex_login::ExternalAuthRefreshContext,
|
||||
) -> codex_login::ExternalAuthFuture<'_, CodexAuth> {
|
||||
self.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn deferred_connection_keeps_runtime_source_and_captured_account_policy() -> anyhow::Result<()>
|
||||
{
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path("/agent/register"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": "runtime-mcp", "agent_host_id": "host-a",
|
||||
"actor": {"kind": "chatgpt", "user_id": "user-a", "account_id": "workspace-a"},
|
||||
})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(path("/mcp"))
|
||||
.respond_with(ResponseTemplate::new(200))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let home = tempfile::tempdir()?;
|
||||
let oauth = |session, token| {
|
||||
let claims = json!({
|
||||
"iss": "https://auth.openai.com/", "session_id": session, "jti": token,
|
||||
"https://api.openai.com/auth": {"user_id": "user-a", "chatgpt_account_id": "workspace-a"}
|
||||
});
|
||||
let payload =
|
||||
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string());
|
||||
CodexAuth::from_external_chatgpt_tokens(
|
||||
&format!("header.{payload}.signature"),
|
||||
"workspace-a",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
let initial = oauth("session-a", "initial");
|
||||
let refreshed = oauth("session-a", "refreshed");
|
||||
let source = Arc::new(RotatingAuth(std::sync::RwLock::new(initial.clone())));
|
||||
let controller = NetworkPolicyController::default();
|
||||
let policy = controller.policy();
|
||||
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
|
||||
.with_network_policy(policy.clone());
|
||||
let credentials = Arc::new(
|
||||
AuthManager::new(
|
||||
home.path().to_path_buf(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::Ephemeral,
|
||||
/*forced_chatgpt_workspace_id*/ None,
|
||||
/*chatgpt_base_url*/ None,
|
||||
AuthKeyringBackendKind::Direct,
|
||||
AuthRouteConfig::from_http_client_factory(factory.clone()),
|
||||
)
|
||||
.await,
|
||||
);
|
||||
credentials.set_external_auth(source.clone()).await?;
|
||||
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
|
||||
let runtime = (
|
||||
Arc::new(std::sync::OnceLock::from(Arc::new(
|
||||
RuntimeAuthManager::new(
|
||||
Arc::clone(&credentials),
|
||||
AgentHostAuthorization::InstallationId {
|
||||
installation_id: uuid::Uuid::nil(),
|
||||
},
|
||||
RuntimeRegistrationMetadata {
|
||||
harness: Some("codex".into()),
|
||||
harness_version: None,
|
||||
role: RuntimeRole::Orchestrator,
|
||||
},
|
||||
format!("{}/agent/register", server.uri()).parse()?,
|
||||
),
|
||||
))),
|
||||
mode,
|
||||
);
|
||||
let context = McpRuntimeContext::new(
|
||||
Arc::new(EnvironmentManager::without_environments(factory)),
|
||||
home.path().to_path_buf(),
|
||||
);
|
||||
let deferred = McpAuthProvider::runtime(runtime.clone(), initial.clone());
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
let error = deferred
|
||||
.resolve(context.clone(), "https://future.openai.com/mcp")
|
||||
.await
|
||||
.err()
|
||||
.expect("unsupported OpenAI destination must fail before registration");
|
||||
assert!(
|
||||
error
|
||||
.downcast_ref::<codex_protocol::error::CodexErr>()
|
||||
.is_some_and(|error| matches!(
|
||||
error.details(),
|
||||
codex_protocol::error::CodexErrorDetails::UnsupportedOperation(_)
|
||||
))
|
||||
);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
let (provider, selected_context) = deferred.resolve(context.clone(), &server.uri()).await?;
|
||||
let first = provider
|
||||
.resolve(&Default::default())
|
||||
.await?
|
||||
.apply_auth_headers(Default::default())
|
||||
.await?;
|
||||
*source.0.write().unwrap() = refreshed.clone();
|
||||
let second = provider
|
||||
.resolve(&Default::default())
|
||||
.await?
|
||||
.apply_auth_headers(Default::default())
|
||||
.await?;
|
||||
let assertion_header = match mode {
|
||||
RuntimeAuthMode::DualHeader => "x-openai-agent-assertion",
|
||||
RuntimeAuthMode::AssertionOnly => "authorization",
|
||||
};
|
||||
assert_ne!(first[assertion_header], second[assertion_header]);
|
||||
if mode == RuntimeAuthMode::DualHeader {
|
||||
assert_eq!(
|
||||
first["authorization"],
|
||||
format!("Bearer {}", initial.get_token()?)
|
||||
);
|
||||
assert_eq!(
|
||||
second["authorization"],
|
||||
format!("Bearer {}", refreshed.get_token()?)
|
||||
);
|
||||
}
|
||||
let request = || HttpRequestParams {
|
||||
method: "GET".into(),
|
||||
url: format!("{}/mcp", server.uri()),
|
||||
headers: Vec::new(),
|
||||
body: None,
|
||||
timeout_ms: Some(1000),
|
||||
redirect_policy: HttpRedirectPolicy::Stop,
|
||||
request_id: "mcp-policy-test".into(),
|
||||
stream_response: false,
|
||||
};
|
||||
let client = selected_context.local_http_client();
|
||||
assert_eq!(client.http_request(request()).await?.status, 200);
|
||||
policy.invalidate();
|
||||
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
|
||||
assert!(client.http_request(request()).await.is_err());
|
||||
// A new connection captures the new policy and reuses the same registered runtime.
|
||||
let current = McpAuthProvider::runtime(runtime, refreshed);
|
||||
let (_, current_context) = current.resolve(context, &server.uri()).await?;
|
||||
assert_eq!(
|
||||
current_context
|
||||
.local_http_client()
|
||||
.http_request(request())
|
||||
.await?
|
||||
.status,
|
||||
200
|
||||
);
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(
|
||||
requests
|
||||
.iter()
|
||||
.filter(|request| request.url.path() == "/agent/register")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
*source.0.write().unwrap() = oauth("another-session", "replacement");
|
||||
assert!(provider.resolve(&Default::default()).await.is_err());
|
||||
assert_eq!(
|
||||
requests
|
||||
.iter()
|
||||
.filter(|request| request.url.path() == "/mcp")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -456,22 +456,6 @@ impl PreparedMcpCall {
|
||||
let (arguments, meta) = prepare().await?;
|
||||
let timeout_deadline =
|
||||
effective_timeout.map(|timeout| tokio::time::Instant::now() + timeout);
|
||||
let add_trusted_access_context = self.connections.add_trusted_access_context(
|
||||
self.tool_info(),
|
||||
&self.server_metadata,
|
||||
arguments.as_ref(),
|
||||
meta,
|
||||
);
|
||||
let meta = match effective_timeout.zip(timeout_deadline) {
|
||||
Some((timeout, deadline)) => {
|
||||
tokio::time::timeout_at(deadline, add_trusted_access_context)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
codex_rmcp_client::request_timeout_error("tools/call", timeout)
|
||||
})?
|
||||
}
|
||||
None => add_trusted_access_context.await,
|
||||
};
|
||||
let remaining_timeout = match effective_timeout.zip(timeout_deadline) {
|
||||
Some((timeout, deadline)) => {
|
||||
let remaining =
|
||||
|
||||
@@ -9,24 +9,19 @@ use serde_json::Map;
|
||||
use serde_json::Value;
|
||||
|
||||
/// Projects privileged capabilities only to their intended recipients.
|
||||
/// Verification requires the host-owned plugin service; network policy requires a trusted
|
||||
/// ChatGPT origin. Server names and caller-supplied capabilities do not grant either privilege.
|
||||
/// Verification requires the host-owned plugin service. Network policy metadata is only
|
||||
/// ever offered to trusted hosted origins, which aKode never connects to, so it is
|
||||
/// stripped for every server. Server names and caller-supplied capabilities grant neither.
|
||||
pub(crate) fn server_mcp_extensions(
|
||||
extensions: &ClientMcpExtensions,
|
||||
server_name: &str,
|
||||
server: Option<&crate::catalog::ResolvedMcpServer>,
|
||||
advertise_network_policy: bool,
|
||||
chatgpt_base_url: &str,
|
||||
) -> ClientMcpExtensions {
|
||||
let plugin_service = server.is_some_and(|server| {
|
||||
server
|
||||
.source()
|
||||
.is_host_owned_apps(server_name, server.config())
|
||||
});
|
||||
let network_policy = advertise_network_policy
|
||||
&& server.is_some_and(|server| {
|
||||
crate::mcp::is_trusted_chatgpt_mcp_server(&server.config().transport, chatgpt_base_url)
|
||||
});
|
||||
ClientMcpExtensions::new(
|
||||
extensions
|
||||
.iter()
|
||||
@@ -40,13 +35,7 @@ pub(crate) fn server_mcp_extensions(
|
||||
settings.remove("userVerification");
|
||||
}
|
||||
(id.to_string(), settings)
|
||||
})
|
||||
.chain(network_policy.then(|| {
|
||||
(
|
||||
crate::MCP_NETWORK_POLICY_META_CAPABILITY.to_string(),
|
||||
Value::Object(Map::new()),
|
||||
)
|
||||
})),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -85,8 +85,6 @@ fn user_verification_is_projected_only_to_the_host_owned_plugin_service() {
|
||||
&extensions,
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
/*server*/ None,
|
||||
/*advertise_network_policy*/ true,
|
||||
"https://chatgpt.com",
|
||||
),
|
||||
ClientMcpExtensions::new([(
|
||||
OPENAI_ELICITATION_EXTENSION_ID.to_string(),
|
||||
@@ -143,8 +141,6 @@ fn user_verification_is_projected_only_to_the_host_owned_plugin_service() {
|
||||
&extensions,
|
||||
name,
|
||||
catalog.server(name),
|
||||
/*advertise_network_policy*/ false,
|
||||
"https://chatgpt.com",
|
||||
),
|
||||
ClientMcpExtensions::new([(OPENAI_ELICITATION_EXTENSION_ID.to_string(), settings)]),
|
||||
);
|
||||
|
||||
@@ -22,7 +22,6 @@ mod status;
|
||||
#[path = "connection_manager/tool_catalog.rs"]
|
||||
mod tool_catalog;
|
||||
|
||||
use startup::chatgpt_auth_provider_for_server;
|
||||
use startup::emit_update;
|
||||
use startup::mcp_init_error_display;
|
||||
use startup::mcp_startup_failure_reason;
|
||||
@@ -65,8 +64,6 @@ use crate::server::McpServerMetadata;
|
||||
use crate::tools::ToolFilter;
|
||||
use crate::tools::ToolInfo;
|
||||
use crate::tools::filter_tools;
|
||||
use crate::trusted_access::ENTITLEMENT_CONTEXT_KEY;
|
||||
use crate::trusted_access::TrustedAccessContext;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
@@ -94,6 +91,9 @@ use tokio::sync::watch;
|
||||
use tokio::task::JoinSet;
|
||||
use tracing::warn;
|
||||
|
||||
/// Host-owned entitlement metadata that direct callers may never supply.
|
||||
const ENTITLEMENT_CONTEXT_KEY: &str = "openai/entitlementContext";
|
||||
|
||||
static LIVE_CONNECTIONS: Gauge = Gauge::new("mcp.connections.live");
|
||||
|
||||
pub(crate) struct McpServerConnection {
|
||||
@@ -344,7 +344,6 @@ pub(crate) struct McpConnectionSet {
|
||||
prefix_mcp_tool_names: bool,
|
||||
non_prefixed_mcp_tool_servers: Vec<String>,
|
||||
elicitation_requests: ElicitationRequestManager,
|
||||
pub(crate) trusted_access: Option<TrustedAccessContext>,
|
||||
}
|
||||
|
||||
impl McpConnectionSet {
|
||||
@@ -360,7 +359,6 @@ impl McpConnectionSet {
|
||||
) -> Self {
|
||||
let same_owner = previous.as_ref().is_some_and(|state| state.same_owner);
|
||||
let previous = previous.map(|state| state.connections);
|
||||
let trusted_access = TrustedAccessContext::from_runtime(&input);
|
||||
let McpRuntimeInput {
|
||||
startup_policy,
|
||||
config,
|
||||
@@ -378,7 +376,6 @@ impl McpConnectionSet {
|
||||
client_mcp_extensions,
|
||||
auth,
|
||||
auth_manager,
|
||||
runtime_auth,
|
||||
elicitation_reviewer,
|
||||
elicitation_lifecycle,
|
||||
} = input;
|
||||
@@ -442,17 +439,6 @@ impl McpConnectionSet {
|
||||
};
|
||||
let tool_plugin_context = Arc::new(tool_plugin_context);
|
||||
let startup_submit_id = submit_id;
|
||||
let static_chatgpt_auth_provider = auth
|
||||
.filter(|auth| auth.uses_codex_backend())
|
||||
.map(codex_model_provider::auth_provider_from_auth);
|
||||
let codex_apps_auth_provider = auth_manager.as_ref().and_then(|auth_manager| {
|
||||
auth.filter(|auth| auth.uses_codex_backend()).map(|auth| {
|
||||
codex_model_provider::auth_provider_from_auth_manager(
|
||||
Arc::clone(auth_manager),
|
||||
auth,
|
||||
)
|
||||
})
|
||||
});
|
||||
for (server_name, server) in mcp_servers
|
||||
.into_iter()
|
||||
.filter(|(_, server)| server.enabled())
|
||||
@@ -463,8 +449,6 @@ impl McpConnectionSet {
|
||||
&client_mcp_extensions,
|
||||
&server_name,
|
||||
registration,
|
||||
network_policy_metadata.is_some(),
|
||||
&config.chatgpt_base_url,
|
||||
);
|
||||
let is_host_owned_codex_apps = registration.is_some_and(|server| {
|
||||
server
|
||||
@@ -546,17 +530,6 @@ impl McpConnectionSet {
|
||||
&& should_share_codex_apps_tools_cache(&server_name, uses_env_bearer_token);
|
||||
let shares_codex_apps_tools_cache =
|
||||
eligible_for_apps_cache && codex_apps_tools_cache.shares_snapshot();
|
||||
let openai_runtime = runtime_auth.as_ref().filter(|_| {
|
||||
!uses_env_bearer_token
|
||||
&& configured_config.is_local_environment()
|
||||
&& matches!(configured_config.auth, codex_config::McpServerAuth::ChatGpt)
|
||||
&& auth.is_some_and(codex_login::CodexAuth::uses_codex_backend)
|
||||
&& matches!(&configured_config.transport,
|
||||
McpServerTransportConfig::StreamableHttp { url, .. }
|
||||
if codex_http_client::classify_openai_api_url(url)
|
||||
!= codex_http_client::OpenAiDestination::Other)
|
||||
});
|
||||
let runtime_auth_mode = openai_runtime.map(|(_, mode)| *mode);
|
||||
let codex_apps_tools_cache_context = shares_codex_apps_tools_cache.then(|| {
|
||||
// Only equivalent discovery inputs may share executable Apps tools.
|
||||
let mut transport = configured_config.transport.clone();
|
||||
@@ -572,7 +545,6 @@ impl McpConnectionSet {
|
||||
let mut scope = serde_json::json!([
|
||||
transport,
|
||||
&configured_config.auth,
|
||||
runtime_auth_mode,
|
||||
protocol_mode.preferred_protocol_version().as_str(),
|
||||
catalog_item_limit,
|
||||
&client_elicitation_capability,
|
||||
@@ -585,34 +557,8 @@ impl McpConnectionSet {
|
||||
.context(codex_home.clone(), codex_apps_tools_cache_key.clone())
|
||||
.with_live_scope(scope.to_string())
|
||||
});
|
||||
// The reserved Codex Apps registration follows the shared
|
||||
// AuthManager across refreshes. In the hosted-plugin path, this
|
||||
// is the ChatGPT /ps/mcp connection. User-configured MCP
|
||||
// registrations keep their existing configured auth path.
|
||||
let chatgpt_auth_provider = if server_name == CODEX_APPS_MCP_SERVER_NAME {
|
||||
codex_apps_auth_provider
|
||||
.clone()
|
||||
.or_else(|| static_chatgpt_auth_provider.clone())
|
||||
} else {
|
||||
static_chatgpt_auth_provider.clone()
|
||||
};
|
||||
// If Codex Apps has an env bearer token, that is its auth path. Do
|
||||
// not also attach the ambient CodexAuth provider.
|
||||
let runtime_auth_provider =
|
||||
if server_name == CODEX_APPS_MCP_SERVER_NAME && uses_env_bearer_token {
|
||||
None
|
||||
} else {
|
||||
chatgpt_auth_provider_for_server(&server, chatgpt_auth_provider).map(
|
||||
|provider| match (openai_runtime, auth) {
|
||||
(Some(runtime), Some(auth)) => {
|
||||
crate::auth::McpAuthProvider::runtime(runtime.clone(), auth.clone())
|
||||
}
|
||||
_ => crate::auth::McpAuthProvider::Credentials(provider),
|
||||
},
|
||||
)
|
||||
};
|
||||
let discover_local_stdio = config.discover_local_stdio
|
||||
&& server.can_discover_local_stdio(&server_name, runtime_auth_provider.as_ref());
|
||||
let discover_local_stdio =
|
||||
config.discover_local_stdio && server.can_discover_local_stdio(&server_name);
|
||||
let protocol_mode = if discover_local_stdio {
|
||||
McpProtocolMode::DiscoverLocalStdio
|
||||
} else {
|
||||
@@ -626,7 +572,6 @@ impl McpConnectionSet {
|
||||
oauth_refresh_mode,
|
||||
runtime_context: runtime_context.clone(),
|
||||
resolved_environment: resolved_environment.clone(),
|
||||
auth_provider: runtime_auth_provider.clone(),
|
||||
auth_manager: auth_manager.clone(),
|
||||
auth: auth.cloned(),
|
||||
protocol_mode,
|
||||
@@ -642,9 +587,6 @@ impl McpConnectionSet {
|
||||
oauth_refresh_mode,
|
||||
&resolved_environment,
|
||||
&runtime_context,
|
||||
runtime_auth_provider.as_ref(),
|
||||
runtime_auth_mode,
|
||||
auth,
|
||||
eligible_for_apps_cache
|
||||
.then(|| (codex_home.clone(), codex_apps_tools_cache_key.clone())),
|
||||
client_elicitation_capability.clone(),
|
||||
@@ -888,7 +830,6 @@ impl McpConnectionSet {
|
||||
}
|
||||
let cancel_token = startup_cancellation_token.child_token();
|
||||
let tool_catalog_cache_context = tool_catalog_cache_context.take();
|
||||
let has_runtime_auth = runtime_auth_provider.is_some();
|
||||
let connection_pool = connection_pool.map(|pool| {
|
||||
(
|
||||
pool.clone(),
|
||||
@@ -929,7 +870,6 @@ impl McpConnectionSet {
|
||||
tool_catalog_cache_context,
|
||||
runtime_context.clone(),
|
||||
resolved_environment,
|
||||
runtime_auth_provider,
|
||||
client_elicitation_capability.clone(),
|
||||
client_mcp_extensions.clone(),
|
||||
auth_manager
|
||||
@@ -1015,7 +955,6 @@ impl McpConnectionSet {
|
||||
let auth_state = match &outcome {
|
||||
Err(error)
|
||||
if error.is_authentication_required()
|
||||
&& !has_runtime_auth
|
||||
&& !matches!(configured_config.auth, McpServerAuth::EmaAuth) =>
|
||||
{
|
||||
match &configured_config.transport {
|
||||
@@ -1112,7 +1051,6 @@ impl McpConnectionSet {
|
||||
prefix_mcp_tool_names,
|
||||
non_prefixed_mcp_tool_servers,
|
||||
elicitation_requests: elicitation_requests.clone(),
|
||||
trusted_access,
|
||||
};
|
||||
tokio::spawn(async move {
|
||||
if !publication_gate.wait().await {
|
||||
@@ -1189,7 +1127,6 @@ impl McpConnectionSet {
|
||||
prefix_mcp_tool_names,
|
||||
non_prefixed_mcp_tool_servers: Vec::new(),
|
||||
elicitation_requests: ElicitationRequestManager::default(),
|
||||
trusted_access: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -87,12 +87,14 @@ impl NetworkPolicyMetadataProvider for CapturedPolicy {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tool_calls_deliver_only_negotiated_trusted_network_policy() -> anyhow::Result<()> {
|
||||
async fn tool_calls_never_deliver_network_policy_and_strip_forged_metadata() -> anyhow::Result<()> {
|
||||
// Network policy metadata was only offered to trusted ChatGPT origins, which aKode never
|
||||
// connects to, so no server receives it and forged caller metadata is always stripped.
|
||||
for (url, provider_available, supports_policy, delivers_policy) in [
|
||||
(Some("https://chatgpt.com/mcp"), true, true, true),
|
||||
(Some("https://chatgpt.com/mcp"), true, true, false),
|
||||
(Some("https://chatgpt.com/mcp"), true, false, false),
|
||||
(Some("https://chatgpt.com/mcp"), false, true, false),
|
||||
(Some("https://gov.chatgpt.com/mcp"), true, true, true),
|
||||
(Some("https://gov.chatgpt.com/mcp"), true, true, false),
|
||||
(
|
||||
Some("https://chatgpt.com.attacker.example/mcp"),
|
||||
true,
|
||||
@@ -126,8 +128,6 @@ async fn tool_calls_deliver_only_negotiated_trusted_network_policy() -> anyhow::
|
||||
)]),
|
||||
"docs",
|
||||
catalog.server("docs"),
|
||||
provider_available,
|
||||
"https://chatgpt.com",
|
||||
);
|
||||
let client_supports_policy = extensions
|
||||
.iter()
|
||||
|
||||
@@ -2,7 +2,6 @@ use std::collections::HashMap;
|
||||
|
||||
use anyhow::Result;
|
||||
use async_channel::Sender;
|
||||
use codex_api::SharedAuthProvider;
|
||||
use codex_config::McpServerAuth;
|
||||
use codex_config::McpServerConfig;
|
||||
use codex_config::McpServerTransportConfig;
|
||||
@@ -16,20 +15,6 @@ use codex_rmcp_client::McpLoginRequirement;
|
||||
use crate::mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use crate::rmcp_client::DEFAULT_STARTUP_TIMEOUT;
|
||||
use crate::rmcp_client::StartupOutcomeError;
|
||||
use crate::server::EffectiveMcpServer;
|
||||
|
||||
/// Makes ChatGPT authentication available to servers that explicitly opt in.
|
||||
pub(super) fn chatgpt_auth_provider_for_server(
|
||||
server: &EffectiveMcpServer,
|
||||
chatgpt_auth_provider: Option<SharedAuthProvider>,
|
||||
) -> Option<SharedAuthProvider> {
|
||||
if !matches!(&server.config().auth, McpServerAuth::ChatGpt)
|
||||
|| !server.config().is_local_environment()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
chatgpt_auth_provider
|
||||
}
|
||||
|
||||
pub(super) fn should_share_codex_apps_tools_cache(
|
||||
server_name: &str,
|
||||
|
||||
@@ -40,14 +40,8 @@ use codex_connectors::ConnectorRuntimeContext;
|
||||
use codex_connectors::ConnectorRuntimeContextKey;
|
||||
use codex_connectors::ConnectorRuntimeFetchSource;
|
||||
use codex_connectors::ConnectorRuntimeManager;
|
||||
use codex_exec_server::ExecServerError;
|
||||
use codex_exec_server::HttpClient;
|
||||
use codex_exec_server::HttpRequestParams;
|
||||
use codex_exec_server::HttpRequestResponse;
|
||||
use codex_exec_server::HttpResponseBodyStream;
|
||||
use codex_exec_server_test_support::environment_manager_without_environments;
|
||||
use codex_login::AuthHeaders;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_protocol::ToolName;
|
||||
use codex_protocol::approvals::ElicitationRequest;
|
||||
@@ -128,7 +122,6 @@ impl McpConnectionSet {
|
||||
/*lifecycle*/ None,
|
||||
ElicitationRequestRouter::default(),
|
||||
),
|
||||
trusted_access: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -257,24 +250,6 @@ fn create_test_server_info(title: &str) -> McpServerInfo {
|
||||
|
||||
struct TestInProcessTransportFactory;
|
||||
|
||||
struct PendingHttpClient;
|
||||
|
||||
impl HttpClient for PendingHttpClient {
|
||||
fn http_request(
|
||||
&self,
|
||||
_params: HttpRequestParams,
|
||||
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
|
||||
futures::future::pending().boxed()
|
||||
}
|
||||
|
||||
fn http_request_stream(
|
||||
&self,
|
||||
_params: HttpRequestParams,
|
||||
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
|
||||
futures::future::pending().boxed()
|
||||
}
|
||||
}
|
||||
|
||||
impl InProcessTransportFactory for TestInProcessTransportFactory {
|
||||
fn open(&self) -> BoxFuture<'static, io::Result<DuplexStream>> {
|
||||
async {
|
||||
@@ -525,86 +500,6 @@ async fn create_test_managed_client(tools: Vec<ToolInfo>) -> ManagedClient {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn prepared_call_timeout_includes_trusted_access_lookup() {
|
||||
let mut tool = create_test_tool("docs", "access");
|
||||
tool.tool.annotations = Some(rmcp::model::ToolAnnotations::new().read_only(true));
|
||||
let mut tool_meta = rmcp::model::MetaObject::new();
|
||||
tool_meta.insert(
|
||||
"openai/requestedEntitlements".to_string(),
|
||||
serde_json::json!(["cyber_trusted_access"]),
|
||||
);
|
||||
tool.tool.meta = Some(tool_meta);
|
||||
|
||||
let approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
|
||||
let permission_profile = Constrained::allow_any(PermissionProfile::default());
|
||||
let mut manager = McpConnectionSet::new_uninitialized(
|
||||
&approval_policy,
|
||||
&permission_profile,
|
||||
/*prefix_mcp_tool_names*/ true,
|
||||
);
|
||||
let mut config = crate::mcp::tests::test_mcp_config(std::env::temp_dir());
|
||||
let mut catalog = crate::ResolvedMcpCatalog::builder();
|
||||
catalog.register(crate::McpServerRegistration::from_plugin(
|
||||
"docs".to_string(),
|
||||
crate::McpPluginAttribution::new("docs@test".to_string(), "Docs".to_string()),
|
||||
/*plugin_order*/ 0,
|
||||
serde_json::from_value(serde_json::json!({ "command": "docs" }))
|
||||
.expect("plugin MCP config"),
|
||||
));
|
||||
config.mcp_server_catalog = catalog.build();
|
||||
config
|
||||
.server_permissions
|
||||
.insert("docs".to_string(), McpServerPermissions::Thread);
|
||||
manager.tool_plugin_context = Arc::new(crate::tool_plugin_context(&config));
|
||||
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
|
||||
manager.trusted_access = Some(TrustedAccessContext::new(
|
||||
auth.clone(),
|
||||
AuthManager::from_auth_for_testing(auth),
|
||||
"https://chatgpt.com/backend-api".to_string(),
|
||||
Arc::new(PendingHttpClient),
|
||||
));
|
||||
let manager = Arc::new(manager);
|
||||
let server_metadata = McpServerMetadata {
|
||||
environment_id: codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
|
||||
pollutes_memory: true,
|
||||
origin: Some(McpServerOrigin::Stdio),
|
||||
supports_parallel_tool_calls: false,
|
||||
default_tools_approval_mode: None,
|
||||
tool_approval_modes: HashMap::new(),
|
||||
};
|
||||
let client = Arc::new(create_test_managed_client(vec![tool.clone()]).await);
|
||||
let catalog_snapshot = client.tool_catalog.read(Arc::new).await;
|
||||
let prepared = crate::PreparedMcpCall::new(
|
||||
manager,
|
||||
client,
|
||||
Arc::new(config),
|
||||
catalog_snapshot,
|
||||
tool,
|
||||
server_metadata,
|
||||
Some("docs@test".to_string()),
|
||||
/*selected_plugin_server*/ false,
|
||||
)
|
||||
.expect("docs should retain its permission profile");
|
||||
|
||||
let started = tokio::time::Instant::now();
|
||||
let error = prepared
|
||||
.call(
|
||||
Some(serde_json::json!({})),
|
||||
/*meta*/ None,
|
||||
Some(Duration::from_secs(1)),
|
||||
)
|
||||
.await
|
||||
.expect_err("trusted access lookup should consume the call timeout");
|
||||
|
||||
assert_eq!(started.elapsed(), Duration::from_secs(1));
|
||||
assert!(format!("{error:#}").contains("timed out awaiting tools/call after 1s"));
|
||||
assert_eq!(
|
||||
codex_rmcp_client::request_error_code(&error),
|
||||
Some("request_timeout")
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) async fn create_ready_async_managed_client(tools: Vec<ToolInfo>) -> AsyncManagedClient {
|
||||
AsyncManagedClient {
|
||||
ema_authority: None,
|
||||
@@ -2147,7 +2042,6 @@ async fn shared_apps_snapshot_requires_writable_discovery_and_a_shared_cache() -
|
||||
McpPublicationGate::already_published(),
|
||||
McpRuntimeInput {
|
||||
network_policy_metadata: None,
|
||||
runtime_auth: None,
|
||||
startup_policy: McpStartupPolicy::Eager,
|
||||
config: Arc::new(config),
|
||||
plugins_available: false,
|
||||
@@ -2228,7 +2122,6 @@ async fn hosted_apps_protocol_mode_is_independent_of_generic_mode() -> anyhow::R
|
||||
McpPublicationGate::already_published(),
|
||||
McpRuntimeInput {
|
||||
network_policy_metadata: None,
|
||||
runtime_auth: None,
|
||||
startup_policy: McpStartupPolicy::Eager,
|
||||
config: Arc::new(config),
|
||||
plugins_available: false,
|
||||
@@ -2400,7 +2293,6 @@ async fn codex_apps_extension_does_not_share_host_owned_tools_cache() -> anyhow:
|
||||
McpPublicationGate::already_published(),
|
||||
McpRuntimeInput {
|
||||
network_policy_metadata: None,
|
||||
runtime_auth: None,
|
||||
startup_policy: McpStartupPolicy::Eager,
|
||||
config: Arc::new(config),
|
||||
plugins_available: false,
|
||||
@@ -4738,95 +4630,6 @@ fn server_metadata_preserves_tool_approval_policy() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hosted_actor_credentials_are_only_available_to_host_owned_mcp_servers() {
|
||||
let bootstrap_auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
|
||||
let mut actor_headers = Default::default();
|
||||
codex_model_provider::auth_provider_from_auth(&bootstrap_auth)
|
||||
.add_auth_headers(&mut actor_headers)
|
||||
.unwrap();
|
||||
actor_headers.insert(
|
||||
"x-openai-actor-authorization",
|
||||
"hosted-actor-secret"
|
||||
.parse()
|
||||
.expect("valid actor authorization header"),
|
||||
);
|
||||
let hosted_auth = CodexAuth::Headers(AuthHeaders::new(actor_headers));
|
||||
let provider = codex_model_provider::auth_provider_from_auth(&hosted_auth);
|
||||
let mut local_config = crate::mcp::test_http_mcp_server_config("https://chatgpt.com");
|
||||
local_config.auth = McpServerAuth::ChatGpt;
|
||||
|
||||
let local_server = EffectiveMcpServer::from_host_config(local_config.clone());
|
||||
let local_provider =
|
||||
chatgpt_auth_provider_for_server(&local_server, Some(Arc::clone(&provider)))
|
||||
.expect("host-owned Codex Apps must retain hosted authentication");
|
||||
assert_eq!(
|
||||
local_provider
|
||||
.to_auth_headers()
|
||||
.unwrap()
|
||||
.get("x-openai-actor-authorization")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("hosted-actor-secret")
|
||||
);
|
||||
|
||||
let mut remote_config = local_config;
|
||||
remote_config.environment_id = "customer-executor".to_string();
|
||||
let remote_server = EffectiveMcpServer::from_host_config(remote_config);
|
||||
assert!(
|
||||
chatgpt_auth_provider_for_server(&remote_server, Some(provider)).is_none(),
|
||||
"customer-owned executors must never receive hosted actor credentials"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gov_codex_apps_retain_local_chatgpt_auth_provider() -> anyhow::Result<()> {
|
||||
let codex_home = tempdir()?;
|
||||
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
|
||||
let provider = codex_model_provider::auth_provider_from_auth(&auth);
|
||||
let mut config = crate::mcp::tests::test_mcp_config(codex_home.path().to_path_buf());
|
||||
config.chatgpt_base_url = "https://gov.chatgpt.com/backend-api/".to_string();
|
||||
config.apps_enabled = true;
|
||||
|
||||
let mut local_config =
|
||||
crate::mcp::test_http_mcp_server_config("https://gov.chatgpt.com/backend-api/ps/mcp");
|
||||
local_config.auth = McpServerAuth::ChatGpt;
|
||||
let mut remote_config = local_config.clone();
|
||||
remote_config.environment_id = "customer-executor".to_string();
|
||||
let mut custom_oauth = local_config.clone();
|
||||
custom_oauth.auth = McpServerAuth::OAuth;
|
||||
|
||||
let mut catalog = crate::ResolvedMcpCatalog::builder();
|
||||
catalog.register(crate::McpServerRegistration::from_hosted_apps(
|
||||
"test-host",
|
||||
/*contribution_order*/ 0,
|
||||
local_config,
|
||||
));
|
||||
catalog.register(crate::McpServerRegistration::from_config(
|
||||
"custom-oauth".to_string(),
|
||||
custom_oauth,
|
||||
));
|
||||
catalog.register(crate::McpServerRegistration::from_config(
|
||||
"remote-gov".to_string(),
|
||||
remote_config,
|
||||
));
|
||||
config.mcp_server_catalog = catalog.build();
|
||||
|
||||
let servers = crate::effective_mcp_servers(&config, Some(&auth));
|
||||
// aKode never connects to the ChatGPT-hosted apps MCP server.
|
||||
assert!(!servers.contains_key(CODEX_APPS_MCP_SERVER_NAME));
|
||||
|
||||
assert_eq!(servers["custom-oauth"].config().auth, McpServerAuth::OAuth);
|
||||
assert_eq!(servers["remote-gov"].config().auth, McpServerAuth::ChatGpt);
|
||||
for name in ["custom-oauth", "remote-gov"] {
|
||||
assert!(
|
||||
chatgpt_auth_provider_for_server(&servers[name], Some(Arc::clone(&provider))).is_none(),
|
||||
"{name} must not receive the host ChatGPT provider"
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn executor_owned_chatgpt_mcp_accepts_only_safe_explicit_authorization() -> anyhow::Result<()>
|
||||
{
|
||||
@@ -4839,7 +4642,7 @@ async fn executor_owned_chatgpt_mcp_accepts_only_safe_explicit_authorization() -
|
||||
)?;
|
||||
let runtime_context =
|
||||
McpRuntimeContext::new(Arc::clone(&environment_manager), PathBuf::from("/tmp"));
|
||||
let bootstrap_auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
|
||||
let bootstrap_auth = CodexAuth::from_api_key("hosted-bootstrap-key");
|
||||
let mut actor_headers = Default::default();
|
||||
codex_model_provider::auth_provider_from_auth(&bootstrap_auth)
|
||||
.add_auth_headers(&mut actor_headers)
|
||||
@@ -4939,14 +4742,6 @@ async fn executor_owned_chatgpt_mcp_accepts_only_safe_explicit_authorization() -
|
||||
McpServerAuth::ChatGpt
|
||||
));
|
||||
let remote_server = &mcp_servers["fake-first-party"];
|
||||
assert!(
|
||||
chatgpt_auth_provider_for_server(
|
||||
remote_server,
|
||||
Some(codex_model_provider::auth_provider_from_auth(&hosted_auth)),
|
||||
)
|
||||
.is_none(),
|
||||
"{case}: executor-owned servers must never receive hosted actor credentials"
|
||||
);
|
||||
let resolved_environment =
|
||||
runtime_context.resolve_server_environment("fake-first-party", remote_server.config());
|
||||
let connection_identity = |keyring_backend_kind| {
|
||||
@@ -4959,9 +4754,6 @@ async fn executor_owned_chatgpt_mcp_accepts_only_safe_explicit_authorization() -
|
||||
McpOAuthRefreshMode::Legacy,
|
||||
&resolved_environment,
|
||||
&runtime_context,
|
||||
/*runtime_auth_provider*/ None,
|
||||
/*runtime_auth_mode*/ None,
|
||||
Some(&hosted_auth),
|
||||
/*codex_apps_cache_identity*/ None,
|
||||
ElicitationCapability::default(),
|
||||
ClientMcpExtensions::default(),
|
||||
@@ -4986,8 +4778,6 @@ async fn executor_owned_chatgpt_mcp_accepts_only_safe_explicit_authorization() -
|
||||
OAuthCredentialsStoreMode::default(),
|
||||
AuthKeyringBackendKind::default(),
|
||||
Some(&hosted_auth),
|
||||
/*auth_manager*/ None,
|
||||
&crate::EmaState::default(),
|
||||
&runtime_context,
|
||||
)
|
||||
.await;
|
||||
@@ -5008,7 +4798,6 @@ async fn executor_owned_chatgpt_mcp_accepts_only_safe_explicit_authorization() -
|
||||
McpPublicationGate::already_published(),
|
||||
McpRuntimeInput {
|
||||
network_policy_metadata: None,
|
||||
runtime_auth: None,
|
||||
startup_policy: McpStartupPolicy::Eager,
|
||||
config: Arc::new(runtime_config.clone()),
|
||||
plugins_available: false,
|
||||
@@ -5130,7 +4919,6 @@ async fn no_local_runtime_fails_local_stdio_but_keeps_local_http_server() {
|
||||
McpPublicationGate::already_published(),
|
||||
McpRuntimeInput {
|
||||
network_policy_metadata: None,
|
||||
runtime_auth: None,
|
||||
startup_policy: McpStartupPolicy::Eager,
|
||||
config: Arc::new(crate::mcp::tests::test_mcp_config(
|
||||
codex_home.path().to_path_buf(),
|
||||
@@ -5510,9 +5298,6 @@ pub(crate) fn reusable_server_identity(
|
||||
McpOAuthRefreshMode::Legacy,
|
||||
&resolved_environment,
|
||||
runtime_context,
|
||||
/*runtime_auth_provider*/ None,
|
||||
/*runtime_auth_mode*/ None,
|
||||
/*auth*/ None,
|
||||
/*codex_apps_cache_identity*/ None,
|
||||
ElicitationCapability::default(),
|
||||
ClientMcpExtensions::default(),
|
||||
@@ -5594,7 +5379,6 @@ async fn reconcile_reusable_server_with_mcp_config(
|
||||
McpPublicationGate::already_published(),
|
||||
McpRuntimeInput {
|
||||
network_policy_metadata: None,
|
||||
runtime_auth: None,
|
||||
startup_policy: McpStartupPolicy::Eager,
|
||||
config: Arc::new(mcp_config),
|
||||
plugins_available: false,
|
||||
@@ -6334,9 +6118,6 @@ fn connection_identity_tracks_only_oauth_credentials_when_oauth_is_active() {
|
||||
McpOAuthRefreshMode::Legacy,
|
||||
&Ok(None),
|
||||
&runtime_context,
|
||||
/*runtime_auth_provider*/ None,
|
||||
/*runtime_auth_mode*/ None,
|
||||
/*auth*/ None,
|
||||
/*codex_apps_cache_identity*/ None,
|
||||
ElicitationCapability::default(),
|
||||
ClientMcpExtensions::default(),
|
||||
@@ -6417,9 +6198,6 @@ fn connection_identity_uses_effective_authorization_headers() {
|
||||
oauth_refresh_mode,
|
||||
&Ok(None),
|
||||
&runtime_context,
|
||||
/*runtime_auth_provider*/ None,
|
||||
/*runtime_auth_mode*/ None,
|
||||
/*auth*/ None,
|
||||
/*codex_apps_cache_identity*/ None,
|
||||
ElicitationCapability::default(),
|
||||
ClientMcpExtensions::default(),
|
||||
@@ -6569,7 +6347,6 @@ async fn reconciliation_replaces_connection_when_protocol_mode_changes() {
|
||||
McpPublicationGate::already_published(),
|
||||
McpRuntimeInput {
|
||||
network_policy_metadata: None,
|
||||
runtime_auth: None,
|
||||
startup_policy: McpStartupPolicy::Eager,
|
||||
config: Arc::new(mcp_config),
|
||||
plugins_available: false,
|
||||
@@ -6634,7 +6411,6 @@ async fn reconciliation_reuses_legacy_stdio_server_when_modern_protocol_is_enabl
|
||||
McpPublicationGate::already_published(),
|
||||
McpRuntimeInput {
|
||||
network_policy_metadata: None,
|
||||
runtime_auth: None,
|
||||
startup_policy: McpStartupPolicy::Eager,
|
||||
config: Arc::new(mcp_config),
|
||||
plugins_available: false,
|
||||
@@ -6915,9 +6691,6 @@ async fn reconciliation_reconnects_when_host_plugin_root_changes() {
|
||||
McpOAuthRefreshMode::Legacy,
|
||||
&resolved_environment,
|
||||
&runtime_context,
|
||||
/*runtime_auth_provider*/ None,
|
||||
/*runtime_auth_mode*/ None,
|
||||
/*auth*/ None,
|
||||
/*codex_apps_cache_identity*/ None,
|
||||
ElicitationCapability::default(),
|
||||
ClientMcpExtensions::default(),
|
||||
@@ -6970,136 +6743,6 @@ async fn reconciliation_reconnects_when_host_plugin_root_changes() {
|
||||
assert!(!unchanged.shares_test_connection_with(&replacement, "docs"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn connection_identity_distinguishes_accounts_with_the_same_token() -> anyhow::Result<()> {
|
||||
let runtime_context = reusable_server_runtime_context();
|
||||
let config = reusable_server_config("http://127.0.0.1:1");
|
||||
let server = EffectiveMcpServer::from_host_config(config);
|
||||
let access_token = "header.e30.same";
|
||||
let previous_auth = CodexAuth::from_external_chatgpt_tokens(
|
||||
access_token,
|
||||
"account-a",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?;
|
||||
let changed_auth = CodexAuth::from_external_chatgpt_tokens(
|
||||
access_token,
|
||||
"account-b",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?;
|
||||
let connection_identity = |auth: &CodexAuth| {
|
||||
let provider = codex_model_provider::auth_provider_from_auth(auth);
|
||||
McpServerConnectionIdentity::new(
|
||||
"docs",
|
||||
&server,
|
||||
/*host_plugin_root*/ None,
|
||||
OAuthCredentialsStoreMode::default(),
|
||||
AuthKeyringBackendKind::default(),
|
||||
McpOAuthRefreshMode::Legacy,
|
||||
&Ok(None),
|
||||
&runtime_context,
|
||||
Some(&crate::auth::McpAuthProvider::Credentials(provider)),
|
||||
/*runtime_auth_mode*/ None,
|
||||
Some(auth),
|
||||
/*codex_apps_cache_identity*/ None,
|
||||
ElicitationCapability::default(),
|
||||
ClientMcpExtensions::default(),
|
||||
/*previous_identity*/ None,
|
||||
)
|
||||
};
|
||||
|
||||
assert_eq!(previous_auth, changed_auth);
|
||||
assert_eq!(previous_auth.get_token()?, changed_auth.get_token()?);
|
||||
assert!(
|
||||
!connection_identity(&previous_auth)
|
||||
.has_same_connection_config(&connection_identity(&changed_auth))
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn connection_identity_distinguishes_agent_account_runtime_and_task() -> anyhow::Result<()> {
|
||||
let runtime_context = reusable_server_runtime_context();
|
||||
let config = reusable_server_config("http://127.0.0.1:1");
|
||||
let server = EffectiveMcpServer::from_host_config(config);
|
||||
let record = codex_login::auth::AgentIdentityAuthRecord {
|
||||
agent_runtime_id: "agent-a".to_string(),
|
||||
agent_private_key: "MC4CAQAwBQYDK2VwBCIEIJ7kFBaOujmoz1gvBNEC+BeM2IX87FFB0xmISOZ/XO0c"
|
||||
.to_string(),
|
||||
account_id: "account-a".to_string(),
|
||||
chatgpt_user_id: "user-a".to_string(),
|
||||
email: Some("agent@example.com".to_string()),
|
||||
plan_type: codex_protocol::account::PlanType::Plus,
|
||||
chatgpt_account_is_fedramp: false,
|
||||
task_id: Some("task-a".to_string()),
|
||||
};
|
||||
let auth_route_config = codex_login::test_support::transport_default_auth_route_config();
|
||||
let previous_auth = CodexAuth::AgentIdentity(
|
||||
codex_login::auth::AgentIdentityAuth::from_record(
|
||||
record.clone(),
|
||||
"https://auth.openai.com/api/accounts",
|
||||
&auth_route_config,
|
||||
)
|
||||
.await?,
|
||||
);
|
||||
let connection_identity = |auth: &CodexAuth| {
|
||||
let provider = codex_model_provider::auth_provider_from_auth(auth);
|
||||
McpServerConnectionIdentity::new(
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
&server,
|
||||
/*host_plugin_root*/ None,
|
||||
OAuthCredentialsStoreMode::default(),
|
||||
AuthKeyringBackendKind::default(),
|
||||
McpOAuthRefreshMode::Legacy,
|
||||
&Ok(None),
|
||||
&runtime_context,
|
||||
Some(&crate::auth::McpAuthProvider::Credentials(provider)),
|
||||
/*runtime_auth_mode*/ None,
|
||||
Some(auth),
|
||||
/*codex_apps_cache_identity*/ None,
|
||||
ElicitationCapability::default(),
|
||||
ClientMcpExtensions::default(),
|
||||
/*previous_identity*/ None,
|
||||
)
|
||||
};
|
||||
let previous_identity = connection_identity(&previous_auth);
|
||||
|
||||
for changed_record in [
|
||||
codex_login::auth::AgentIdentityAuthRecord {
|
||||
account_id: "account-b".to_string(),
|
||||
..record.clone()
|
||||
},
|
||||
codex_login::auth::AgentIdentityAuthRecord {
|
||||
chatgpt_user_id: "user-b".to_string(),
|
||||
..record.clone()
|
||||
},
|
||||
codex_login::auth::AgentIdentityAuthRecord {
|
||||
chatgpt_account_is_fedramp: true,
|
||||
..record.clone()
|
||||
},
|
||||
codex_login::auth::AgentIdentityAuthRecord {
|
||||
agent_runtime_id: "agent-b".to_string(),
|
||||
..record.clone()
|
||||
},
|
||||
codex_login::auth::AgentIdentityAuthRecord {
|
||||
task_id: Some("task-b".to_string()),
|
||||
..record.clone()
|
||||
},
|
||||
] {
|
||||
let changed_auth = CodexAuth::AgentIdentity(
|
||||
codex_login::auth::AgentIdentityAuth::from_record(
|
||||
changed_record,
|
||||
"https://auth.openai.com/api/accounts",
|
||||
&auth_route_config,
|
||||
)
|
||||
.await?,
|
||||
);
|
||||
assert_eq!(previous_auth, changed_auth);
|
||||
assert!(!previous_identity.has_same_connection_config(&connection_identity(&changed_auth)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn view_only_changes_reuse_connection_and_preserve_the_old_step() {
|
||||
let runtime_context = reusable_server_runtime_context();
|
||||
|
||||
@@ -694,8 +694,7 @@ async fn callback_during_startup_releases_waiting_chats_without_sharing_authorit
|
||||
|
||||
#[tokio::test]
|
||||
async fn connection_key_changes_with_the_owner_but_survives_credential_refresh() {
|
||||
let manager =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
|
||||
let manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test-api-key"));
|
||||
let mut original = key(&context(), &config());
|
||||
original.auth_state = Some((manager, AuthChangeState::default()));
|
||||
let mut refreshed = original.clone();
|
||||
|
||||
@@ -758,7 +758,7 @@ async fn reused_elicitation_senders_follow_each_servers_latest_permission_author
|
||||
config.approval_policy = codex_config::Constrained::allow_any(AskForApproval::Never);
|
||||
config.permission_profile = PermissionProfile::Disabled;
|
||||
config.apps_enabled = true;
|
||||
let auth = codex_login::CodexAuth::create_dummy_chatgpt_auth_for_testing();
|
||||
let auth = codex_login::CodexAuth::from_api_key("test-api-key");
|
||||
|
||||
let hosted_server = crate::mcp::test_http_mcp_server_config("https://example.com");
|
||||
let mut attached_server = hosted_server.clone();
|
||||
|
||||
@@ -1,115 +1,12 @@
|
||||
//! Account-grant eligibility and registration-specific sign-in requirements.
|
||||
//! The MCP service owns this state across threads; it retains registration policy but no user tokens.
|
||||
//! Registration-scoped EMA state shared by the MCP service across threads.
|
||||
|
||||
use std::sync::Mutex;
|
||||
|
||||
use codex_config::McpEmaRegistration;
|
||||
use codex_config::McpServerIdpOAuthConfig;
|
||||
use codex_login::AccountOAuthGrantRevision;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::TokenData;
|
||||
use codex_rmcp_client::account_oidc_identity_is_usable;
|
||||
use codex_rmcp_client::account_oidc_issuer_hint;
|
||||
|
||||
/// Remembers a rejected account credential only for the affected EMA registration.
|
||||
/// Retains no user tokens. Enterprise MCP credentials always come from a dedicated
|
||||
/// enterprise sign-in stored in the keyring.
|
||||
#[derive(Default)]
|
||||
pub struct EmaState {
|
||||
rejected: Mutex<Vec<(McpEmaRegistration, AccountOAuthGrantRevision)>>,
|
||||
}
|
||||
pub struct EmaState;
|
||||
|
||||
impl std::fmt::Debug for EmaState {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("EmaState").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl EmaState {
|
||||
pub(crate) fn requires_sign_in(
|
||||
&self,
|
||||
registration: &McpEmaRegistration,
|
||||
tokens: &TokenData,
|
||||
) -> bool {
|
||||
let revision = AccountOAuthGrantRevision::from(tokens);
|
||||
self.rejected
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.iter()
|
||||
.any(|(registered, rejected)| registered == registration && rejected == &revision)
|
||||
}
|
||||
|
||||
pub(crate) fn reject(&self, registration: &McpEmaRegistration, tokens: &TokenData) {
|
||||
let mut rejected = self
|
||||
.rejected
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
// Replacing a registration's marker also bounds repeated refresh/rejection cycles.
|
||||
rejected.retain(|(registered, _)| registered != registration);
|
||||
rejected.push((
|
||||
registration.clone(),
|
||||
AccountOAuthGrantRevision::from(tokens),
|
||||
));
|
||||
}
|
||||
|
||||
pub(crate) fn account_is_usable(
|
||||
&self,
|
||||
auth: &CodexAuth,
|
||||
registration: &McpEmaRegistration,
|
||||
) -> bool {
|
||||
matches!(auth, CodexAuth::Chatgpt(_))
|
||||
&& auth.get_token_data().is_ok_and(|tokens| {
|
||||
account_grant_is_usable(&tokens, registration.idp())
|
||||
&& !self.requires_sign_in(registration, &tokens)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn account_grant_is_usable(tokens: &TokenData, idp: &McpServerIdpOAuthConfig) -> bool {
|
||||
tokens.oauth_provenance.as_ref().is_some_and(|provenance| {
|
||||
provenance.issuer == idp.issuer
|
||||
// A provisioned secret belongs to the configured client, not another
|
||||
// primary login client at the same IdP. Use dedicated login in that case.
|
||||
&& (idp.client_secret.is_none() || provenance.client_id == idp.client_id)
|
||||
&& tokens
|
||||
.login_owner_id
|
||||
.as_ref()
|
||||
.is_some_and(|id| !id.is_empty())
|
||||
&& !tokens.refresh_token.trim().is_empty()
|
||||
&& tokens
|
||||
.id_token
|
||||
.chatgpt_user_id
|
||||
.as_ref()
|
||||
.is_some_and(|id| !id.is_empty())
|
||||
&& tokens.account_id.as_ref().is_some_and(|id| !id.is_empty())
|
||||
&& tokens.id_token.chatgpt_account_id == tokens.account_id
|
||||
&& account_oidc_identity_is_usable(
|
||||
&tokens.id_token.raw_jwt,
|
||||
&provenance.issuer,
|
||||
&provenance.client_id,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn account_configuration_issue(
|
||||
auth: &CodexAuth,
|
||||
idp: &McpServerIdpOAuthConfig,
|
||||
) -> Option<&'static str> {
|
||||
let tokens = auth.get_token_data().ok()?;
|
||||
if tokens.login_owner_id.is_none()
|
||||
&& (tokens
|
||||
.oauth_provenance
|
||||
.as_ref()
|
||||
.is_some_and(|provenance| provenance.issuer == idp.issuer)
|
||||
|| account_oidc_issuer_hint(&tokens.id_token.raw_jwt, &idp.issuer))
|
||||
{
|
||||
return Some("Sign in to your Codex account again to enable this enterprise MCP server");
|
||||
}
|
||||
if tokens.oauth_provenance.as_ref().is_some_and(|provenance| {
|
||||
provenance.issuer != idp.issuer
|
||||
&& provenance.issuer.trim_end_matches('/') == idp.issuer.trim_end_matches('/')
|
||||
}) {
|
||||
return Some(
|
||||
"Codex sign-in and enterprise MCP issuer strings differ by a trailing slash; align their OIDC issuer configuration",
|
||||
);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
@@ -48,17 +48,16 @@ pub(crate) struct EmaConnectionAuth {
|
||||
pub(crate) authority: EmaRequestAuthority,
|
||||
}
|
||||
|
||||
pub fn ema_auth_scope(auth: Option<&CodexAuth>) -> Option<McpEmaAuthScope> {
|
||||
let auth = auth?;
|
||||
McpEmaAuthScope::new(auth.get_chatgpt_user_id()?, auth.get_account_id()?)
|
||||
/// EMA scopes are keyed by a signed-in account identity. Stored API keys and
|
||||
/// host-supplied headers carry no such identity, so EMA is never in scope.
|
||||
pub fn ema_auth_scope(_auth: Option<&CodexAuth>) -> Option<McpEmaAuthScope> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Retained by the thread across MCP refreshes; a revoked owner cannot be replaced.
|
||||
pub(crate) struct EmaAuth {
|
||||
pub(crate) scope: McpEmaAuthScope,
|
||||
pub(crate) config: Arc<McpConfig>,
|
||||
pub(crate) manager: Arc<AuthManager>,
|
||||
pub(crate) account: CodexAuth,
|
||||
pub(crate) authority: EmaRequestAuthority,
|
||||
_revocation: AbortOnDropHandle<()>,
|
||||
}
|
||||
@@ -114,31 +113,12 @@ 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
|
||||
.context(EmaErrorDetail::new(
|
||||
"enterprise MCP account credential validation failed",
|
||||
))?
|
||||
{
|
||||
self.authority.revoke();
|
||||
bail!(codex_rmcp_client::EmaTokenSourceError::new(
|
||||
codex_rmcp_client::EmaCredentialKind::Account,
|
||||
EmaAuthFailure::ReauthenticationRequired,
|
||||
));
|
||||
}
|
||||
self.authority.check()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,15 +1,10 @@
|
||||
//! Pins one EMA connection to an account login or a dedicated enterprise grant.
|
||||
//! Account refresh exclusion ends with the IdP exchange, before resource-server I/O.
|
||||
//! Pins one EMA connection to a dedicated enterprise grant stored in the keyring.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use codex_config::McpEmaRegistration;
|
||||
use codex_exec_server::HttpClient;
|
||||
use codex_login::AccountOAuthGrant;
|
||||
use codex_login::AccountOAuthGrantLease;
|
||||
use codex_login::AccountOAuthGrantRevision;
|
||||
use codex_rmcp_client::EmaAccessToken;
|
||||
use codex_rmcp_client::EmaAuthFailure;
|
||||
use codex_rmcp_client::EmaAuthTokenExchangeRequest;
|
||||
@@ -23,34 +18,16 @@ use codex_rmcp_client::EmaTokenSource;
|
||||
use codex_rmcp_client::EmaTokenSourceError;
|
||||
use codex_rmcp_client::StreamableHttpRedirectMode;
|
||||
use codex_rmcp_client::exchange_ema_auth_token;
|
||||
use codex_rmcp_client::resolve_ema_account_idp_identity;
|
||||
use codex_rmcp_client::resolve_ema_idp_identity;
|
||||
use url::Url;
|
||||
|
||||
use crate::ema_account::account_configuration_issue;
|
||||
use crate::ema_account::account_grant_is_usable;
|
||||
use crate::ema_auth::EmaAuth;
|
||||
use crate::ema_auth::stored_ema_credentials;
|
||||
|
||||
enum CredentialSource {
|
||||
Account { client_id: String },
|
||||
Keyring(Box<EmaCredentialSnapshot>),
|
||||
}
|
||||
|
||||
enum IdpLease {
|
||||
Account(AccountOAuthGrantLease),
|
||||
Keyring(EmaCredentialLease),
|
||||
}
|
||||
|
||||
enum ExchangeReceipt {
|
||||
Account(AccountOAuthGrant),
|
||||
Keyring(EmaCredentialLease),
|
||||
}
|
||||
|
||||
pub(crate) struct EnterpriseTokenSource {
|
||||
endpoint: Url,
|
||||
registration: McpEmaRegistration,
|
||||
credentials: CredentialSource,
|
||||
credentials: Box<EmaCredentialSnapshot>,
|
||||
auth: Arc<EmaAuth>,
|
||||
http_client: Arc<dyn HttpClient>,
|
||||
}
|
||||
@@ -62,41 +39,17 @@ impl EnterpriseTokenSource {
|
||||
http_client: Arc<dyn HttpClient>,
|
||||
) -> Result<Self> {
|
||||
auth.check_account().await?;
|
||||
let account = auth
|
||||
.manager
|
||||
.lease_account_oauth_grant()
|
||||
.await
|
||||
.map_err(|_| EmaErrorDetail::new("enterprise MCP account credential read failed"))?;
|
||||
let client_id = account
|
||||
.as_ref()
|
||||
.filter(|lease| {
|
||||
account_grant_is_usable(lease.tokens(), registration.idp())
|
||||
&& !auth
|
||||
.config
|
||||
.ema_state
|
||||
.requires_sign_in(®istration, lease.tokens())
|
||||
})
|
||||
.and_then(|lease| lease.tokens().oauth_provenance.as_ref())
|
||||
.map(|provenance| provenance.client_id.clone());
|
||||
drop(account);
|
||||
let credentials = match client_id {
|
||||
Some(client_id) => CredentialSource::Account { client_id },
|
||||
None => {
|
||||
let snapshot = stored_ema_credentials(
|
||||
registration.idp(),
|
||||
&auth.scope,
|
||||
auth.config.auth_keyring_backend_kind,
|
||||
)
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
anyhow::Error::new(EmaAuthFailure::ReauthenticationRequired).context(
|
||||
account_configuration_issue(&auth.account, registration.idp())
|
||||
.unwrap_or("Complete enterprise sign-in to use this MCP server"),
|
||||
)
|
||||
})?;
|
||||
CredentialSource::Keyring(Box::new(snapshot.pin_ema_credentials().await?))
|
||||
}
|
||||
};
|
||||
let snapshot = stored_ema_credentials(
|
||||
registration.idp(),
|
||||
&auth.scope,
|
||||
auth.config.auth_keyring_backend_kind,
|
||||
)
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
anyhow::Error::new(EmaAuthFailure::ReauthenticationRequired)
|
||||
.context("Complete enterprise sign-in to use this MCP server")
|
||||
})?;
|
||||
let credentials = Box::new(snapshot.pin_ema_credentials().await?);
|
||||
Ok(Self {
|
||||
endpoint: Url::parse(registration.server_url())?,
|
||||
registration,
|
||||
@@ -107,143 +60,26 @@ impl EnterpriseTokenSource {
|
||||
}
|
||||
|
||||
pub(crate) async fn initial_access_token(&mut self) -> Result<EmaAccessToken> {
|
||||
let error = match self.access_token().await {
|
||||
Ok(token) => return Ok(token),
|
||||
Err(error) => error,
|
||||
};
|
||||
// A restart forgets the rejection marker. A saved enterprise login can still
|
||||
// satisfy step-up, but a live connection never silently changes its source.
|
||||
if matches!(self.credentials, CredentialSource::Account { .. })
|
||||
&& error
|
||||
.downcast_ref::<EmaTokenSourceError>()
|
||||
.is_some_and(EmaTokenSourceError::is_authentication_required)
|
||||
&& let Some(lease) = self
|
||||
.auth
|
||||
.manager
|
||||
.lease_account_oauth_grant()
|
||||
.await
|
||||
.map_err(|_| EmaErrorDetail::new("enterprise MCP account credential read failed"))?
|
||||
{
|
||||
let rejected = self
|
||||
.auth
|
||||
.config
|
||||
.ema_state
|
||||
.requires_sign_in(&self.registration, lease.tokens());
|
||||
drop(lease);
|
||||
if rejected
|
||||
&& let Ok(Some(snapshot)) = stored_ema_credentials(
|
||||
self.registration.idp(),
|
||||
&self.auth.scope,
|
||||
self.auth.config.auth_keyring_backend_kind,
|
||||
)
|
||||
.await
|
||||
{
|
||||
self.auth.check_account().await?;
|
||||
self.credentials =
|
||||
CredentialSource::Keyring(Box::new(snapshot.pin_ema_credentials().await?));
|
||||
return self.access_token().await;
|
||||
}
|
||||
}
|
||||
Err(error)
|
||||
self.access_token().await
|
||||
}
|
||||
|
||||
async fn account_grant(&self, client_id: &str) -> Result<AccountOAuthGrant> {
|
||||
self.auth.check_account().await?;
|
||||
let lease = self
|
||||
.auth
|
||||
.manager
|
||||
.lease_account_oauth_grant()
|
||||
.await
|
||||
.map_err(|_| EmaErrorDetail::new("enterprise MCP account credential read failed"))?
|
||||
.ok_or(EmaAuthFailure::ReauthenticationRequired)?;
|
||||
if !account_grant_is_usable(lease.tokens(), self.registration.idp())
|
||||
|| lease
|
||||
.tokens()
|
||||
.oauth_provenance
|
||||
.as_ref()
|
||||
.is_none_or(|provenance| provenance.client_id != client_id)
|
||||
{
|
||||
bail!(EmaAuthFailure::ReauthenticationRequired);
|
||||
}
|
||||
if self
|
||||
.auth
|
||||
.config
|
||||
.ema_state
|
||||
.requires_sign_in(&self.registration, lease.tokens())
|
||||
{
|
||||
bail!(EmaAuthFailure::InsufficientUserAuthentication {
|
||||
grant_source: EmaInvalidGrantSource::EnterpriseIdentity
|
||||
});
|
||||
}
|
||||
Ok(lease.release())
|
||||
}
|
||||
|
||||
async fn exchange(&self, account: Option<&AccountOAuthGrant>) -> Result<EmaAccessToken> {
|
||||
async fn exchange(&self) -> Result<EmaAccessToken> {
|
||||
let idp = self.registration.idp();
|
||||
let client_id = match &self.credentials {
|
||||
CredentialSource::Account { client_id } => client_id,
|
||||
CredentialSource::Keyring(_) => &idp.client_id,
|
||||
};
|
||||
let client_id = &idp.client_id;
|
||||
let identity = Box::pin(async {
|
||||
self.auth.check_account().await?;
|
||||
match &self.credentials {
|
||||
CredentialSource::Account { .. } => {
|
||||
let grant = account.ok_or(EmaAuthFailure::ReauthenticationRequired)?;
|
||||
let tokens = grant.tokens();
|
||||
// Metadata discovery must not block ordinary account refresh.
|
||||
let identity = resolve_ema_account_idp_identity(
|
||||
idp,
|
||||
client_id,
|
||||
&tokens.id_token.raw_jwt,
|
||||
tokens.refresh_token.clone(),
|
||||
/*credentials*/ (),
|
||||
Arc::clone(&self.http_client),
|
||||
StreamableHttpRedirectMode::Legacy,
|
||||
)
|
||||
.await?;
|
||||
let lease = self
|
||||
.auth
|
||||
.manager
|
||||
.lease_account_oauth_grant()
|
||||
.await
|
||||
.map_err(|_| {
|
||||
EmaErrorDetail::new("enterprise MCP account credential read failed")
|
||||
})?
|
||||
.ok_or(EmaAuthFailure::ReauthenticationRequired)?;
|
||||
if AccountOAuthGrantRevision::from(lease.tokens())
|
||||
!= AccountOAuthGrantRevision::from(tokens)
|
||||
|| !account_grant_is_usable(lease.tokens(), idp)
|
||||
{
|
||||
bail!(EmaAuthFailure::ReauthenticationRequired);
|
||||
}
|
||||
if self
|
||||
.auth
|
||||
.config
|
||||
.ema_state
|
||||
.requires_sign_in(&self.registration, lease.tokens())
|
||||
{
|
||||
bail!(EmaAuthFailure::InsufficientUserAuthentication {
|
||||
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
|
||||
});
|
||||
}
|
||||
Ok(identity.map_credentials(|()| IdpLease::Account(lease)))
|
||||
}
|
||||
CredentialSource::Keyring(snapshot) => {
|
||||
resolve_ema_idp_identity(EmaIdpIdentityRequest {
|
||||
issuer: &idp.issuer,
|
||||
client_id,
|
||||
client_secret: idp.client_secret.as_ref().map(|secret| secret.as_str()),
|
||||
token_endpoint_auth_method: idp.token_endpoint_auth_method,
|
||||
credentials: snapshot.acquire_current_ema_credentials().await?,
|
||||
http_client: Arc::clone(&self.http_client),
|
||||
redirect_mode: StreamableHttpRedirectMode::Legacy,
|
||||
})
|
||||
.await
|
||||
.map(|identity| identity.map_credentials(IdpLease::Keyring))
|
||||
}
|
||||
}
|
||||
resolve_ema_idp_identity(EmaIdpIdentityRequest {
|
||||
issuer: &idp.issuer,
|
||||
client_id,
|
||||
client_secret: idp.client_secret.as_ref().map(|secret| secret.as_str()),
|
||||
token_endpoint_auth_method: idp.token_endpoint_auth_method,
|
||||
credentials: self.credentials.acquire_current_ema_credentials().await?,
|
||||
http_client: Arc::clone(&self.http_client),
|
||||
redirect_mode: StreamableHttpRedirectMode::Legacy,
|
||||
})
|
||||
.await
|
||||
});
|
||||
let (token, receipt) = exchange_ema_auth_token(
|
||||
let (token, lease) = exchange_ema_auth_token(
|
||||
EmaAuthTokenExchangeRequest {
|
||||
server_url: self.registration.server_url(),
|
||||
resource: self.registration.resource(),
|
||||
@@ -260,123 +96,36 @@ impl EnterpriseTokenSource {
|
||||
idp_http_client: Arc::clone(&self.http_client),
|
||||
resource_http_client: Arc::clone(&self.http_client),
|
||||
},
|
||||
|lease| match lease {
|
||||
IdpLease::Account(lease) => ExchangeReceipt::Account(lease.release()),
|
||||
IdpLease::Keyring(lease) => ExchangeReceipt::Keyring(lease),
|
||||
},
|
||||
|lease: EmaCredentialLease| lease,
|
||||
)
|
||||
.await?;
|
||||
match receipt {
|
||||
ExchangeReceipt::Account(grant) => {
|
||||
if grant
|
||||
.current_tokens()
|
||||
.await
|
||||
.map_err(|_| {
|
||||
EmaErrorDetail::new("enterprise MCP account credential validation failed")
|
||||
})?
|
||||
.as_ref()
|
||||
.is_none_or(|tokens| {
|
||||
!account_grant_is_usable(tokens, idp)
|
||||
|| self
|
||||
.auth
|
||||
.config
|
||||
.ema_state
|
||||
.requires_sign_in(&self.registration, tokens)
|
||||
})
|
||||
{
|
||||
// Discard this bearer. The bounded retry below reacquires the grant
|
||||
// only if its credential changed under the same admitted owner.
|
||||
bail!(EmaAuthFailure::ReauthenticationRequired);
|
||||
}
|
||||
}
|
||||
ExchangeReceipt::Keyring(lease) => {
|
||||
drop(lease);
|
||||
if let CredentialSource::Keyring(snapshot) = &self.credentials {
|
||||
snapshot.acquire_current_ema_credentials().await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(lease);
|
||||
self.credentials.acquire_current_ema_credentials().await?;
|
||||
self.auth.check_account().await?;
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
async fn acquire_token(&self) -> Result<EmaAccessToken> {
|
||||
self.auth.check_account().await?;
|
||||
match &self.credentials {
|
||||
CredentialSource::Account { client_id } => {
|
||||
let mut grant = self.account_grant(client_id).await?;
|
||||
for attempt in 0..2 {
|
||||
let error = match self.exchange(Some(&grant)).await {
|
||||
Ok(token) => return Ok(token),
|
||||
Err(error) => error,
|
||||
};
|
||||
if idp_rejected(&error)
|
||||
|| matches!(
|
||||
error.downcast_ref::<EmaAuthFailure>(),
|
||||
Some(EmaAuthFailure::ReauthenticationRequired)
|
||||
)
|
||||
{
|
||||
let current = self.account_grant(client_id).await?;
|
||||
if !current.same_credential(&grant) {
|
||||
if attempt == 0 {
|
||||
grant = current;
|
||||
continue;
|
||||
}
|
||||
// Repeated rotation is transient; a later call can renew
|
||||
// without revoking this still-current account owner.
|
||||
bail!(EmaTokenSourceError::unexpected(EmaCredentialKind::Account));
|
||||
}
|
||||
if idp_rejected(&error)
|
||||
&& let Some(lease) = self
|
||||
.auth
|
||||
.manager
|
||||
.lease_account_oauth_grant()
|
||||
.await
|
||||
.map_err(|_| {
|
||||
EmaErrorDetail::new(
|
||||
"enterprise MCP account credential read failed",
|
||||
)
|
||||
})?
|
||||
{
|
||||
if AccountOAuthGrantRevision::from(lease.tokens())
|
||||
!= AccountOAuthGrantRevision::from(grant.tokens())
|
||||
{
|
||||
// Refresh may also rotate after the first credential check.
|
||||
bail!(EmaTokenSourceError::unexpected(EmaCredentialKind::Account));
|
||||
}
|
||||
// Serialize rejection publication with refresh and other leases.
|
||||
// A late rejection cannot replace a newer credential's marker.
|
||||
self.auth
|
||||
.config
|
||||
.ema_state
|
||||
.reject(&self.registration, lease.tokens());
|
||||
}
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
unreachable!("each exchange returns or retries once")
|
||||
}
|
||||
CredentialSource::Keyring(snapshot) => {
|
||||
let result = self.exchange(/*account*/ None).await;
|
||||
if result.as_ref().is_err_and(|error| {
|
||||
matches!(
|
||||
error.downcast_ref::<EmaAuthFailure>(),
|
||||
Some(EmaAuthFailure::InvalidGrant {
|
||||
grant_source: EmaInvalidGrantSource::EnterpriseIdentity
|
||||
})
|
||||
)
|
||||
}) && snapshot
|
||||
.invalidate_ema_credentials_if_current(async {
|
||||
self.auth.check_account().await.is_ok()
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!("failed to clear rejected enterprise credentials");
|
||||
}
|
||||
result
|
||||
}
|
||||
let result = self.exchange().await;
|
||||
if result.as_ref().is_err_and(|error| {
|
||||
matches!(
|
||||
error.downcast_ref::<EmaAuthFailure>(),
|
||||
Some(EmaAuthFailure::InvalidGrant {
|
||||
grant_source: EmaInvalidGrantSource::EnterpriseIdentity
|
||||
})
|
||||
)
|
||||
}) && self
|
||||
.credentials
|
||||
.invalidate_ema_credentials_if_current(async {
|
||||
self.auth.check_account().await.is_ok()
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!("failed to clear rejected enterprise credentials");
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -386,10 +135,7 @@ impl EmaTokenSource for EnterpriseTokenSource {
|
||||
}
|
||||
|
||||
async fn access_token(&self) -> Result<EmaAccessToken> {
|
||||
let kind = match self.credentials {
|
||||
CredentialSource::Account { .. } => EmaCredentialKind::Account,
|
||||
CredentialSource::Keyring(_) => EmaCredentialKind::Keyring,
|
||||
};
|
||||
let kind = EmaCredentialKind::Keyring;
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
() = self.auth.config.mcp_ema_cancellation.cancelled() => Err(EmaAuthFailure::ReauthenticationRequired.into()),
|
||||
@@ -414,16 +160,3 @@ impl EmaTokenSource for EnterpriseTokenSource {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn idp_rejected(error: &anyhow::Error) -> bool {
|
||||
matches!(
|
||||
error.downcast_ref::<EmaAuthFailure>(),
|
||||
Some(
|
||||
EmaAuthFailure::InvalidGrant {
|
||||
grant_source: EmaInvalidGrantSource::EnterpriseIdentity
|
||||
} | EmaAuthFailure::InsufficientUserAuthentication {
|
||||
grant_source: EmaInvalidGrantSource::EnterpriseIdentity
|
||||
} | EmaAuthFailure::IdentityClientRejected
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::auth::McpAuthProvider;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use codex_config::types::AuthKeyringBackendKind;
|
||||
@@ -35,7 +34,6 @@ pub(crate) struct EventStreamConnectionSettings {
|
||||
pub oauth_refresh_mode: McpOAuthRefreshMode,
|
||||
pub runtime_context: McpRuntimeContext,
|
||||
pub resolved_environment: std::result::Result<Option<Arc<Environment>>, String>,
|
||||
pub auth_provider: Option<McpAuthProvider>,
|
||||
pub auth_manager: Option<Arc<AuthManager>>,
|
||||
pub auth: Option<CodexAuth>,
|
||||
pub protocol_mode: McpProtocolMode,
|
||||
@@ -87,7 +85,6 @@ impl McpEventStreamOpener {
|
||||
connection.oauth_refresh_mode,
|
||||
connection.runtime_context.clone(),
|
||||
connection.resolved_environment.clone(),
|
||||
connection.auth_provider.clone(),
|
||||
connection.protocol_mode,
|
||||
)).await??);
|
||||
client.initialize(
|
||||
@@ -139,22 +136,6 @@ impl McpEventStreamOpener {
|
||||
}
|
||||
|
||||
fn matches_auth(&self, current: Option<&CodexAuth>) -> bool {
|
||||
match (self.connection.auth.as_ref(), current) {
|
||||
(Some(CodexAuth::AgentIdentity(expected)), Some(CodexAuth::AgentIdentity(current))) => {
|
||||
expected.record() == current.record()
|
||||
}
|
||||
(Some(CodexAuth::AgentIdentity(_)), _) | (_, Some(CodexAuth::AgentIdentity(_))) => {
|
||||
false
|
||||
}
|
||||
(Some(expected), Some(current)) => {
|
||||
expected.get_account_id() == current.get_account_id()
|
||||
&& expected.get_chatgpt_user_id() == current.get_chatgpt_user_id()
|
||||
&& expected.is_workspace_account() == current.is_workspace_account()
|
||||
&& expected.is_fedramp_account() == current.is_fedramp_account()
|
||||
&& (expected.get_account_id().is_some() || expected == current)
|
||||
}
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
}
|
||||
self.connection.auth.as_ref() == current
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,7 +45,6 @@ pub use tool_catalog_cache::McpToolCatalogCache;
|
||||
pub use tool_request_meta::McpToolRequestMetaHook;
|
||||
pub use tool_request_meta::McpToolRequestMetaProvider;
|
||||
pub use tools::ToolInfo;
|
||||
pub use trusted_access::TrustedAccessContext;
|
||||
|
||||
/// Backward-compatible name for the shared Codex Apps tools runtime.
|
||||
pub type CodexAppsToolsCache = codex_connectors::ConnectorRuntimeManager<ToolInfo>;
|
||||
@@ -114,7 +113,6 @@ pub use mcp::McpPermissionPromptAutoApproveContext;
|
||||
pub use mcp::mcp_permission_prompt_is_auto_approved;
|
||||
pub use mcp::qualified_mcp_tool_name_prefix;
|
||||
|
||||
mod auth;
|
||||
mod auth_changes;
|
||||
pub(crate) mod auth_elicitation;
|
||||
mod binding;
|
||||
@@ -146,4 +144,3 @@ pub(crate) mod server;
|
||||
mod tool_catalog_cache;
|
||||
mod tool_request_meta;
|
||||
pub(crate) mod tools;
|
||||
mod trusted_access;
|
||||
|
||||
@@ -8,7 +8,6 @@ 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;
|
||||
@@ -22,7 +21,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 +200,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 +221,6 @@ where
|
||||
store_mode,
|
||||
keyring_backend_kind,
|
||||
auth,
|
||||
auth_manager,
|
||||
account_grant,
|
||||
ema_state,
|
||||
&runtime_context,
|
||||
redirect_mode,
|
||||
)
|
||||
@@ -260,9 +250,6 @@ async fn compute_auth_status(
|
||||
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,
|
||||
runtime_context: &McpRuntimeContext,
|
||||
redirect_mode: StreamableHttpRedirectMode,
|
||||
) -> Result<McpAuthState> {
|
||||
@@ -279,31 +266,6 @@ async fn compute_auth_status(
|
||||
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(),
|
||||
@@ -327,16 +289,6 @@ async fn compute_auth_status(
|
||||
);
|
||||
}
|
||||
|
||||
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 +297,6 @@ async fn compute_auth_status(
|
||||
});
|
||||
}
|
||||
|
||||
if has_runtime_auth {
|
||||
return Ok(McpAuthState::BearerToken);
|
||||
}
|
||||
|
||||
match &config.transport {
|
||||
McpServerTransportConfig::Stdio { .. } => Ok(McpAuthState::Unsupported),
|
||||
McpServerTransportConfig::StreamableHttp {
|
||||
|
||||
@@ -23,7 +23,6 @@ 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;
|
||||
@@ -33,7 +32,6 @@ 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;
|
||||
@@ -378,39 +376,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
|
||||
@@ -435,13 +400,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,
|
||||
@@ -466,10 +429,6 @@ 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,
|
||||
@@ -487,7 +446,6 @@ pub async fn read_mcp_resource(
|
||||
McpPublicationGate::already_published(),
|
||||
McpRuntimeInput {
|
||||
network_policy_metadata: None,
|
||||
runtime_auth,
|
||||
startup_policy: McpStartupPolicy::Eager,
|
||||
config: Arc::new(runtime_config),
|
||||
plugins_available: false,
|
||||
@@ -532,11 +490,6 @@ 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,
|
||||
@@ -564,8 +517,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;
|
||||
@@ -581,7 +532,6 @@ pub async fn collect_mcp_server_status_snapshot_with_detail(
|
||||
McpPublicationGate::already_published(),
|
||||
McpRuntimeInput {
|
||||
network_policy_metadata: None,
|
||||
runtime_auth,
|
||||
startup_policy: McpStartupPolicy::Eager,
|
||||
config: Arc::new(runtime_config),
|
||||
plugins_available: false,
|
||||
@@ -829,7 +779,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,
|
||||
|
||||
@@ -11,8 +11,6 @@ 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;
|
||||
@@ -21,7 +19,9 @@ 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 codex_rmcp_client::McpLoginRequirement;
|
||||
use futures::FutureExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashMap;
|
||||
@@ -31,49 +31,10 @@ 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 ema_auth_statuses_require_enterprise_login_without_account_identity() -> 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!({
|
||||
@@ -104,24 +65,28 @@ 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")?;
|
||||
// Stored API keys carry no account identity, so EMA never borrows them.
|
||||
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::LoggedOut(McpLoginRequirement::Login)
|
||||
),
|
||||
(
|
||||
"second".to_string(),
|
||||
McpAuthState::LoggedOut(McpLoginRequirement::Login)
|
||||
),
|
||||
]),
|
||||
);
|
||||
drop(lease);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -597,7 +562,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"),
|
||||
(
|
||||
@@ -626,7 +591,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}",
|
||||
);
|
||||
}
|
||||
@@ -669,7 +634,7 @@ 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(
|
||||
|
||||
@@ -32,7 +32,6 @@ use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::auth::McpAuthProvider;
|
||||
use crate::client_tool_catalog::ClientToolCatalog;
|
||||
use crate::codex_apps::normalize_codex_apps_callable_name;
|
||||
use crate::codex_apps::normalize_codex_apps_callable_namespace;
|
||||
@@ -284,7 +283,6 @@ struct ManagedClientStartup {
|
||||
tool_catalog_cache_context: Option<McpToolCatalogCacheContext>,
|
||||
runtime_context: McpRuntimeContext,
|
||||
resolved_environment: std::result::Result<Option<Arc<Environment>>, String>,
|
||||
runtime_auth_provider: Option<McpAuthProvider>,
|
||||
client_elicitation_capability: ElicitationCapability,
|
||||
client_mcp_extensions: ClientMcpExtensions,
|
||||
auth_changes: Option<watch::Receiver<AuthChangeState>>,
|
||||
@@ -320,7 +318,6 @@ impl ManagedClientStartup {
|
||||
tool_catalog_cache_context,
|
||||
runtime_context,
|
||||
resolved_environment,
|
||||
runtime_auth_provider,
|
||||
client_elicitation_capability,
|
||||
client_mcp_extensions,
|
||||
auth_changes,
|
||||
@@ -358,8 +355,7 @@ impl ManagedClientStartup {
|
||||
oauth_refresh_mode,
|
||||
runtime_context,
|
||||
resolved_environment,
|
||||
runtime_auth_provider,
|
||||
protocol_mode,
|
||||
protocol_mode,
|
||||
),
|
||||
)
|
||||
.await
|
||||
@@ -489,8 +485,7 @@ impl AsyncManagedClient {
|
||||
tool_catalog_cache_context: Option<McpToolCatalogCacheContext>,
|
||||
runtime_context: McpRuntimeContext,
|
||||
resolved_environment: std::result::Result<Option<Arc<Environment>>, String>,
|
||||
runtime_auth_provider: Option<McpAuthProvider>,
|
||||
client_elicitation_capability: ElicitationCapability,
|
||||
client_elicitation_capability: ElicitationCapability,
|
||||
client_mcp_extensions: ClientMcpExtensions,
|
||||
auth_changes: Option<watch::Receiver<AuthChangeState>>,
|
||||
protocol_mode: McpProtocolMode,
|
||||
@@ -548,7 +543,6 @@ impl AsyncManagedClient {
|
||||
tool_catalog_cache_context,
|
||||
runtime_context,
|
||||
resolved_environment,
|
||||
runtime_auth_provider,
|
||||
client_elicitation_capability,
|
||||
client_mcp_extensions,
|
||||
auth_changes,
|
||||
@@ -1431,7 +1425,6 @@ pub(crate) async fn make_rmcp_client(
|
||||
oauth_refresh_mode: McpOAuthRefreshMode,
|
||||
runtime_context: McpRuntimeContext,
|
||||
resolved_environment: std::result::Result<Option<Arc<Environment>>, String>,
|
||||
runtime_auth_provider: Option<McpAuthProvider>,
|
||||
protocol_mode: McpProtocolMode,
|
||||
) -> Result<RmcpClient, StartupOutcomeError> {
|
||||
let config = server.config().clone();
|
||||
@@ -1537,13 +1530,6 @@ pub(crate) async fn make_rmcp_client(
|
||||
bearer_token_env_var,
|
||||
http_headers_helper: _,
|
||||
} => {
|
||||
let (runtime_auth_provider, runtime_context) = match runtime_auth_provider {
|
||||
Some(provider) => {
|
||||
let (provider, context) = provider.resolve(runtime_context, &url).await?;
|
||||
(Some(provider), context)
|
||||
}
|
||||
None => (None, runtime_context),
|
||||
};
|
||||
let http_client = runtime_context
|
||||
.http_client_for_server(server.config(), resolved_environment.as_ref())
|
||||
.map_err(|error| StartupOutcomeError::from(anyhow!(error)))?;
|
||||
@@ -1600,7 +1586,7 @@ pub(crate) async fn make_rmcp_client(
|
||||
store_mode,
|
||||
keyring_backend_kind,
|
||||
http_client,
|
||||
runtime_auth_provider,
|
||||
/*auth_provider*/ None,
|
||||
protocol_mode,
|
||||
redirect_mode,
|
||||
oauth_refresh_mode,
|
||||
|
||||
@@ -110,10 +110,6 @@ pub struct McpRuntimeInput {
|
||||
pub client_mcp_extensions: ClientMcpExtensions,
|
||||
pub auth: Option<CodexAuth>,
|
||||
pub auth_manager: Option<Arc<AuthManager>>,
|
||||
pub runtime_auth: Option<(
|
||||
codex_runtime_agent_instance::RuntimeAuthSlot,
|
||||
codex_features::RuntimeAuthMode,
|
||||
)>,
|
||||
pub elicitation_reviewer: Option<ElicitationReviewerHandle>,
|
||||
pub elicitation_lifecycle: Option<ElicitationLifecycle>,
|
||||
}
|
||||
@@ -196,11 +192,7 @@ impl PublishedMcpRuntime {
|
||||
fn auth_matches(&self, auth: Option<&CodexAuth>) -> bool {
|
||||
match (self.auth.as_ref(), auth) {
|
||||
(Some(previous), Some(latest)) => {
|
||||
previous == latest
|
||||
&& previous.get_account_id() == latest.get_account_id()
|
||||
&& previous.get_chatgpt_user_id() == latest.get_chatgpt_user_id()
|
||||
&& previous.is_fedramp_account() == latest.is_fedramp_account()
|
||||
&& self.auth_token == latest.get_token().ok()
|
||||
previous == latest && self.auth_token == latest.get_token().ok()
|
||||
}
|
||||
(None, None) => true,
|
||||
(Some(_), None) | (None, Some(_)) => false,
|
||||
@@ -1091,14 +1083,6 @@ impl McpRuntimeContext {
|
||||
self.local_process_cwd.clone()
|
||||
}
|
||||
|
||||
pub(crate) fn http_client_factory(&self) -> codex_http_client::HttpClientFactory {
|
||||
self.environment_manager.http_client_factory().clone()
|
||||
}
|
||||
|
||||
pub(crate) fn set_local_http_client(&mut self, client: Arc<dyn HttpClient>) {
|
||||
self.local_http_client = client;
|
||||
}
|
||||
|
||||
pub(crate) fn local_http_client(&self) -> Arc<dyn HttpClient> {
|
||||
Arc::clone(&self.local_http_client)
|
||||
}
|
||||
|
||||
@@ -56,8 +56,6 @@ impl McpRuntime {
|
||||
config.mcp_oauth_credentials_store_mode,
|
||||
config.auth_keyring_backend_kind,
|
||||
current.auth.as_ref(),
|
||||
current.auth_manager.as_ref(),
|
||||
&config.ema_state,
|
||||
&runtime_context,
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -80,7 +80,6 @@ async fn forced_refresh_replaces_pending_connection_without_interrupting_other_c
|
||||
}));
|
||||
let input = McpRuntimeInput {
|
||||
network_policy_metadata: None,
|
||||
runtime_auth: None,
|
||||
startup_policy: McpStartupPolicy::Eager,
|
||||
config,
|
||||
plugins_available: false,
|
||||
|
||||
@@ -4,7 +4,6 @@ use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::auth::McpAuthProvider;
|
||||
use crate::mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use crate::runtime::McpRuntimeContext;
|
||||
use codex_config::AppToolApproval;
|
||||
@@ -16,7 +15,6 @@ use codex_config::types::AuthKeyringBackendKind;
|
||||
use codex_config::types::OAuthCredentialsStoreMode;
|
||||
use codex_connectors::ConnectorRuntimeContextKey;
|
||||
use codex_exec_server::Environment;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_protocol::mcp::ClientMcpExtensions;
|
||||
use codex_rmcp_client::McpOAuthRefreshMode;
|
||||
use codex_rmcp_client::McpProtocolMode;
|
||||
@@ -87,16 +85,11 @@ impl EffectiveMcpServer {
|
||||
|
||||
/// Checks whether Core can discover the protocol of a local stdio server.
|
||||
///
|
||||
/// The reserved `codex_apps` server has a per-chat catalog. Servers with runtime or
|
||||
/// The reserved `codex_apps` server has a per-chat catalog. Servers with
|
||||
/// enterprise-managed credentials need that chat's authentication state.
|
||||
pub(crate) fn can_discover_local_stdio(
|
||||
&self,
|
||||
server_name: &str,
|
||||
runtime_auth_provider: Option<&McpAuthProvider>,
|
||||
) -> bool {
|
||||
pub(crate) fn can_discover_local_stdio(&self, server_name: &str) -> bool {
|
||||
server_name != CODEX_APPS_MCP_SERVER_NAME
|
||||
&& self.config.is_local_environment()
|
||||
&& runtime_auth_provider.is_none()
|
||||
&& !matches!(self.config.auth, McpServerAuth::EmaAuth)
|
||||
&& self
|
||||
.stdio_protocol_mode(McpProtocolMode::DiscoverLocalStdio)
|
||||
@@ -176,9 +169,6 @@ pub(crate) struct McpServerConnectionIdentity {
|
||||
resolved_environment: Result<Option<Arc<Environment>>, String>,
|
||||
local_stdio_fallback_cwd: Option<PathBuf>,
|
||||
referenced_environment_variables: Vec<(String, Option<OsString>)>,
|
||||
runtime_auth: Option<CodexAuth>,
|
||||
runtime_auth_token: Option<String>,
|
||||
runtime_auth_mode: Option<codex_features::RuntimeAuthMode>,
|
||||
codex_apps_cache_identity: Option<(PathBuf, ConnectorRuntimeContextKey)>,
|
||||
client_elicitation_capability: ElicitationCapability,
|
||||
client_mcp_extensions: ClientMcpExtensions,
|
||||
@@ -197,9 +187,6 @@ impl McpServerConnectionIdentity {
|
||||
oauth_refresh_mode: McpOAuthRefreshMode,
|
||||
resolved_environment: &Result<Option<Arc<Environment>>, String>,
|
||||
runtime_context: &McpRuntimeContext,
|
||||
runtime_auth_provider: Option<&McpAuthProvider>,
|
||||
runtime_auth_mode: Option<codex_features::RuntimeAuthMode>,
|
||||
auth: Option<&CodexAuth>,
|
||||
codex_apps_cache_identity: Option<(PathBuf, ConnectorRuntimeContextKey)>,
|
||||
client_elicitation_capability: ElicitationCapability,
|
||||
client_mcp_extensions: ClientMcpExtensions,
|
||||
@@ -211,8 +198,7 @@ impl McpServerConnectionIdentity {
|
||||
.bytes()
|
||||
.all(|byte| byte == b'\t' || (byte >= b' ' && byte != 0x7f))
|
||||
};
|
||||
let stored_oauth_url = if runtime_auth_provider.is_none()
|
||||
&& !matches!(config.auth, McpServerAuth::EmaAuth)
|
||||
let stored_oauth_url = if !matches!(config.auth, McpServerAuth::EmaAuth)
|
||||
&& (!matches!(config.auth, McpServerAuth::ChatGpt) || config.is_local_environment())
|
||||
{
|
||||
match &config.transport {
|
||||
@@ -282,8 +268,6 @@ impl McpServerConnectionIdentity {
|
||||
McpCredentialPolicy::HostFallbackAllowed => referenced_environment_variables(config),
|
||||
McpCredentialPolicy::ExecutorOnly => Vec::new(),
|
||||
};
|
||||
let runtime_auth = runtime_auth_provider.and(auth).cloned();
|
||||
let runtime_auth_token = runtime_auth.as_ref().and_then(|auth| auth.get_token().ok());
|
||||
let oauth_store_was_contended = oauth_credentials
|
||||
.as_ref()
|
||||
.ok()
|
||||
@@ -306,9 +290,6 @@ impl McpServerConnectionIdentity {
|
||||
resolved_environment: resolved_environment.clone(),
|
||||
local_stdio_fallback_cwd,
|
||||
referenced_environment_variables,
|
||||
runtime_auth,
|
||||
runtime_auth_token,
|
||||
runtime_auth_mode,
|
||||
codex_apps_cache_identity,
|
||||
client_elicitation_capability,
|
||||
client_mcp_extensions,
|
||||
@@ -318,19 +299,6 @@ impl McpServerConnectionIdentity {
|
||||
}
|
||||
|
||||
pub(crate) fn has_same_connection_config(&self, other: &Self) -> bool {
|
||||
let same_runtime_auth = match (&self.runtime_auth, &other.runtime_auth) {
|
||||
(Some(CodexAuth::AgentIdentity(left)), Some(CodexAuth::AgentIdentity(right))) => {
|
||||
left.record() == right.record()
|
||||
}
|
||||
(Some(left), Some(right)) => {
|
||||
left == right
|
||||
&& left.get_account_id() == right.get_account_id()
|
||||
&& left.get_chatgpt_user_id() == right.get_chatgpt_user_id()
|
||||
&& left.is_fedramp_account() == right.is_fedramp_account()
|
||||
}
|
||||
(None, None) => true,
|
||||
(Some(_), None) | (None, Some(_)) => false,
|
||||
};
|
||||
self.auth == other.auth
|
||||
&& self.credential_policy == other.credential_policy
|
||||
&& self.transport == other.transport
|
||||
@@ -346,9 +314,6 @@ impl McpServerConnectionIdentity {
|
||||
&& same_resolved_environment(&self.resolved_environment, &other.resolved_environment)
|
||||
&& self.local_stdio_fallback_cwd == other.local_stdio_fallback_cwd
|
||||
&& self.referenced_environment_variables == other.referenced_environment_variables
|
||||
&& same_runtime_auth
|
||||
&& self.runtime_auth_token == other.runtime_auth_token
|
||||
&& self.runtime_auth_mode == other.runtime_auth_mode
|
||||
&& self.codex_apps_cache_identity == other.codex_apps_cache_identity
|
||||
&& self.client_elicitation_capability == other.client_elicitation_capability
|
||||
&& self.client_mcp_extensions == other.client_mcp_extensions
|
||||
|
||||
@@ -75,9 +75,6 @@ fn connection_identity(
|
||||
McpOAuthRefreshMode::Legacy,
|
||||
&Ok(None),
|
||||
runtime_context,
|
||||
/*runtime_auth_provider*/ None,
|
||||
/*runtime_auth_mode*/ None,
|
||||
/*auth*/ None,
|
||||
/*codex_apps_cache_identity*/ None,
|
||||
ElicitationCapability::default(),
|
||||
ClientMcpExtensions::default(),
|
||||
|
||||
@@ -1,330 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::connection_manager::McpConnectionSet;
|
||||
use crate::runtime::McpRuntimeInput;
|
||||
use crate::server::McpServerMetadata;
|
||||
use crate::server::McpServerOrigin;
|
||||
use crate::tools::ToolInfo;
|
||||
use codex_exec_server::HttpClient;
|
||||
use codex_exec_server::HttpHeader;
|
||||
use codex_exec_server::HttpRedirectPolicy;
|
||||
use codex_exec_server::HttpRequestParams;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_protocol::auth::AuthMode;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use serde_json::Map;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
|
||||
pub(crate) const ENTITLEMENT_CONTEXT_KEY: &str = "openai/entitlementContext";
|
||||
const MAX_VERIFIED_ACCESS_RESPONSE_BYTES: usize = 1024 * 1024;
|
||||
const REQUESTED_ENTITLEMENTS_KEY: &str = "openai/requestedEntitlements";
|
||||
const CYBER_TRUSTED_ACCESS_ENTITLEMENT: &str = "cyber_trusted_access";
|
||||
const TRUSTED_ACCESS_TIMEOUT: Duration = Duration::from_millis(2_500);
|
||||
|
||||
impl McpConnectionSet {
|
||||
/// Installed and task-selected plugins may request supported advisory entitlement metadata.
|
||||
/// Model calls use the local, read-only, zero-argument boundary.
|
||||
pub(crate) async fn add_trusted_access_context(
|
||||
&self,
|
||||
tool: &ToolInfo,
|
||||
server: &McpServerMetadata,
|
||||
arguments: Option<&Value>,
|
||||
meta: Option<Value>,
|
||||
) -> Option<Value> {
|
||||
if tool
|
||||
.tool
|
||||
.meta
|
||||
.as_deref()
|
||||
.and_then(|meta| meta.get(REQUESTED_ENTITLEMENTS_KEY))
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|entitlements| {
|
||||
entitlements.iter().all(Value::is_string)
|
||||
&& entitlements.iter().any(|entitlement| {
|
||||
entitlement.as_str() == Some(CYBER_TRUSTED_ACCESS_ENTITLEMENT)
|
||||
})
|
||||
})
|
||||
&& self
|
||||
.plugin_id_for_mcp_server_name(&tool.server_name)
|
||||
.is_some()
|
||||
&& arguments.is_none_or(|arguments| arguments.as_object().is_some_and(Map::is_empty))
|
||||
&& server.environment_id == codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID
|
||||
&& matches!(server.origin, Some(McpServerOrigin::Stdio))
|
||||
&& tool
|
||||
.tool
|
||||
.annotations
|
||||
.as_ref()
|
||||
.and_then(|annotations| annotations.read_only_hint)
|
||||
== Some(true)
|
||||
&& let Some(context) = self.trusted_access.as_ref()
|
||||
{
|
||||
context.add_context(meta).await
|
||||
} else {
|
||||
meta
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct VerifiedAccessResponse {
|
||||
programs: Vec<Value>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct VerifiedAccessProgram {
|
||||
state: VerifiedAccessState,
|
||||
grants: Vec<VerifiedAccessGrant>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum VerifiedAccessState {
|
||||
Active,
|
||||
Inactive,
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct VerifiedAccessGrant {
|
||||
level: TrustedAccessLevel,
|
||||
source: VerifiedAccessSource,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum TrustedAccessLevel {
|
||||
Tac1,
|
||||
Tac2,
|
||||
Tac3,
|
||||
Government,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum VerifiedAccessSource {
|
||||
Individual,
|
||||
Organization,
|
||||
}
|
||||
|
||||
/// Fetches account-bound verified access for trusted, host-owned MCP metadata.
|
||||
/// Callers must authorize the receiving plugin and tool before attaching it.
|
||||
pub struct TrustedAccessContext {
|
||||
auth: CodexAuth,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
chatgpt_base_url: String,
|
||||
http_client: Arc<dyn HttpClient>,
|
||||
runtime_auth: Option<(crate::auth::McpAuthProvider, crate::McpRuntimeContext)>,
|
||||
}
|
||||
|
||||
impl TrustedAccessContext {
|
||||
pub(crate) fn from_runtime(input: &McpRuntimeInput) -> Option<Self> {
|
||||
let auth = input.auth.as_ref()?;
|
||||
if !matches!(
|
||||
auth.api_auth_mode(),
|
||||
AuthMode::Chatgpt | AuthMode::ChatgptAuthTokens
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
let mut context = Self::new(
|
||||
auth.clone(),
|
||||
input.auth_manager.clone()?,
|
||||
input.config.chatgpt_base_url.clone(),
|
||||
input.runtime_context.local_http_client(),
|
||||
);
|
||||
context.runtime_auth = input
|
||||
.runtime_auth
|
||||
.as_ref()
|
||||
.filter(|_| {
|
||||
codex_http_client::classify_openai_api_url(&input.config.chatgpt_base_url)
|
||||
!= codex_http_client::OpenAiDestination::Other
|
||||
})
|
||||
.map(|runtime| {
|
||||
(
|
||||
crate::auth::McpAuthProvider::runtime(runtime.clone(), auth.clone()),
|
||||
input.runtime_context.clone(),
|
||||
)
|
||||
});
|
||||
Some(context)
|
||||
}
|
||||
|
||||
pub fn new(
|
||||
auth: CodexAuth,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
chatgpt_base_url: String,
|
||||
http_client: Arc<dyn HttpClient>,
|
||||
) -> Self {
|
||||
Self {
|
||||
auth,
|
||||
auth_manager,
|
||||
chatgpt_base_url,
|
||||
http_client,
|
||||
runtime_auth: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces caller-supplied entitlement metadata with a fresh verified result.
|
||||
pub async fn add_context(&self, meta: Option<Value>) -> Option<Value> {
|
||||
let mut meta = match meta {
|
||||
Some(Value::Object(meta)) => meta,
|
||||
None => Map::new(),
|
||||
other => return other,
|
||||
};
|
||||
meta.remove(ENTITLEMENT_CONTEXT_KEY);
|
||||
|
||||
let status = tokio::time::timeout(TRUSTED_ACCESS_TIMEOUT, self.fetch_status())
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.unwrap_or_else(|| {
|
||||
json!({
|
||||
"schemaVersion": 1,
|
||||
"status": "unknown",
|
||||
"grants": [],
|
||||
"stale": false
|
||||
})
|
||||
});
|
||||
meta.insert(
|
||||
ENTITLEMENT_CONTEXT_KEY.to_string(),
|
||||
json!({
|
||||
"schemaVersion": 1,
|
||||
"entitlements": { "cyber_trusted_access": status }
|
||||
}),
|
||||
);
|
||||
Some(Value::Object(meta))
|
||||
}
|
||||
|
||||
async fn fetch_status(&self) -> Option<Value> {
|
||||
let auth = self.auth_manager.auth().await?;
|
||||
let expected_account_id = self
|
||||
.auth
|
||||
.get_account_id()
|
||||
.filter(|account_id| !account_id.trim().is_empty())?;
|
||||
let account_id = auth
|
||||
.get_account_id()
|
||||
.filter(|account_id| !account_id.trim().is_empty())?;
|
||||
if !matches!(
|
||||
self.auth.api_auth_mode(),
|
||||
AuthMode::Chatgpt | AuthMode::ChatgptAuthTokens
|
||||
) || !matches!(
|
||||
auth.api_auth_mode(),
|
||||
AuthMode::Chatgpt | AuthMode::ChatgptAuthTokens
|
||||
) || account_id != expected_account_id
|
||||
|| auth.get_chatgpt_user_id() != self.auth.get_chatgpt_user_id()
|
||||
|| auth.is_workspace_account() != self.auth.is_workspace_account()
|
||||
|| auth.is_fedramp_account() != self.auth.is_fedramp_account()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
let (provider, http_client) = match &self.runtime_auth {
|
||||
Some((resolver, context)) => {
|
||||
let (resolver, context) = resolver
|
||||
.resolve(context.clone(), &self.chatgpt_base_url)
|
||||
.await
|
||||
.ok()?;
|
||||
(
|
||||
resolver.resolve(&Default::default()).await.ok()?,
|
||||
context.local_http_client(),
|
||||
)
|
||||
}
|
||||
None => (
|
||||
codex_model_provider::auth_provider_from_auth(&auth),
|
||||
Arc::clone(&self.http_client),
|
||||
),
|
||||
};
|
||||
let headers = provider
|
||||
.apply_auth_headers(Default::default())
|
||||
.await
|
||||
.ok()?
|
||||
.iter()
|
||||
.map(|(name, value)| {
|
||||
Some(HttpHeader {
|
||||
name: name.as_str().to_string(),
|
||||
value: value.to_str().ok()?.to_string(),
|
||||
value_env_var: None,
|
||||
})
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()?;
|
||||
let (response, mut response_body) = http_client
|
||||
.http_request_stream(HttpRequestParams {
|
||||
method: "GET".to_string(),
|
||||
url: format!(
|
||||
"{}/accounts/verified_access",
|
||||
self.chatgpt_base_url.trim_end_matches('/')
|
||||
),
|
||||
headers,
|
||||
body: None,
|
||||
timeout_ms: Some(TRUSTED_ACCESS_TIMEOUT.as_millis() as u64),
|
||||
redirect_policy: HttpRedirectPolicy::Stop,
|
||||
request_id: "trusted-access-status".to_string(),
|
||||
stream_response: true,
|
||||
})
|
||||
.await
|
||||
.ok()?;
|
||||
if response.status != 200 {
|
||||
return None;
|
||||
}
|
||||
let mut response_bytes = Vec::new();
|
||||
while let Some(chunk) = response_body.recv().await.ok()? {
|
||||
if chunk.len() > MAX_VERIFIED_ACCESS_RESPONSE_BYTES - response_bytes.len() {
|
||||
return None;
|
||||
}
|
||||
response_bytes.extend_from_slice(&chunk);
|
||||
}
|
||||
let response: VerifiedAccessResponse = serde_json::from_slice(&response_bytes).ok()?;
|
||||
let mut programs = response
|
||||
.programs
|
||||
.into_iter()
|
||||
.filter(|program| program.get("program").and_then(Value::as_str) == Some("cyber"));
|
||||
let program = programs.next()?;
|
||||
if programs.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
let program: VerifiedAccessProgram = serde_json::from_value(program).ok()?;
|
||||
|
||||
if self.auth_manager.auth_cached().is_none_or(|current| {
|
||||
!matches!(
|
||||
current.api_auth_mode(),
|
||||
AuthMode::Chatgpt | AuthMode::ChatgptAuthTokens
|
||||
) || current.get_account_id().as_deref() != Some(account_id.as_str())
|
||||
|| current.get_chatgpt_user_id() != auth.get_chatgpt_user_id()
|
||||
|| current.is_workspace_account() != auth.is_workspace_account()
|
||||
|| current.is_fedramp_account() != auth.is_fedramp_account()
|
||||
}) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let status = match program.state {
|
||||
VerifiedAccessState::Active if !program.grants.is_empty() => "granted",
|
||||
VerifiedAccessState::Inactive if program.grants.is_empty() => "not_granted",
|
||||
VerifiedAccessState::Unavailable if program.grants.is_empty() => "unknown",
|
||||
VerifiedAccessState::Active
|
||||
| VerifiedAccessState::Inactive
|
||||
| VerifiedAccessState::Unavailable => return None,
|
||||
};
|
||||
let grants = program
|
||||
.grants
|
||||
.into_iter()
|
||||
.map(|grant| {
|
||||
let source = match grant.source {
|
||||
VerifiedAccessSource::Individual => "user",
|
||||
VerifiedAccessSource::Organization => "current_account",
|
||||
};
|
||||
json!({ "level": grant.level, "source": source })
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
Some(json!({
|
||||
"schemaVersion": 1,
|
||||
"status": status,
|
||||
"grants": grants,
|
||||
"stale": false
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "trusted_access_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,658 +0,0 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_exec_server::ByteChunk;
|
||||
use codex_exec_server::ExecServerError;
|
||||
use codex_exec_server::HttpClient;
|
||||
use codex_exec_server::HttpHeader;
|
||||
use codex_exec_server::HttpRedirectPolicy;
|
||||
use codex_exec_server::HttpRequestParams;
|
||||
use codex_exec_server::HttpRequestResponse;
|
||||
use codex_exec_server::HttpResponseBodyStream;
|
||||
use codex_login::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthHeaders;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::ExternalAuth;
|
||||
use codex_login::ExternalAuthFuture;
|
||||
use codex_login::ExternalAuthRefreshContext;
|
||||
use futures::FutureExt;
|
||||
use futures::future::BoxFuture;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
use super::MAX_VERIFIED_ACCESS_RESPONSE_BYTES;
|
||||
use super::TrustedAccessContext;
|
||||
|
||||
struct RecordingHttpClient {
|
||||
requests: Mutex<Vec<HttpRequestParams>>,
|
||||
status: u16,
|
||||
response: Vec<u8>,
|
||||
response_chunks: Option<Vec<Vec<u8>>>,
|
||||
response_gate: Option<(Notify, Notify)>,
|
||||
}
|
||||
|
||||
impl RecordingHttpClient {
|
||||
fn new(status: u16, response: Value) -> Self {
|
||||
Self {
|
||||
requests: Mutex::new(Vec::new()),
|
||||
status,
|
||||
response: serde_json::to_vec(&response).expect("serialize response"),
|
||||
response_chunks: None,
|
||||
response_gate: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HttpClient for RecordingHttpClient {
|
||||
fn http_request(
|
||||
&self,
|
||||
params: HttpRequestParams,
|
||||
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
|
||||
self.requests.lock().expect("record request").push(params);
|
||||
let response = HttpRequestResponse {
|
||||
status: self.status,
|
||||
headers: Vec::new(),
|
||||
body: ByteChunk::from(self.response.clone()),
|
||||
};
|
||||
async move {
|
||||
if let Some((requested, release)) = &self.response_gate {
|
||||
requested.notify_one();
|
||||
release.notified().await;
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
.boxed()
|
||||
}
|
||||
|
||||
fn http_request_stream(
|
||||
&self,
|
||||
params: HttpRequestParams,
|
||||
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
|
||||
self.requests.lock().expect("record request").push(params);
|
||||
let response = HttpRequestResponse {
|
||||
status: self.status,
|
||||
headers: Vec::new(),
|
||||
body: ByteChunk::from(Vec::new()),
|
||||
};
|
||||
let chunks = self
|
||||
.response_chunks
|
||||
.clone()
|
||||
.unwrap_or_else(|| vec![self.response.clone()]);
|
||||
async move {
|
||||
if let Some((requested, release)) = &self.response_gate {
|
||||
requested.notify_one();
|
||||
release.notified().await;
|
||||
}
|
||||
Ok((response, HttpResponseBodyStream::from_chunks(chunks)))
|
||||
}
|
||||
.boxed()
|
||||
}
|
||||
}
|
||||
|
||||
struct StaticExternalAuth(CodexAuth);
|
||||
|
||||
impl ExternalAuth for StaticExternalAuth {
|
||||
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async { Ok(self.0.clone()) })
|
||||
}
|
||||
|
||||
fn refresh(&self, _context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
self.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
struct SequencedExternalAuth(Mutex<VecDeque<CodexAuth>>);
|
||||
|
||||
impl ExternalAuth for SequencedExternalAuth {
|
||||
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async {
|
||||
let mut sequence = self.0.lock().expect("auth sequence");
|
||||
Ok(if sequence.len() > 1 {
|
||||
sequence.pop_front().expect("next auth")
|
||||
} else {
|
||||
sequence.front().expect("last auth").clone()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn refresh(&self, _context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
self.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
fn header_auth() -> CodexAuth {
|
||||
CodexAuth::Headers(AuthHeaders::new(
|
||||
[
|
||||
(
|
||||
"authorization".parse().unwrap(),
|
||||
"Bearer synthetic-pat".parse().unwrap(),
|
||||
),
|
||||
(
|
||||
"chatgpt-account-id".parse().unwrap(),
|
||||
"account-a".parse().unwrap(),
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
fn chatgpt_auth(account_id: &str) -> CodexAuth {
|
||||
CodexAuth::from_external_chatgpt_tokens(
|
||||
"header.e30.same",
|
||||
account_id,
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)
|
||||
.expect("test auth")
|
||||
}
|
||||
|
||||
fn fedramp_chatgpt_auth(account_id: &str) -> CodexAuth {
|
||||
CodexAuth::from_external_chatgpt_tokens(
|
||||
"header.eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF9hY2NvdW50X2lzX2ZlZHJhbXAiOnRydWV9fQ.same",
|
||||
account_id,
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)
|
||||
.expect("FedRAMP test auth")
|
||||
}
|
||||
|
||||
fn context(auth: CodexAuth, client: Arc<RecordingHttpClient>) -> TrustedAccessContext {
|
||||
TrustedAccessContext::new(
|
||||
auth.clone(),
|
||||
AuthManager::from_auth_for_testing(auth),
|
||||
"https://chatgpt.com/backend-api".to_string(),
|
||||
client,
|
||||
)
|
||||
}
|
||||
|
||||
fn cyber_response(state: &str, grants: Value) -> Value {
|
||||
json!({ "programs": [{ "program": "cyber", "state": state, "grants": grants }] })
|
||||
}
|
||||
|
||||
fn expected_metadata(status: &str, grants: Value) -> Value {
|
||||
json!({ "openai/entitlementContext": {
|
||||
"schemaVersion": 1,
|
||||
"entitlements": { "cyber_trusted_access": {
|
||||
"schemaVersion": 1,
|
||||
"status": status,
|
||||
"grants": grants,
|
||||
"stale": false
|
||||
} }
|
||||
} })
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delivers_account_bound_verified_access_to_the_calling_plugin() {
|
||||
let client = Arc::new(RecordingHttpClient::new(
|
||||
/*status*/ 200,
|
||||
cyber_response(
|
||||
"active",
|
||||
json!([
|
||||
{ "level": "tac2", "source": "individual" },
|
||||
{ "level": "government", "source": "organization" }
|
||||
]),
|
||||
),
|
||||
));
|
||||
let mut context = context(
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
client.clone(),
|
||||
);
|
||||
context.chatgpt_base_url.push('/');
|
||||
let metadata = context
|
||||
.add_context(Some(json!({ "threadId": "thread-1" })))
|
||||
.await;
|
||||
let mut expected = expected_metadata(
|
||||
"granted",
|
||||
json!([
|
||||
{ "level": "tac2", "source": "user" },
|
||||
{ "level": "government", "source": "current_account" }
|
||||
]),
|
||||
);
|
||||
expected["threadId"] = json!("thread-1");
|
||||
assert_eq!(metadata, Some(expected));
|
||||
|
||||
let mut requests = client.requests.lock().expect("inspect recorded requests");
|
||||
for request in requests.iter_mut() {
|
||||
request
|
||||
.headers
|
||||
.sort_by(|left, right| left.name.cmp(&right.name));
|
||||
}
|
||||
assert_eq!(
|
||||
*requests,
|
||||
vec![HttpRequestParams {
|
||||
method: "GET".to_string(),
|
||||
url: "https://chatgpt.com/backend-api/accounts/verified_access".to_string(),
|
||||
headers: vec![
|
||||
HttpHeader {
|
||||
name: "authorization".to_string(),
|
||||
value: "Bearer Access Token".to_string(),
|
||||
value_env_var: None,
|
||||
},
|
||||
HttpHeader {
|
||||
name: "chatgpt-account-id".to_string(),
|
||||
value: "account_id".to_string(),
|
||||
value_env_var: None,
|
||||
},
|
||||
],
|
||||
body: None,
|
||||
timeout_ms: Some(2_500),
|
||||
redirect_policy: HttpRedirectPolicy::Stop,
|
||||
request_id: "trusted-access-status".to_string(),
|
||||
stream_response: true,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_auth_without_a_nonempty_account_id() -> anyhow::Result<()> {
|
||||
for account_id in [None, Some(""), Some(" ")] {
|
||||
let home = tempfile::tempdir()?;
|
||||
std::fs::write(
|
||||
home.path().join("auth.json"),
|
||||
serde_json::to_vec(&json!({
|
||||
"auth_mode": "chatgpt",
|
||||
"tokens": {
|
||||
"id_token": "header.eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF91c2VyX2lkIjoidXNlci1hIn19.signature",
|
||||
"access_token": "synthetic-access-token",
|
||||
"refresh_token": "synthetic-refresh-token",
|
||||
"account_id": account_id
|
||||
},
|
||||
"last_refresh": "2099-01-01T00:00:00Z"
|
||||
}))?,
|
||||
)?;
|
||||
let auth = CodexAuth::from_auth_storage(
|
||||
home.path(),
|
||||
AuthCredentialsStoreMode::File,
|
||||
/*chatgpt_base_url*/ None,
|
||||
AuthKeyringBackendKind::default(),
|
||||
&codex_login::test_support::transport_default_auth_route_config(),
|
||||
)
|
||||
.await?
|
||||
.expect("managed ChatGPT auth");
|
||||
let client = Arc::new(RecordingHttpClient::new(
|
||||
/*status*/ 200,
|
||||
cyber_response(
|
||||
"active",
|
||||
json!([{ "level": "tac1", "source": "individual" }]),
|
||||
),
|
||||
));
|
||||
assert_eq!(
|
||||
context(auth, client.clone())
|
||||
.add_context(/*meta*/ None)
|
||||
.await,
|
||||
Some(expected_metadata("unknown", json!([]))),
|
||||
"account_id={account_id:?}"
|
||||
);
|
||||
assert!(client.requests.lock().expect("inspect requests").is_empty());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_api_key_authentication_without_sending_credentials() {
|
||||
let client = Arc::new(RecordingHttpClient::new(
|
||||
/*status*/ 200,
|
||||
json!({ "programs": [] }),
|
||||
));
|
||||
let context = context(CodexAuth::from_api_key("test-api-key"), client.clone());
|
||||
|
||||
let metadata = context
|
||||
.add_context(Some(json!({
|
||||
"threadId": "thread-1",
|
||||
"openai/entitlementContext": { "forged": true }
|
||||
})))
|
||||
.await;
|
||||
|
||||
let mut expected = expected_metadata("unknown", json!([]));
|
||||
expected["threadId"] = json!("thread-1");
|
||||
assert_eq!(metadata, Some(expected));
|
||||
assert!(client.requests.lock().expect("inspect requests").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_initial_unsupported_auth_after_switch_to_chatgpt() {
|
||||
let client = Arc::new(RecordingHttpClient::new(
|
||||
/*status*/ 200,
|
||||
cyber_response(
|
||||
"active",
|
||||
json!([{ "level": "tac1", "source": "individual" }]),
|
||||
),
|
||||
));
|
||||
let mut context = context(header_auth(), client.clone());
|
||||
context.auth_manager = AuthManager::from_auth_for_testing(chatgpt_auth("account-a"));
|
||||
|
||||
assert_eq!(
|
||||
context.add_context(/*meta*/ None).await,
|
||||
Some(expected_metadata("unknown", json!([])))
|
||||
);
|
||||
assert!(client.requests.lock().expect("inspect requests").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn maps_verified_access_states_and_rejects_invalid_provider_responses() {
|
||||
let cases = [
|
||||
(
|
||||
200,
|
||||
json!({ "programs": [
|
||||
{ "program": "future", "state": "pending", "grants": [{ "level": "premium", "source": "subscription" }] },
|
||||
{ "program": "cyber", "state": "active", "grants": [{ "level": "tac1", "source": "individual" }] }
|
||||
] }),
|
||||
expected_metadata("granted", json!([{ "level": "tac1", "source": "user" }])),
|
||||
),
|
||||
(
|
||||
200,
|
||||
cyber_response("inactive", json!([])),
|
||||
expected_metadata("not_granted", json!([])),
|
||||
),
|
||||
(
|
||||
200,
|
||||
cyber_response("unavailable", json!([])),
|
||||
expected_metadata("unknown", json!([])),
|
||||
),
|
||||
(
|
||||
200,
|
||||
json!({ "programs": [{ "program": "other", "state": "active", "grants": [] }] }),
|
||||
expected_metadata("unknown", json!([])),
|
||||
),
|
||||
(
|
||||
200,
|
||||
cyber_response(
|
||||
"active",
|
||||
json!([{ "level": "admin", "source": "individual" }]),
|
||||
),
|
||||
expected_metadata("unknown", json!([])),
|
||||
),
|
||||
(
|
||||
200,
|
||||
cyber_response("active", json!([])),
|
||||
expected_metadata("unknown", json!([])),
|
||||
),
|
||||
(
|
||||
403,
|
||||
json!({ "error": "forbidden" }),
|
||||
expected_metadata("unknown", json!([])),
|
||||
),
|
||||
];
|
||||
|
||||
for (response_status, response, expected) in cases {
|
||||
let response_description = response.to_string();
|
||||
let context = context(
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
Arc::new(RecordingHttpClient::new(response_status, response)),
|
||||
);
|
||||
let metadata = context.add_context(/*meta*/ None).await.expect("metadata");
|
||||
assert_eq!(
|
||||
metadata, expected,
|
||||
"HTTP {response_status}: {response_description}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn replaces_untrusted_entitlements_on_malformed_response() {
|
||||
let mut client = RecordingHttpClient::new(/*status*/ 200, Value::Null);
|
||||
client.response = b"{\"programs\":[".to_vec();
|
||||
let context = context(chatgpt_auth("account-a"), Arc::new(client));
|
||||
let mut expected = expected_metadata("unknown", json!([]));
|
||||
expected["threadId"] = json!("thread-1");
|
||||
|
||||
assert_eq!(
|
||||
context
|
||||
.add_context(Some(json!({
|
||||
"threadId": "thread-1",
|
||||
"openai/entitlementContext": { "forged": true }
|
||||
})))
|
||||
.await,
|
||||
Some(expected)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_verified_access_response_larger_than_one_mebibyte() {
|
||||
let valid_response = serde_json::to_vec(&cyber_response(
|
||||
"active",
|
||||
json!([{ "level": "tac1", "source": "individual" }]),
|
||||
))
|
||||
.expect("serialize response");
|
||||
let mut client = RecordingHttpClient::new(/*status*/ 200, Value::Null);
|
||||
client.response_chunks = Some(vec![
|
||||
vec![b' '; MAX_VERIFIED_ACCESS_RESPONSE_BYTES],
|
||||
valid_response,
|
||||
]);
|
||||
client.response = client
|
||||
.response_chunks
|
||||
.as_ref()
|
||||
.expect("response chunks")
|
||||
.concat();
|
||||
|
||||
assert_eq!(
|
||||
context(chatgpt_auth("account-a"), Arc::new(client))
|
||||
.add_context(/*meta*/ None)
|
||||
.await,
|
||||
Some(expected_metadata("unknown", json!([])))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn returns_unknown_at_the_lookup_deadline() {
|
||||
let mut client = RecordingHttpClient::new(/*status*/ 200, Value::Null);
|
||||
client.response_gate = Some((Notify::new(), Notify::new()));
|
||||
let client = Arc::new(client);
|
||||
let context = context(chatgpt_auth("account-a"), client.clone());
|
||||
let lookup = context.add_context(/*meta*/ None);
|
||||
tokio::pin!(lookup);
|
||||
|
||||
assert!(futures::poll!(lookup.as_mut()).is_pending());
|
||||
assert_eq!(client.requests.lock().expect("recorded requests").len(), 1);
|
||||
tokio::time::advance(Duration::from_millis(2_499)).await;
|
||||
assert!(futures::poll!(lookup.as_mut()).is_pending());
|
||||
tokio::time::advance(Duration::from_millis(1)).await;
|
||||
assert_eq!(
|
||||
lookup
|
||||
.now_or_never()
|
||||
.expect("lookup must finish at the deadline"),
|
||||
Some(expected_metadata("unknown", json!([])))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_duplicate_cyber_programs() {
|
||||
let active = json!({
|
||||
"program": "cyber", "state": "active",
|
||||
"grants": [{ "level": "tac1", "source": "individual" }]
|
||||
});
|
||||
for other in [
|
||||
active.clone(),
|
||||
json!({ "program": "cyber", "state": "inactive", "grants": [] }),
|
||||
json!({ "program": "cyber" }),
|
||||
] {
|
||||
for programs in [json!([active, other]), json!([other, active])] {
|
||||
let context = context(
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
Arc::new(RecordingHttpClient::new(
|
||||
/*status*/ 200,
|
||||
json!({ "programs": programs }),
|
||||
)),
|
||||
);
|
||||
assert_eq!(
|
||||
context.add_context(/*meta*/ None).await,
|
||||
Some(expected_metadata("unknown", json!([]))),
|
||||
"duplicate programs: {programs}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_identity_changes_before_sending_credentials() {
|
||||
for (description, initial_auth, selected_auth) in [
|
||||
(
|
||||
"account switch",
|
||||
chatgpt_auth("account-a"),
|
||||
chatgpt_auth("account-b"),
|
||||
),
|
||||
(
|
||||
"standard to FedRAMP",
|
||||
chatgpt_auth("account-a"),
|
||||
fedramp_chatgpt_auth("account-a"),
|
||||
),
|
||||
(
|
||||
"FedRAMP to standard",
|
||||
fedramp_chatgpt_auth("account-a"),
|
||||
chatgpt_auth("account-a"),
|
||||
),
|
||||
] {
|
||||
let client = Arc::new(RecordingHttpClient::new(
|
||||
/*status*/ 200,
|
||||
cyber_response(
|
||||
"active",
|
||||
json!([{ "level": "tac1", "source": "individual" }]),
|
||||
),
|
||||
));
|
||||
let mut context = context(initial_auth, client.clone());
|
||||
context.auth_manager = AuthManager::from_auth_for_testing(selected_auth);
|
||||
assert_eq!(
|
||||
context.add_context(/*meta*/ None).await,
|
||||
Some(expected_metadata("unknown", json!([]))),
|
||||
"identity change before the request: {description}"
|
||||
);
|
||||
assert!(
|
||||
client.requests.lock().expect("inspect requests").is_empty(),
|
||||
"identity change before the request: {description}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn uses_the_checked_auth_snapshot_for_request_headers() -> anyhow::Result<()> {
|
||||
let client = Arc::new(RecordingHttpClient::new(
|
||||
/*status*/ 200,
|
||||
cyber_response("inactive", json!([])),
|
||||
));
|
||||
let context = context(chatgpt_auth("account-a"), client.clone());
|
||||
let refreshed = CodexAuth::from_external_chatgpt_tokens(
|
||||
"header.e30.refreshed",
|
||||
"account-a",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?;
|
||||
context
|
||||
.auth_manager
|
||||
.set_external_auth(Arc::new(SequencedExternalAuth(Mutex::new(VecDeque::from(
|
||||
[context.auth.clone(), refreshed, header_auth()],
|
||||
)))))
|
||||
.await?;
|
||||
|
||||
assert_eq!(
|
||||
context.add_context(/*meta*/ None).await,
|
||||
Some(expected_metadata("not_granted", json!([])))
|
||||
);
|
||||
let requests = client.requests.lock().expect("recorded requests");
|
||||
assert_eq!(requests.len(), 1);
|
||||
let authorization = requests[0]
|
||||
.headers
|
||||
.iter()
|
||||
.find(|header| header.name == "authorization");
|
||||
assert_eq!(
|
||||
authorization,
|
||||
Some(&HttpHeader {
|
||||
name: "authorization".to_string(),
|
||||
value: "Bearer header.e30.refreshed".to_string(),
|
||||
value_env_var: None,
|
||||
})
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_identity_changes_while_request_is_in_flight() -> anyhow::Result<()> {
|
||||
let personal = chatgpt_auth("account-a");
|
||||
let workspace =
|
||||
CodexAuth::from_external_chatgpt_tokens("header.e30.same", "account-a", Some("team"))?;
|
||||
for (description, initial_auth, selected_auth) in [
|
||||
(
|
||||
"account switch",
|
||||
personal.clone(),
|
||||
Some(chatgpt_auth("account-b")),
|
||||
),
|
||||
("logout", personal.clone(), None),
|
||||
(
|
||||
"personal to workspace",
|
||||
personal.clone(),
|
||||
Some(workspace.clone()),
|
||||
),
|
||||
("workspace to personal", workspace, Some(personal)),
|
||||
(
|
||||
"auth mode change",
|
||||
chatgpt_auth("account-a"),
|
||||
Some(header_auth()),
|
||||
),
|
||||
(
|
||||
"standard to FedRAMP",
|
||||
chatgpt_auth("account-a"),
|
||||
Some(fedramp_chatgpt_auth("account-a")),
|
||||
),
|
||||
(
|
||||
"FedRAMP to standard",
|
||||
fedramp_chatgpt_auth("account-a"),
|
||||
Some(chatgpt_auth("account-a")),
|
||||
),
|
||||
] {
|
||||
let mut client = RecordingHttpClient::new(
|
||||
/*status*/ 200,
|
||||
cyber_response(
|
||||
"active",
|
||||
json!([{ "level": "tac1", "source": "individual" }]),
|
||||
),
|
||||
);
|
||||
client.response_gate = Some((Notify::new(), Notify::new()));
|
||||
let client = Arc::new(client);
|
||||
let request_is_fedramp = initial_auth.is_fedramp_account();
|
||||
let context = context(initial_auth, client.clone());
|
||||
let auth_manager = &context.auth_manager;
|
||||
auth_manager
|
||||
.set_external_auth(Arc::new(StaticExternalAuth(context.auth.clone())))
|
||||
.await?;
|
||||
|
||||
let (metadata, auth_change) = tokio::join!(context.add_context(/*meta*/ None), async {
|
||||
let (requested, release) = client.response_gate.as_ref().expect("gated response");
|
||||
tokio::time::timeout(Duration::from_secs(5), requested.notified()).await?;
|
||||
{
|
||||
let requests = client.requests.lock().expect("inspect request");
|
||||
assert_eq!(requests.len(), 1);
|
||||
assert!(requests[0].headers.iter().any(|header| {
|
||||
header.name.eq_ignore_ascii_case("chatgpt-account-id")
|
||||
&& header.value == "account-a"
|
||||
}));
|
||||
assert_eq!(
|
||||
requests[0]
|
||||
.headers
|
||||
.iter()
|
||||
.any(|header| header.name.eq_ignore_ascii_case("x-openai-fedramp")),
|
||||
request_is_fedramp
|
||||
);
|
||||
}
|
||||
if let Some(auth) = selected_auth {
|
||||
auth_manager
|
||||
.set_external_auth(Arc::new(StaticExternalAuth(auth)))
|
||||
.await?;
|
||||
} else {
|
||||
auth_manager.clear_external_auth();
|
||||
}
|
||||
release.notify_one();
|
||||
Ok::<(), anyhow::Error>(())
|
||||
});
|
||||
auth_change?;
|
||||
|
||||
assert_eq!(
|
||||
metadata,
|
||||
Some(expected_metadata("unknown", json!([]))),
|
||||
"auth change after the request: {description}"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user