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

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

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

View File

@@ -8,9 +8,7 @@ use ctor::ctor;
use std::sync::OnceLock;
use tempfile::TempDir;
use codex_config::CloudConfigBundleLoader;
use codex_config::LoaderOverrides;
use codex_config::test_support::CloudConfigBundleFixture;
use codex_config::test_support::ManagedConfigFixture;
use codex_core::CodexThread;
use codex_core::config::Config;
use codex_core::config::ConfigBuilder;
@@ -24,7 +22,7 @@ use regex_lite::Regex;
use std::path::Path;
use std::path::PathBuf;
pub mod apps_test_server;
pub mod mcp_test_server;
#[cfg(unix)]
pub mod code_mode_host;
pub mod context_snapshot;
@@ -34,7 +32,6 @@ pub mod network_policy_mcp;
pub mod oauth;
pub mod process;
pub mod responses;
pub mod runtime_auth;
pub mod startup;
pub mod streaming_sse;
pub mod test_codex;
@@ -200,31 +197,31 @@ pub fn fetch_dotslash_file(
/// temporary directory. Using a per-test directory keeps tests hermetic and
/// avoids clobbering a developer’s real `~/.codex`.
pub async fn load_default_config_for_test(codex_home: &TempDir) -> Config {
load_default_config_for_test_with_cloud_config_bundle(
codex_home,
CloudConfigBundleLoader::default(),
)
.await
load_default_config_for_test_with_managed_config(codex_home, ManagedConfigFixture::default())
.await
}
/// Returns a default `Config` with test-provided cloud bundle requirements applied.
/// during config construction.
pub async fn load_default_config_for_test_with_cloud_config_bundle(
/// Returns a default `Config` with test-provided local managed requirements and
/// config applied. The fixture is written below `codex_home` and loaded as the
/// system `requirements.toml` / `config.toml`.
pub async fn load_default_config_for_test_with_managed_config(
codex_home: &TempDir,
cloud_config_bundle: CloudConfigBundleLoader,
managed_config: ManagedConfigFixture,
) -> Config {
let loader_overrides = managed_config
.loader_overrides_for_tests(codex_home.path())
.expect("managed config fixture should be writable");
ConfigBuilder::default()
.loader_overrides(LoaderOverrides::without_managed_config_for_tests())
.loader_overrides(loader_overrides)
.codex_home(codex_home.path().to_path_buf())
.harness_overrides(default_test_overrides())
.cloud_config_bundle(cloud_config_bundle)
.build()
.await
.expect("defaults for test should always succeed")
}
pub fn managed_network_requirements_loader() -> CloudConfigBundleLoader {
CloudConfigBundleFixture::loader_with_enterprise_requirement(
pub fn managed_network_requirements() -> ManagedConfigFixture {
ManagedConfigFixture::requirements(
r#"
[experimental_network]
enabled = true

View File

@@ -1,14 +1,11 @@
use crate::PathExt;
//! Mock streamable HTTP MCP server for tests that exercise generic MCP behaviour through a
//! user-configured `[mcp_servers.calendar]` registration.
use crate::test_codex::TestCodexBuilder;
use crate::test_codex::test_codex;
use anyhow::Result;
use codex_config::types::AppToolApproval;
use codex_core::config::Config;
use codex_extension_api::ExtensionFuture;
use codex_extension_api::McpServerContribution;
use codex_extension_api::McpServerContributionContext;
use codex_extension_api::McpServerContributor;
use codex_features::Feature;
use codex_login::CodexAuth;
use codex_models_manager::bundled_models_response;
use codex_protocol::config_types::ApprovalsReviewer;
@@ -27,85 +24,58 @@ use wiremock::Request;
use wiremock::Respond;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::path_regex;
const CONNECTOR_ID: &str = "calendar";
pub const LINK_ID: &str = "link_calendar";
const CONNECTOR_NAME: &str = "Calendar";
const DISCOVERABLE_CALENDAR_ID: &str = "connector_2128aebfecb84f64a069897515042a44";
const DISCOVERABLE_GMAIL_ID: &str = "connector_68df038e0ba48191908c8434991bbac2";
const CONNECTOR_DESCRIPTION: &str = "Plan events and manage your calendar.";
const CODEX_APPS_META_KEY: &str = "_codex_apps";
const CODEX_APPS_MCP_PATH_REGEX: &str = "^/(?:api/codex|backend-api)/ps/mcp/?$";
const HOSTED_PLUGIN_RUNTIME_MCP_PATH_REGEX: &str = "^/(?:api/codex|backend-api)/ps/mcp/?$";
/// Name of the user-configured MCP server registration backed by this mock.
pub const MCP_TEST_SERVER_NAME: &str = "calendar";
/// URL path of the mock MCP endpoint.
pub const MCP_TEST_SERVER_PATH: &str = "/mcp";
const MCP_PATH_REGEX: &str = "^/mcp/?$";
const PROTOCOL_VERSION: &str = "2025-11-25";
const SERVER_NAME: &str = "codex-apps-test";
const SERVER_NAME: &str = "calendar-mcp-test";
const SERVER_VERSION: &str = "1.0.0";
const SEARCHABLE_TOOL_COUNT: usize = 100;
const CALENDAR_CREATE_EVENT_TOOL_NAME: &str = "calendar_create_event";
const CALENDAR_APP_ONLY_TOOL_NAME: &str = "calendar_app_only_action";
pub const CALENDAR_CREATE_EVENT_TOOL_NAME: &str = "calendar_create_event";
pub const CALENDAR_APP_ONLY_TOOL_NAME: &str = "calendar_app_only_action";
pub const CALENDAR_EXTRACT_TEXT_TOOL_NAME: &str = "calendar_extract_text";
const CALENDAR_LIST_EVENTS_TOOL_NAME: &str = "calendar_list_events";
pub const DIRECT_CALENDAR_CREATE_EVENT_TOOL: &str = "mcp__codex_apps__calendar__create_event";
pub const DIRECT_CALENDAR_APP_ONLY_TOOL: &str = "mcp__codex_apps__calendar__app_only_action";
pub const DIRECT_CALENDAR_LIST_EVENTS_TOOL: &str = "mcp__codex_apps__calendar__list_events";
pub const DIRECT_CALENDAR_EXTRACT_TEXT_TOOL: &str = "mcp__codex_apps__calendar__extract_text";
pub const SEARCH_CALENDAR_NAMESPACE: &str = "mcp__codex_apps__calendar";
pub const SEARCH_CALENDAR_APP_ONLY_TOOL: &str = "_app_only_action";
pub const SEARCH_CALENDAR_CREATE_TOOL: &str = "_create_event";
pub const SEARCH_CALENDAR_EXTRACT_TEXT_TOOL: &str = "_extract_text";
pub const SEARCH_CALENDAR_LIST_TOOL: &str = "_list_events";
pub const CALENDAR_CREATE_EVENT_RESOURCE_URI: &str =
"connector://calendar/tools/calendar_create_event";
pub const CALENDAR_LIST_EVENTS_TOOL_NAME: &str = "calendar_list_events";
/// Model-visible namespace of the mock server's tools.
pub const CALENDAR_NAMESPACE: &str = "mcp__calendar";
/// Flattened model-visible names (namespace + raw tool name).
pub const DIRECT_CALENDAR_CREATE_EVENT_TOOL: &str = "mcp__calendar__calendar_create_event";
pub const DIRECT_CALENDAR_APP_ONLY_TOOL: &str = "mcp__calendar__calendar_app_only_action";
pub const DIRECT_CALENDAR_LIST_EVENTS_TOOL: &str = "mcp__calendar__calendar_list_events";
pub const DIRECT_CALENDAR_EXTRACT_TEXT_TOOL: &str = "mcp__calendar__calendar_extract_text";
pub const CALENDAR_CREATE_EVENT_MCP_APP_RESOURCE_URI: &str =
"ui://widget/calendar-create-event.html";
const CALENDAR_LIST_EVENTS_RESOURCE_URI: &str = "connector://calendar/tools/calendar_list_events";
pub const DOCUMENT_EXTRACT_TEXT_RESOURCE_URI: &str =
"connector://calendar/tools/calendar_extract_text";
type AppsStartupInitializeGate = Arc<Mutex<VecDeque<mpsc::Receiver<()>>>>;
type McpStartupInitializeGate = Arc<Mutex<VecDeque<mpsc::Receiver<()>>>>;
pub struct HostedMessagingServer(pub String);
#[derive(Clone)]
pub struct McpTestServer {
/// Base URL of the mock server; the MCP endpoint lives at [`MCP_TEST_SERVER_PATH`].
pub base_url: String,
}
impl McpServerContributor<Config> for HostedMessagingServer {
fn id(&self) -> &'static str {
"hosted_user_messaging_fixture"
}
fn contribute<'a>(
&'a self,
_context: McpServerContributionContext<'a, Config>,
) -> ExtensionFuture<'a, Vec<McpServerContribution>> {
Box::pin(async move {
vec![McpServerContribution::HostedApps {
config: Box::new(
serde_json::from_value(json!({
"url": self.0,
"default_tools_approval_mode": "approve",
"supports_parallel_tool_calls": true
}))
.expect("host-owned messaging MCP config"),
),
protocol_mode: None,
}]
})
impl McpTestServer {
/// Full URL of the mock MCP endpoint.
pub fn mcp_url(&self) -> String {
mcp_test_server_url(&self.base_url)
}
}
#[derive(Clone)]
pub struct AppsTestServer {
pub chatgpt_base_url: String,
pub fn mcp_test_server_url(base_url: &str) -> String {
format!("{}{MCP_TEST_SERVER_PATH}", base_url.trim_end_matches('/'))
}
#[derive(Clone)]
pub struct AppsTestServerStartupControl {
pub struct McpTestServerStartupControl {
initialize_attempts: Arc<AtomicUsize>,
remaining_initialize_failures: Arc<AtomicUsize>,
successful_initialize_gate: AppsStartupInitializeGate,
successful_initialize_gate: McpStartupInitializeGate,
}
impl AppsTestServerStartupControl {
impl McpTestServerStartupControl {
pub fn fail_next_initialize_attempts(&self, attempts: usize) {
self.remaining_initialize_failures
.store(attempts, Ordering::SeqCst);
@@ -121,132 +91,86 @@ impl AppsTestServerStartupControl {
let (release, gate) = mpsc::channel();
self.successful_initialize_gate
.lock()
.expect("Apps initialization gate lock should not be poisoned")
.expect("MCP initialization gate lock should not be poisoned")
.push_back(gate);
release
}
}
#[derive(Clone, Copy)]
pub enum AppsTestToolLoading {
pub enum McpTestToolLoading {
Direct,
Searchable,
}
#[derive(Clone)]
enum AppsTestToolsListBehavior {
enum McpTestToolsListBehavior {
AlwaysAvailable,
AvailableWhen(Arc<AtomicBool>),
AlwaysUnavailable,
Custom(Arc<Mutex<Vec<Value>>>),
}
impl AppsTestServer {
impl McpTestServer {
pub async fn mount(server: &MockServer) -> Result<Self> {
Self::mount_with_connector_name(server, CONNECTOR_NAME).await
}
pub async fn mount_searchable(server: &MockServer) -> Result<Self> {
mount_oauth_metadata(server).await;
mount_connectors_directory(server).await;
mount_streamable_http_json_rpc(
Self::mount_with(
server,
CONNECTOR_NAME.to_string(),
CONNECTOR_DESCRIPTION.to_string(),
/*searchable*/ true,
/*include_app_only_tool*/ false,
AppsTestToolsListBehavior::AlwaysAvailable,
)
.await;
Ok(Self {
chatgpt_base_url: server.uri(),
})
}
pub async fn mount_hosted_plugin_runtime_searchable(server: &MockServer) -> Result<Self> {
mount_oauth_metadata(server).await;
mount_connectors_directory(server).await;
mount_streamable_http_json_rpc_at_path(
server,
HOSTED_PLUGIN_RUNTIME_MCP_PATH_REGEX,
CONNECTOR_NAME.to_string(),
CONNECTOR_DESCRIPTION.to_string(),
/*searchable*/ true,
/*include_app_only_tool*/ false,
AppsTestToolsListBehavior::AlwaysAvailable,
)
.await;
Ok(Self {
chatgpt_base_url: server.uri(),
})
}
pub async fn mount_with_connector_name(
server: &MockServer,
connector_name: &str,
) -> Result<Self> {
mount_oauth_metadata(server).await;
mount_connectors_directory(server).await;
mount_streamable_http_json_rpc(
server,
connector_name.to_string(),
CONNECTOR_DESCRIPTION.to_string(),
/*searchable*/ false,
/*include_app_only_tool*/ false,
AppsTestToolsListBehavior::AlwaysAvailable,
McpTestToolsListBehavior::AlwaysAvailable,
)
.await;
Ok(Self {
chatgpt_base_url: server.uri(),
})
.await
}
/// Mounts the server with enough extra tools to push tool loading into search mode.
pub async fn mount_searchable(server: &MockServer) -> Result<Self> {
Self::mount_with(
server,
/*searchable*/ true,
/*include_app_only_tool*/ false,
McpTestToolsListBehavior::AlwaysAvailable,
)
.await
}
pub async fn mount_with_app_only_tool(
server: &MockServer,
tool_loading: AppsTestToolLoading,
tool_loading: McpTestToolLoading,
) -> Result<Self> {
mount_oauth_metadata(server).await;
mount_connectors_directory(server).await;
mount_streamable_http_json_rpc(
Self::mount_with(
server,
CONNECTOR_NAME.to_string(),
CONNECTOR_DESCRIPTION.to_string(),
matches!(tool_loading, AppsTestToolLoading::Searchable),
matches!(tool_loading, McpTestToolLoading::Searchable),
/*include_app_only_tool*/ true,
AppsTestToolsListBehavior::AlwaysAvailable,
McpTestToolsListBehavior::AlwaysAvailable,
)
.await;
Ok(Self {
chatgpt_base_url: server.uri(),
})
.await
}
pub async fn mount_with_startup_control(
server: &MockServer,
) -> Result<(Self, AppsTestServerStartupControl)> {
mount_oauth_metadata(server).await;
mount_connectors_directory(server).await;
let control = AppsTestServerStartupControl {
) -> Result<(Self, McpTestServerStartupControl)> {
let control = McpTestServerStartupControl {
initialize_attempts: Arc::new(AtomicUsize::new(0)),
remaining_initialize_failures: Arc::new(AtomicUsize::new(0)),
successful_initialize_gate: Arc::new(Mutex::new(VecDeque::new())),
};
mount_streamable_http_json_rpc_with_startup_control(
mount_streamable_http_json_rpc(
server,
CODEX_APPS_MCP_PATH_REGEX,
CONNECTOR_NAME.to_string(),
CONNECTOR_DESCRIPTION.to_string(),
/*searchable*/ true,
/*include_app_only_tool*/ false,
AppsTestToolsListBehavior::AlwaysAvailable,
Some(Arc::clone(&control.initialize_attempts)),
Some(Arc::clone(&control.remaining_initialize_failures)),
Some(Arc::clone(&control.successful_initialize_gate)),
McpJsonRpcResponder {
searchable: true,
include_app_only_tool: false,
tools_list_behavior: McpTestToolsListBehavior::AlwaysAvailable,
initialize_attempts: Some(Arc::clone(&control.initialize_attempts)),
remaining_initialize_failures: Some(Arc::clone(
&control.remaining_initialize_failures,
)),
successful_initialize_gate: Some(Arc::clone(&control.successful_initialize_gate)),
},
)
.await;
Ok((
Self {
chatgpt_base_url: server.uri(),
base_url: server.uri(),
},
control,
))
@@ -256,9 +180,11 @@ impl AppsTestServer {
server: &MockServer,
tools_available: Arc<AtomicBool>,
) -> Result<Self> {
Self::mount_with_tools_list_behavior(
Self::mount_with(
server,
AppsTestToolsListBehavior::AvailableWhen(tools_available),
/*searchable*/ false,
/*include_app_only_tool*/ false,
McpTestToolsListBehavior::AvailableWhen(tools_available),
)
.await
}
@@ -267,31 +193,45 @@ impl AppsTestServer {
server: &MockServer,
tools: Arc<Mutex<Vec<Value>>>,
) -> Result<Self> {
Self::mount_with_tools_list_behavior(server, AppsTestToolsListBehavior::Custom(tools)).await
Self::mount_with(
server,
/*searchable*/ false,
/*include_app_only_tool*/ false,
McpTestToolsListBehavior::Custom(tools),
)
.await
}
pub async fn mount_without_tools(server: &MockServer) -> Result<Self> {
Self::mount_with_tools_list_behavior(server, AppsTestToolsListBehavior::AlwaysUnavailable)
.await
}
async fn mount_with_tools_list_behavior(
server: &MockServer,
tools_list_behavior: AppsTestToolsListBehavior,
) -> Result<Self> {
mount_oauth_metadata(server).await;
mount_connectors_directory(server).await;
mount_streamable_http_json_rpc(
Self::mount_with(
server,
CONNECTOR_NAME.to_string(),
CONNECTOR_DESCRIPTION.to_string(),
/*searchable*/ false,
/*include_app_only_tool*/ false,
tools_list_behavior,
McpTestToolsListBehavior::AlwaysUnavailable,
)
.await
}
async fn mount_with(
server: &MockServer,
searchable: bool,
include_app_only_tool: bool,
tools_list_behavior: McpTestToolsListBehavior,
) -> Result<Self> {
mount_streamable_http_json_rpc(
server,
McpJsonRpcResponder {
searchable,
include_app_only_tool,
tools_list_behavior,
initialize_attempts: None,
remaining_initialize_failures: None,
successful_initialize_gate: None,
},
)
.await;
Ok(Self {
chatgpt_base_url: server.uri(),
base_url: server.uri(),
})
}
}
@@ -308,61 +248,83 @@ pub fn configure_search_capable_model(config: &mut Config) {
config.model_catalog = Some(model_catalog);
}
fn configure_apps(config: &mut Config, apps_base_url: &str) {
config
.features
.enable(Feature::Apps)
.expect("test config should allow feature update");
config.chatgpt_base_url = apps_base_url.to_string();
/// The `[mcp_servers.calendar]` registration pointing at the mock server.
pub fn mcp_test_server_config(base_url: &str) -> codex_config::McpServerConfig {
#[expect(clippy::expect_used, reason = "static test config is valid")]
serde_json::from_value(json!({
"url": mcp_test_server_url(base_url),
"startup_timeout_sec": 30,
}))
.expect("valid mock MCP server config")
}
pub fn configure_search_capable_apps(config: &mut Config, apps_base_url: &str) {
configure_apps(config, apps_base_url);
/// Adds the mock server as the user-configured `calendar` MCP server.
pub fn configure_mcp_test_server(config: &mut Config, base_url: &str) {
let mut servers = config.mcp_servers.get().clone();
servers.insert(
MCP_TEST_SERVER_NAME.to_string(),
mcp_test_server_config(base_url),
);
config
.mcp_servers
.set(servers)
.expect("test config should accept MCP servers");
}
/// Updates the `calendar` registration in place.
pub fn update_mcp_test_server_config(
config: &mut Config,
update: impl FnOnce(&mut codex_config::McpServerConfig),
) {
let mut servers = config.mcp_servers.get().clone();
let server = servers
.get_mut(MCP_TEST_SERVER_NAME)
.expect("calendar MCP server should be configured");
update(server);
config
.mcp_servers
.set(servers)
.expect("test config should accept MCP servers");
}
pub fn configure_search_capable_mcp_test_server(config: &mut Config, base_url: &str) {
configure_mcp_test_server(config, base_url);
configure_search_capable_model(config);
}
pub fn apps_enabled_builder(apps_base_url: impl Into<String>) -> TestCodexBuilder {
let apps_base_url = apps_base_url.into();
pub fn mcp_server_builder(base_url: impl Into<String>) -> TestCodexBuilder {
let base_url = base_url.into();
test_codex()
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
.with_config(move |config| configure_apps(config, apps_base_url.as_str()))
.with_auth(CodexAuth::from_api_key("Test API Key"))
.with_config(move |config| configure_mcp_test_server(config, base_url.as_str()))
}
pub fn set_default_app_approval_mode_and_reviewer(
/// Sets the default tool approval mode of the `calendar` server and the session reviewer.
pub fn set_mcp_test_server_approval_mode_and_reviewer(
config: &mut Config,
approval_mode: AppToolApproval,
reviewer: ApprovalsReviewer,
) {
let path = config.codex_home.join("config.toml").abs();
let user_config = serde_json::from_value(json!({
"apps": { "_default": {
"approvals_reviewer": reviewer,
"default_tools_approval_mode": approval_mode,
} }
}))
.expect("apps config should parse");
config.config_layer_stack = config
.config_layer_stack
.with_user_config(&path, user_config)
.expect("apps user config should be valid");
update_mcp_test_server_config(config, |server| {
server.default_tools_approval_mode = Some(approval_mode);
});
config.approvals_reviewer = reviewer;
}
pub fn search_capable_apps_builder(apps_base_url: impl Into<String>) -> TestCodexBuilder {
let apps_base_url = apps_base_url.into();
pub fn search_capable_mcp_server_builder(base_url: impl Into<String>) -> TestCodexBuilder {
let base_url = base_url.into();
test_codex()
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
.with_config(move |config| configure_search_capable_apps(config, apps_base_url.as_str()))
.with_auth(CodexAuth::from_api_key("Test API Key"))
.with_config(move |config| {
configure_search_capable_mcp_test_server(config, base_url.as_str())
})
}
fn apps_tool_call_id(body: &Value) -> Option<&str> {
body.get("params")?
.get("_meta")?
.get(CODEX_APPS_META_KEY)?
.get("call_id")?
.as_str()
fn mcp_tool_call_id(body: &Value) -> Option<&str> {
body.pointer("/params/_meta/callId")?.as_str()
}
pub async fn recorded_apps_tool_calls(server: &MockServer) -> Vec<Value> {
pub async fn recorded_mcp_tool_calls(server: &MockServer) -> Vec<Value> {
server
.received_requests()
.await
@@ -370,32 +332,32 @@ pub async fn recorded_apps_tool_calls(server: &MockServer) -> Vec<Value> {
.into_iter()
.filter_map(|request| {
let body: Value = serde_json::from_slice(&request.body).ok()?;
(request.url.path() == "/api/codex/ps/mcp"
(request.url.path() == MCP_TEST_SERVER_PATH
&& body.get("method").and_then(Value::as_str) == Some("tools/call"))
.then_some(body)
})
.collect()
}
pub async fn recorded_apps_tool_call_by_call_id(server: &MockServer, call_id: &str) -> Value {
let matches = recorded_apps_tool_calls(server)
pub async fn recorded_mcp_tool_call_by_call_id(server: &MockServer, call_id: &str) -> Value {
let matches = recorded_mcp_tool_calls(server)
.await
.into_iter()
.filter(|body| apps_tool_call_id(body) == Some(call_id))
.filter(|body| mcp_tool_call_id(body) == Some(call_id))
.collect::<Vec<_>>();
assert_eq!(
matches.len(),
1,
"expected exactly one apps tools/call request for call_id {call_id}"
"expected exactly one MCP tools/call request for call_id {call_id}"
);
matches
.into_iter()
.next()
.expect("matching apps tools/call request should be recorded")
.expect("matching MCP tools/call request should be recorded")
}
pub async fn recorded_apps_tool_call_by_name(server: &MockServer, tool_name: &str) -> Value {
let matches = recorded_apps_tool_calls(server)
pub async fn recorded_mcp_tool_call_by_name(server: &MockServer, tool_name: &str) -> Value {
let matches = recorded_mcp_tool_calls(server)
.await
.into_iter()
.filter(|body| body.pointer("/params/name").and_then(Value::as_str) == Some(tool_name))
@@ -403,142 +365,32 @@ pub async fn recorded_apps_tool_call_by_name(server: &MockServer, tool_name: &st
assert_eq!(
matches.len(),
1,
"expected exactly one apps tools/call request for tool {tool_name}"
"expected exactly one MCP tools/call request for tool {tool_name}"
);
matches
.into_iter()
.next()
.expect("matching apps tools/call request should be recorded")
.expect("matching MCP tools/call request should be recorded")
}
async fn mount_oauth_metadata(server: &MockServer) {
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server/mcp"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"authorization_endpoint": format!("{}/oauth/authorize", server.uri()),
"token_endpoint": format!("{}/oauth/token", server.uri()),
"scopes_supported": [""],
})))
.mount(server)
.await;
}
async fn mount_connectors_directory(server: &MockServer) {
Mock::given(method("GET"))
.and(path("/connectors/directory/list"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"apps": [
{
"id": DISCOVERABLE_CALENDAR_ID,
"name": "Google Calendar",
"description": "Plan events and schedules.",
},
{
"id": DISCOVERABLE_GMAIL_ID,
"name": "Gmail",
"description": "Find and summarize email threads.",
}
],
"nextToken": null
})))
.mount(server)
.await;
Mock::given(method("GET"))
.and(path("/connectors/directory/list_workspace"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"apps": [],
"nextToken": null
})))
.mount(server)
.await;
}
async fn mount_streamable_http_json_rpc(
server: &MockServer,
connector_name: String,
connector_description: String,
searchable: bool,
include_app_only_tool: bool,
tools_list_behavior: AppsTestToolsListBehavior,
) {
mount_streamable_http_json_rpc_at_path(
server,
CODEX_APPS_MCP_PATH_REGEX,
connector_name,
connector_description,
searchable,
include_app_only_tool,
tools_list_behavior,
)
.await;
}
async fn mount_streamable_http_json_rpc_at_path(
server: &MockServer,
mcp_path_regex: &str,
connector_name: String,
connector_description: String,
searchable: bool,
include_app_only_tool: bool,
tools_list_behavior: AppsTestToolsListBehavior,
) {
mount_streamable_http_json_rpc_with_startup_control(
server,
mcp_path_regex,
connector_name,
connector_description,
searchable,
include_app_only_tool,
tools_list_behavior,
/*initialize_attempts*/ None,
/*remaining_initialize_failures*/ None,
/*successful_initialize_gate*/ None,
)
.await;
}
#[allow(clippy::too_many_arguments)]
async fn mount_streamable_http_json_rpc_with_startup_control(
server: &MockServer,
mcp_path_regex: &str,
connector_name: String,
connector_description: String,
searchable: bool,
include_app_only_tool: bool,
tools_list_behavior: AppsTestToolsListBehavior,
initialize_attempts: Option<Arc<AtomicUsize>>,
remaining_initialize_failures: Option<Arc<AtomicUsize>>,
successful_initialize_gate: Option<AppsStartupInitializeGate>,
) {
async fn mount_streamable_http_json_rpc(server: &MockServer, responder: McpJsonRpcResponder) {
Mock::given(method("POST"))
.and(path_regex(mcp_path_regex))
.respond_with(CodexAppsJsonRpcResponder {
connector_name,
connector_description,
searchable,
include_app_only_tool,
tools_list_behavior,
initialize_attempts,
remaining_initialize_failures,
successful_initialize_gate,
})
.and(path_regex(MCP_PATH_REGEX))
.respond_with(responder)
.mount(server)
.await;
}
struct CodexAppsJsonRpcResponder {
connector_name: String,
connector_description: String,
struct McpJsonRpcResponder {
searchable: bool,
include_app_only_tool: bool,
tools_list_behavior: AppsTestToolsListBehavior,
tools_list_behavior: McpTestToolsListBehavior,
initialize_attempts: Option<Arc<AtomicUsize>>,
remaining_initialize_failures: Option<Arc<AtomicUsize>>,
successful_initialize_gate: Option<AppsStartupInitializeGate>,
successful_initialize_gate: Option<McpStartupInitializeGate>,
}
impl Respond for CodexAppsJsonRpcResponder {
impl Respond for McpJsonRpcResponder {
fn respond(&self, request: &Request) -> ResponseTemplate {
let body: Value = match serde_json::from_slice(&request.body) {
Ok(body) => body,
@@ -572,12 +424,12 @@ impl Respond for CodexAppsJsonRpcResponder {
})
{
return ResponseTemplate::new(400).set_body_json(json!({
"error": "simulated non-retryable Apps MCP startup failure",
"error": "simulated non-retryable MCP startup failure",
}));
}
let gate = self.successful_initialize_gate.as_ref().and_then(|gate| {
gate.lock()
.expect("Apps initialization gate lock should not be poisoned")
.expect("MCP initialization gate lock should not be poisoned")
.pop_front()
});
// This responder's dedicated mock server stays paused while the test controls
@@ -586,7 +438,7 @@ impl Respond for CodexAppsJsonRpcResponder {
&& gate.recv().is_err()
{
return ResponseTemplate::new(500).set_body_json(json!({
"error": "Apps initialization gate was dropped before release",
"error": "MCP initialization gate was dropped before release",
}));
}
let id = body.get("id").cloned().unwrap_or(Value::Null);
@@ -614,12 +466,12 @@ impl Respond for CodexAppsJsonRpcResponder {
"notifications/initialized" => ResponseTemplate::new(202),
"tools/list" => {
let tools_available = match &self.tools_list_behavior {
AppsTestToolsListBehavior::AlwaysAvailable
| AppsTestToolsListBehavior::Custom(_) => true,
AppsTestToolsListBehavior::AvailableWhen(tools_available) => {
McpTestToolsListBehavior::AlwaysAvailable
| McpTestToolsListBehavior::Custom(_) => true,
McpTestToolsListBehavior::AvailableWhen(tools_available) => {
tools_available.load(Ordering::SeqCst)
}
AppsTestToolsListBehavior::AlwaysUnavailable => false,
McpTestToolsListBehavior::AlwaysUnavailable => false,
};
let id = body.get("id").cloned().unwrap_or(Value::Null);
let mut response = json!({
@@ -646,16 +498,7 @@ impl Respond for CodexAppsJsonRpcResponder {
"additionalProperties": false
},
"_meta": {
"connector_id": CONNECTOR_ID,
"link_id": LINK_ID,
"connector_name": self.connector_name.clone(),
"connector_description": self.connector_description.clone(),
"openai/outputTemplate": CALENDAR_CREATE_EVENT_MCP_APP_RESOURCE_URI,
"_codex_apps": {
"resource_uri": CALENDAR_CREATE_EVENT_RESOURCE_URI,
"contains_mcp_source": true,
"connector_id": CONNECTOR_ID
}
"openai/outputTemplate": CALENDAR_CREATE_EVENT_MCP_APP_RESOURCE_URI
}
},
{
@@ -673,15 +516,6 @@ impl Respond for CodexAppsJsonRpcResponder {
"additionalProperties": false
},
"_meta": {
"connector_id": CONNECTOR_ID,
"link_id": LINK_ID,
"connector_name": self.connector_name.clone(),
"connector_description": self.connector_description.clone(),
"_codex_apps": {
"resource_uri": CALENDAR_LIST_EVENTS_RESOURCE_URI,
"contains_mcp_source": true,
"connector_id": CONNECTOR_ID
}
}
},
{
@@ -708,27 +542,18 @@ impl Respond for CodexAppsJsonRpcResponder {
"additionalProperties": false
},
"_meta": {
"connector_id": CONNECTOR_ID,
"link_id": LINK_ID,
"connector_name": self.connector_name.clone(),
"connector_description": self.connector_description.clone(),
"openai/fileParams": ["file"],
"_codex_apps": {
"resource_uri": DOCUMENT_EXTRACT_TEXT_RESOURCE_URI,
"contains_mcp_source": true,
"connector_id": CONNECTOR_ID
}
"openai/fileParams": ["file"]
}
}
],
"nextCursor": null
}
});
if let AppsTestToolsListBehavior::Custom(tools) = &self.tools_list_behavior {
if let McpTestToolsListBehavior::Custom(tools) = &self.tools_list_behavior {
response["result"]["tools"] = json!(
tools
.lock()
.expect("Apps test tools lock should not be poisoned")
.expect("MCP test tools lock should not be poisoned")
.clone()
);
}
@@ -759,11 +584,7 @@ impl Respond for CodexAppsJsonRpcResponder {
},
"additionalProperties": false
},
"_meta": {
"connector_id": CONNECTOR_ID,
"connector_name": self.connector_name.clone(),
"connector_description": self.connector_description.clone()
}
"_meta": {}
}));
}
}
@@ -782,9 +603,6 @@ impl Respond for CodexAppsJsonRpcResponder {
"additionalProperties": false
},
"_meta": {
"connector_id": CONNECTOR_ID,
"connector_name": self.connector_name.clone(),
"connector_description": self.connector_description.clone(),
"ui": {
"visibility": ["app"]
}
@@ -811,7 +629,6 @@ impl Respond for CodexAppsJsonRpcResponder {
.pointer("/params/arguments/file/file_id")
.and_then(Value::as_str)
.unwrap_or_default();
let codex_apps_meta = body.pointer("/params/_meta/_codex_apps").cloned();
ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
@@ -822,7 +639,7 @@ impl Respond for CodexAppsJsonRpcResponder {
"text": format!("called {tool_name} for {title} at {starts_at} with {file_id}")
}],
"structuredContent": {
"_codex_apps": codex_apps_meta,
"called": tool_name,
},
"isError": false
}
@@ -844,15 +661,3 @@ impl Respond for CodexAppsJsonRpcResponder {
}
}
/// Builds an MCP server config that points at this mock apps server. aKode no longer ships a
/// production helper for the ChatGPT-hosted apps server; tests that exercise the generic
/// streamable HTTP and ChatGPT-auth MCP paths use this mock-only config instead.
pub fn mock_apps_mcp_server_config(mock_base_url: &str) -> codex_config::McpServerConfig {
#[expect(clippy::expect_used, reason = "static test config is valid")]
serde_json::from_value(json!({
"url": format!("{}/api/codex/ps/mcp", mock_base_url.trim_end_matches('/')),
"auth": "chatgpt",
"startup_timeout_sec": 30,
}))
.expect("valid mock apps MCP server config")
}

View File

@@ -822,14 +822,12 @@ pub fn ev_response_created(id: &str) -> Value {
})
}
pub fn ev_model_verification_metadata(id: &str, verifications: Vec<&str>) -> Value {
pub fn ev_response_metadata(id: &str, metadata: Value) -> Value {
serde_json::json!({
"type": "response.metadata",
"sequence_number": 1,
"response_id": id,
"metadata": {
"openai_verification_recommendation": verifications,
}
"metadata": metadata,
})
}

View File

@@ -1,156 +0,0 @@
//! Route isolated first-party auth tests to loopback without relaxing destination checks.
use anyhow::Result;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::net::TcpListener;
use tokio::net::TcpStream;
use tokio::process::Command;
use tokio::task::JoinSet;
use tokio_rustls::TlsAcceptor;
use tokio_rustls::rustls;
use wiremock::MockServer;
pub const PROBE_SERVER: &str = "CODEX_RUNTIME_AUTH_TEST_SERVER";
/// Run one test in an isolated subprocess with first-party HTTP routed to the mock server.
/// An optional Realtime target receives chatgpt.com Realtime WebSocket upgrades.
pub async fn run_harness_through_proxy(
server: &MockServer,
test_name: &str,
realtime_target: Option<std::net::SocketAddr>,
) -> Result<()> {
run_harness_through_proxy_with_env(server, test_name, realtime_target, &[]).await
}
/// Adds process-local auth inputs without changing the test runner's environment.
pub async fn run_harness_through_proxy_with_env(
server: &MockServer,
test_name: &str,
realtime_target: Option<std::net::SocketAddr>,
environment: &[(&str, Option<&str>)],
) -> Result<()> {
// The production destination check stays intact. A test-only CA and CONNECT proxy route
// the real host names to wiremock, only inside this isolated test subprocess.
codex_utils_rustls_provider::ensure_rustls_crypto_provider();
let rcgen::CertifiedKey { cert, signing_key } = rcgen::generate_simple_self_signed(vec![
"api.openai.com".into(),
"api.openai.org".into(),
"auth.openai.com".into(),
"chatgpt.com".into(),
"us.chatgpt.com".into(),
"chatgpt-staging.com".into(),
"us.chatgpt-staging.com".into(),
"auth.api.openai.org".into(),
])?;
let ca_dir = tempfile::tempdir()?;
let ca_path = ca_dir.path().join("ca.pem");
std::fs::write(&ca_path, cert.pem())?;
let acceptor = TlsAcceptor::from(Arc::new(
rustls::ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(vec![cert.der().clone()], signing_key.into())?,
));
let proxy = TcpListener::bind("127.0.0.1:0").await?;
let proxy_url = format!("http://{}", proxy.local_addr()?);
let target = *server.address();
let proxy_task = tokio::spawn(async move {
let mut connections = JoinSet::new();
loop {
let (mut stream, _) = proxy.accept().await?;
let acceptor = acceptor.clone();
connections.spawn(async move {
let mut headers = Vec::new();
while !headers.ends_with(b"\r\n\r\n") && headers.len() < 8192 {
headers.push(stream.read_u8().await?);
}
let headers = std::str::from_utf8(&headers)?;
anyhow::ensure!(
matches!(
headers.lines().next(),
Some(
"CONNECT api.openai.com:443 HTTP/1.1"
| "CONNECT api.openai.org:443 HTTP/1.1"
| "CONNECT auth.openai.com:443 HTTP/1.1"
| "CONNECT chatgpt.com:443 HTTP/1.1"
| "CONNECT us.chatgpt.com:443 HTTP/1.1"
| "CONNECT chatgpt-staging.com:443 HTTP/1.1"
| "CONNECT us.chatgpt-staging.com:443 HTTP/1.1"
| "CONNECT auth.api.openai.org:443 HTTP/1.1"
)
),
"unexpected proxy destination"
);
stream
.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n")
.await?;
let realtime_host = headers.starts_with("CONNECT chatgpt.com:443 ");
let mut stream = acceptor.accept(stream).await?;
let mut prefix = Vec::new();
let mut destination = target;
if let Some(realtime_target) = realtime_target.filter(|_| realtime_host) {
// Background HTTP requests share this host with Realtime. Only upgrades
// belong on the WebSocket fixture; ordinary HTTP still goes to wiremock.
while !prefix.ends_with(b"\r\n\r\n") && prefix.len() < 65536 {
prefix.push(stream.read_u8().await?);
}
anyhow::ensure!(
prefix.ends_with(b"\r\n\r\n"),
"oversized test request headers"
);
let request_headers = std::str::from_utf8(&prefix)?;
let realtime_path = request_headers.lines().next().is_some_and(|line| {
line.starts_with("GET /v1/realtime") || line.starts_with("GET /v1/live")
});
if realtime_path
&& request_headers.lines().any(|line| {
line.split_once(':').is_some_and(|(name, value)| {
name.eq_ignore_ascii_case("upgrade")
&& value.trim().eq_ignore_ascii_case("websocket")
})
})
{
destination = realtime_target;
}
}
let mut target = TcpStream::connect(destination).await?;
target.write_all(&prefix).await?;
tokio::io::copy_bidirectional(&mut stream, &mut target).await?;
Ok::<_, anyhow::Error>(())
});
}
#[allow(unreachable_code)]
Ok::<_, anyhow::Error>(())
});
let mut command = Command::new(std::env::current_exe()?);
command
.args(["--exact", test_name, "--nocapture"])
.kill_on_drop(true);
for &key in codex_network_proxy::PROXY_ENV_KEYS {
command.env_remove(key);
}
command
.env(PROBE_SERVER, server.uri())
.env("HTTPS_PROXY", proxy_url)
.env("NO_PROXY", codex_network_proxy::DEFAULT_NO_PROXY_VALUE)
.env("CODEX_CA_CERTIFICATE", ca_path);
for (key, value) in environment {
match value {
Some(value) => command.env(key, value),
None => command.env_remove(key),
};
}
let output = tokio::time::timeout(Duration::from_secs(90), command.output()).await;
proxy_task.abort();
let output = output??;
assert!(
output.status.success(),
"harness subprocess failed\n{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
Ok(())
}

View File

@@ -35,12 +35,22 @@ impl StreamingSseServer {
self.requests.lock().await.clone()
}
/// Waits for `count` requests; panics after a generous bound instead of hanging the suite.
pub async fn wait_for_request_count(&self, count: usize) {
loop {
if self.requests.lock().await.len() >= count {
return;
let wait = async {
loop {
if self.requests.lock().await.len() >= count {
return;
}
self.request_notify.notified().await;
}
self.request_notify.notified().await;
};
if tokio::time::timeout(std::time::Duration::from_secs(60), wait)
.await
.is_err()
{
let received = self.requests.lock().await.len();
panic!("timed out waiting for {count} streaming requests; received {received}");
}
}

View File

@@ -17,7 +17,7 @@ use anyhow::Result;
use anyhow::anyhow;
use codex_agent_graph_store::AgentGraphStore;
use codex_attachment_store::AttachmentStore;
use codex_config::CloudConfigBundleLoader;
use codex_config::test_support::ManagedConfigFixture;
use codex_core::CodexThread;
pub use codex_core::StartThreadOptions;
use codex_core::ThreadManager;
@@ -84,7 +84,7 @@ use wiremock::MockServer;
use crate::TempDirExt;
use crate::TestEnvironment;
use crate::load_default_config_for_test;
use crate::load_default_config_for_test_with_cloud_config_bundle;
use crate::load_default_config_for_test_with_managed_config;
use crate::responses::WebSocketTestServer;
use crate::responses::output_value_to_text;
use crate::responses::start_mock_server;
@@ -405,15 +405,20 @@ impl TestAuth {
}
}
/// Host-supplied header auth without credentials, for tests that exercise the merged
/// provider catalog refresh path.
pub fn header_auth_for_testing() -> CodexAuth {
CodexAuth::Headers(codex_login::AuthHeaders::new(Default::default()))
}
pub struct TestCodexBuilder {
apps_tools_cache: codex_core::CodexAppsToolsCache,
config_mutators: Vec<Box<ConfigMutator>>,
thread_manager_configurer: Option<Box<dyn FnOnce(ThreadManager) -> ThreadManager + Send>>,
auth: TestAuth,
pre_build_hooks: Vec<Box<PreBuildHook>>,
workspace_setups: Vec<Box<WorkspaceSetup>>,
home: Option<Arc<TempDir>>,
cloud_config_bundle: Option<CloudConfigBundleLoader>,
managed_config: Option<ManagedConfigFixture>,
user_shell_override: Option<Shell>,
exec_server_url: Option<String>,
extensions: Arc<ExtensionRegistry<Config>>,
@@ -427,11 +432,23 @@ pub struct TestCodexBuilder {
thread_store: Option<Arc<dyn ThreadStore>>,
agent_graph_store: Option<Arc<dyn AgentGraphStore>>,
image_store: Arc<dyn AttachmentStore>,
catalog_discovery: bool,
}
impl TestCodexBuilder {
pub fn with_apps_tools_cache(mut self, cache: codex_core::CodexAppsToolsCache) -> Self {
self.apps_tools_cache = cache;
/// Authenticate with a stored API key and point the provider's model catalog at the
/// mock server, so remote catalog refresh runs. Stored API keys only refresh catalogs
/// from an explicit `model_catalog_url`.
pub fn with_catalog_discovery_api_key(mut self) -> Self {
self.auth = TestAuth::Cached(CodexAuth::from_api_key("Test API Key"));
self.catalog_discovery = true;
self
}
/// Authenticate with host-supplied (empty) request headers. Header auth refreshes the
/// provider catalog from the provider base URL and merges it over the bundled catalog.
pub fn with_header_auth(mut self) -> Self {
self.auth = TestAuth::Cached(header_auth_for_testing());
self
}
@@ -555,11 +572,9 @@ impl TestCodexBuilder {
self
}
pub fn with_cloud_config_bundle(
mut self,
cloud_config_bundle: CloudConfigBundleLoader,
) -> Self {
self.cloud_config_bundle = Some(cloud_config_bundle);
/// Loads the fixture as local managed requirements / config (system files).
pub fn with_managed_config(mut self, managed_config: ManagedConfigFixture) -> Self {
self.managed_config = Some(managed_config);
self
}
@@ -895,7 +910,6 @@ impl TestCodexBuilder {
let thread_manager = ThreadManager::new(
&config,
startup,
self.apps_tools_cache.clone(),
SessionSource::Exec,
Arc::clone(&environment_manager),
Arc::new(extensions.build()),
@@ -905,7 +919,6 @@ impl TestCodexBuilder {
self.agent_graph_store.clone().or_else(|| {
codex_core::local_agent_graph_store_from_state_db(state_db.as_ref())
}),
/*attestation_provider*/ None,
/*external_time_provider*/ self.external_time_provider.clone(),
);
let thread_manager = match self.thread_manager_configurer.take() {
@@ -1022,8 +1035,8 @@ impl TestCodexBuilder {
for hook in self.pre_build_hooks.drain(..) {
hook(home.path());
}
let mut config = if let Some(cloud_config_bundle) = self.cloud_config_bundle.take() {
load_default_config_for_test_with_cloud_config_bundle(home, cloud_config_bundle).await
let mut config = if let Some(managed_config) = self.managed_config.take() {
load_default_config_for_test_with_managed_config(home, managed_config).await
} else {
load_default_config_for_test(home).await
};
@@ -1055,6 +1068,15 @@ impl TestCodexBuilder {
for mutator in mutators {
mutator(&mut config);
}
// Apply after config mutators so tests that replace the provider still get catalog
// discovery from the provider they selected.
if self.catalog_discovery && config.model_provider.model_catalog_url.is_none() {
config.model_provider.model_catalog_url = config
.model_provider
.base_url
.as_deref()
.map(|base_url| format!("{}/models", base_url.trim_end_matches('/')).into());
}
ensure_test_model_catalog(&mut config)?;
Ok((config, cwd))
@@ -1554,7 +1576,6 @@ fn function_call_output<'a>(bodies: &'a [Value], call_id: &str) -> &'a Value {
pub fn test_codex() -> TestCodexBuilder {
TestCodexBuilder {
apps_tools_cache: Default::default(),
thread_manager_configurer: None,
config_mutators: vec![Box::new(|config| {
config
@@ -1571,7 +1592,7 @@ pub fn test_codex() -> TestCodexBuilder {
pre_build_hooks: vec![],
workspace_setups: vec![],
home: None,
cloud_config_bundle: None,
managed_config: None,
user_shell_override: None,
exec_server_url: None,
extensions: empty_extension_registry(),
@@ -1586,6 +1607,7 @@ pub fn test_codex() -> TestCodexBuilder {
thread_store: None,
agent_graph_store: None,
image_store: codex_core::passthrough_image_store(),
catalog_discovery: false,
}
}