WIP fase 2b-3: rimozione sottosistemi solo-ChatGPT (plugin remoti, image gen, daybreak, cyber, attestation, cloud config, app/connettori) - test in corso

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-10 16:07:22 +01:00
parent 231e8cd136
commit 5afc7e9f7f
1223 changed files with 6225 additions and 113722 deletions

View File

@@ -81,13 +81,13 @@ pub(crate) struct RouteAwareHttpRequestRunner {
impl RouteAwareHttpClient {
pub fn new(http_client_factory: HttpClientFactory) -> Self {
Self {
follow_redirects: RouteAwareClientPool::with_chatgpt_cloudflare_cookies_without_request_logging(
follow_redirects: RouteAwareClientPool::new_without_request_logging(
http_client_factory.clone(),
// Delegated HTTP targets arbitrary endpoints; route class only labels diagnostics.
ClientRouteClass::Other,
),
stop_redirects:
RouteAwareClientPool::with_chatgpt_cloudflare_cookies_without_redirects_or_request_logging(
RouteAwareClientPool::new_without_redirects_or_request_logging(
http_client_factory,
// Proxy routing comes from the factory, not this diagnostic-only route class.
ClientRouteClass::Other,

View File

@@ -68,11 +68,9 @@ async fn config_read_timeout_keeps_stdio_connection_usable() {
hostname: Some("original".to_string()),
config: EnvironmentConfigLayerStack {
layers: Vec::new(),
cloud_insertion_index: 0,
},
requirements: EnvironmentConfigLayerStack {
layers: Vec::new(),
cloud_insertion_index: 0,
},
};

View File

@@ -341,7 +341,6 @@ fn parse_root(
DiscoveredSource::Plugin(Box::new(ExecutorPlugin {
id: plugin.id,
display_name,
remote_plugin_id: plugin.remote_plugin_id,
version: plugin.version,
root: location.root,
files,

View File

@@ -7,7 +7,6 @@ use std::collections::BTreeMap;
use std::io;
use crate::LocalFileSystem;
use crate::protocol::FsOpenMode;
use codex_file_system::ExecutorFileSystem;
use codex_file_system::WalkEntryKind;
use codex_file_system::WalkOptions;
@@ -17,11 +16,8 @@ use serde::Deserialize;
use serde::Serialize;
use codex_core_plugin_common::installed::PLUGINS_CACHE_DIR;
use codex_core_plugin_common::installed::REMOTE_PLUGIN_INSTALL_METADATA_FILE;
use codex_core_plugin_common::installed::active_plugin_version;
use codex_core_plugin_common::installed::parse_remote_plugin_id;
use codex_core_plugin_common::plugin_id::PluginId;
use tokio::io::AsyncReadExt;
/// Fixed paths are supplied by the executor, not read from the sandbox helper's sanitized env.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -32,8 +28,6 @@ pub(crate) struct CapabilityLocationRequest {
}
const MAX_LOCATIONS: usize = 512;
const MAX_REMOTE_INSTALL_METADATA_BYTES: u64 = 16 * 1024;
const MAX_REMOTE_PLUGIN_ID_BYTES: usize = 1024;
const AGENTS_SKILLS_SUFFIX: &str = ".agents/skills";
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -47,7 +41,6 @@ pub(crate) struct CapabilityLocation {
pub(crate) struct InstalledPlugin {
pub id: String,
pub version: String,
pub remote_plugin_id: Option<String>,
}
/// Selected locations; membership does not authorize capability reads.
@@ -156,64 +149,21 @@ async fn discover_cached_plugins(
.await
.map_err(io::Error::other)?;
for (id, package_root, version) in installed {
// Avoid reading metadata for plugin locations the final assembly would discard.
if locations.locations.len() == MAX_LOCATIONS {
locations.warnings.push(format!(
"plugin cache reached its {MAX_LOCATIONS}-location limit"
));
break;
}
let metadata_path = package_root.join(REMOTE_PLUGIN_INSTALL_METADATA_FILE);
let remote_plugin_id = match read_remote_plugin_id(metadata_path.as_path()).await {
Ok(remote_plugin_id) => remote_plugin_id,
Err(error) => {
locations.warnings.push(format!(
"could not read remote installation metadata for {id}: {error}"
));
None
}
};
locations.locations.push(CapabilityLocation {
root: PathUri::from_abs_path(&package_root.join(&version)),
standalone_root_id: None,
plugin: Some(InstalledPlugin {
id,
version,
remote_plugin_id,
}),
plugin: Some(InstalledPlugin { id, version }),
});
}
Ok(locations)
}
async fn read_remote_plugin_id(path: &std::path::Path) -> io::Result<Option<String>> {
// Nonblocking open and handle validation reject FIFOs and other non-regular files.
let file = match crate::regular_file::open(path, FsOpenMode::Read).await {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error),
};
let mut contents = Vec::new();
file.take(MAX_REMOTE_INSTALL_METADATA_BYTES + 1)
.read_to_end(&mut contents)
.await?;
if contents.len() as u64 > MAX_REMOTE_INSTALL_METADATA_BYTES {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"remote installation metadata exceeds its byte limit",
));
}
let contents = std::str::from_utf8(&contents).map_err(io::Error::other)?;
let id = parse_remote_plugin_id(contents).map_err(io::Error::other)?;
if id.len() > MAX_REMOTE_PLUGIN_ID_BYTES {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"remote plugin ID exceeds its byte limit",
));
}
Ok(Some(id))
}
#[cfg(test)]
#[path = "tests/capability_locations_tests.rs"]
pub(crate) mod tests;

View File

@@ -57,11 +57,6 @@ async fn prewarming_resolves_global_locations_without_cwd_or_config() -> anyhow:
MANIFEST,
)?;
}
write(
temp.path(),
"codex/plugins/cache/team/demo/.codex-remote-plugin-install.json",
r#"{"schema_version":1,"remote_plugin_id":"plugins~demo"}"#,
)?;
let locations = prewarm_locations(&LocalFileSystem::unsandboxed(), &request).await?;
let mut actual = locations.locations;
actual.sort_unstable_by_key(|location| location.root.to_string());
@@ -71,7 +66,6 @@ async fn prewarming_resolves_global_locations_without_cwd_or_config() -> anyhow:
plugin: Some(InstalledPlugin {
id: "demo@team".to_string(),
version: "1.10.0".to_string(),
remote_plugin_id: Some("plugins~demo".to_string()),
}),
}];
for (id, root) in [
@@ -89,34 +83,6 @@ async fn prewarming_resolves_global_locations_without_cwd_or_config() -> anyhow:
assert_eq!(actual, expected);
assert!(locations.warnings.is_empty());
let metadata = "codex/plugins/cache/team/demo/.codex-remote-plugin-install.json";
for contents in [
"invalid JSON".to_string(),
" ".repeat(super::MAX_REMOTE_INSTALL_METADATA_BYTES as usize + 1),
] {
write(temp.path(), metadata, &contents)?;
let locations = prewarm_locations(&LocalFileSystem::unsandboxed(), &request).await?;
assert!(locations.warnings.iter().any(|warning| {
warning.contains("could not read remote installation metadata for demo@team")
}));
assert!(locations.locations.iter().any(|location| {
location
.plugin
.as_ref()
.is_some_and(|plugin| plugin.id == "demo@team" && plugin.remote_plugin_id.is_none())
}));
}
// Missing remote metadata is valid for locally installed plugins.
std::fs::remove_file(temp.path().join(metadata))?;
let locations = prewarm_locations(&LocalFileSystem::unsandboxed(), &request).await?;
assert!(locations.warnings.is_empty());
assert!(locations.locations.iter().any(|location| {
location
.plugin
.as_ref()
.is_some_and(|plugin| plugin.id == "demo@team" && plugin.remote_plugin_id.is_none())
}));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;

View File

@@ -215,7 +215,6 @@ fn serialize_layer_stack<S>(
.collect::<Result<Vec<_>, ReadEnvironmentConfigError>>()?;
Ok(EnvironmentConfigLayerStack {
layers,
cloud_insertion_index: stack.cloud_insertion_index,
})
}

View File

@@ -23,11 +23,9 @@ fn startup_preference_stays_below_both_managed_layers() -> anyhow::Result<()> {
toml: toml::Value::Table(toml::toml! { [features] prefer_mxc = false }),
})
.collect(),
cloud_insertion_index: 0,
},
requirements: LocalTomlLayerStack {
layers: Vec::new(),
cloud_insertion_index: 0,
},
};
include_startup_preference(&mut layers, &cwd, Some(true));
@@ -46,7 +44,6 @@ fn startup_preference_stays_below_both_managed_layers() -> anyhow::Result<()> {
codex_config::merge_toml_values(&mut effective, &layer.toml);
}
assert_eq!(effective["features"]["prefer_mxc"].as_bool(), Some(false));
assert_eq!(projected.config.cloud_insertion_index, 0);
}
Ok(())
}

View File

@@ -969,7 +969,6 @@ async fn v2_helper_batches_roots_and_bounds_its_response() -> anyhow::Result<()>
"plugin": {
"id": format!("plugin-{index}@test"),
"version": "local",
"remote_plugin_id": null,
},
}));
}
@@ -987,7 +986,6 @@ async fn v2_helper_batches_roots_and_bounds_its_response() -> anyhow::Result<()>
"plugin": {
"id": "plugin-small@test",
"version": "local",
"remote_plugin_id": null,
},
}));
let request = serde_json::json!({

View File

@@ -1,184 +0,0 @@
#![cfg(unix)]
mod common;
#[path = "common/tls_proxy.rs"]
mod tls_proxy;
use std::ffi::OsString;
use std::fs;
use codex_exec_server::HttpRedirectPolicy;
use codex_exec_server::HttpRequestParams;
use codex_exec_server::HttpRequestResponse;
use codex_exec_server::InitializeParams;
use codex_exec_server_protocol::JSONRPCMessage;
use codex_exec_server_protocol::JSONRPCResponse;
use codex_exec_server_protocol::RequestId;
use common::exec_server::ExecServerHarness;
use common::exec_server::exec_server_with_env;
use pretty_assertions::assert_eq;
use serde::de::DeserializeOwned;
use serde_json::Value;
use tempfile::TempDir;
use tls_proxy::TlsInterceptingProxy;
const CHATGPT_MCP_URL: &str = "https://chatgpt.com/backend-api/ps/mcp";
const NON_CHATGPT_MCP_URL: &str = "https://api.openai.com/backend-api/ps/mcp";
/// Exercises the same `http/request` route used by remotely executed Streamable HTTP MCP calls.
/// Each RPC uses the shared route-aware client. The first response sets `__cflb`, and the second response
/// replaces it, proving cross-client persistence through the shared cookie store.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_server_replays_only_chatgpt_cloudflare_cookies() -> anyhow::Result<()> {
let proxy = TlsInterceptingProxy::start(/*expected_requests*/ 4)?;
let temp_dir = TempDir::new()?;
let ca_path = temp_dir.path().join("cloudflare-affinity-test-ca.pem");
fs::write(&ca_path, &proxy.ca_cert_pem)?;
let proxy_url = OsString::from(&proxy.url);
let empty = OsString::new();
let env = vec![
(
OsString::from("CODEX_CA_CERTIFICATE"),
ca_path.as_os_str().to_owned(),
),
(OsString::from("HTTPS_PROXY"), proxy_url.clone()),
(OsString::from("https_proxy"), proxy_url.clone()),
(OsString::from("ALL_PROXY"), proxy_url.clone()),
(OsString::from("all_proxy"), proxy_url),
(OsString::from("NO_PROXY"), empty.clone()),
(OsString::from("no_proxy"), empty),
];
let mut server = exec_server_with_env(env, &[]).await?;
initialize_exec_server(&mut server).await?;
let first_response = execute_http_request(&mut server, CHATGPT_MCP_URL, "first").await?;
assert_eq!(
(first_response.status, first_response.body.into_inner()),
(200, b"ok".to_vec())
);
let first = proxy.next_request()?;
assert_eq!(
(
first.connect_authority.as_str(),
first.request_line.as_str(),
first.headers.get("cookie"),
),
("chatgpt.com:443", "POST /backend-api/ps/mcp HTTP/1.1", None,)
);
let west_response = execute_http_request(&mut server, CHATGPT_MCP_URL, "west").await?;
assert_eq!(west_response.status, 200);
let request_with_west_affinity = proxy.next_request()?;
assert_eq!(
request_with_west_affinity
.headers
.get("cookie")
.cloned()
.unwrap_or_default(),
vec!["__cflb=west".to_string()]
);
let central_response = execute_http_request(&mut server, CHATGPT_MCP_URL, "central").await?;
assert_eq!(central_response.status, 200);
let request_with_central_affinity = proxy.next_request()?;
assert_eq!(
(
request_with_central_affinity.request_line.as_str(),
request_with_central_affinity
.headers
.get("cookie")
.cloned()
.unwrap_or_default(),
),
(
"POST /backend-api/ps/mcp HTTP/1.1",
vec!["__cflb=central".to_string()],
)
);
let other_host_response =
execute_http_request(&mut server, NON_CHATGPT_MCP_URL, "other-host").await?;
assert_eq!(other_host_response.status, 200);
let other_host = proxy.next_request()?;
assert_eq!(
(
other_host.connect_authority.as_str(),
other_host.request_line.as_str(),
other_host.headers.get("cookie"),
),
(
"api.openai.com:443",
"POST /backend-api/ps/mcp HTTP/1.1",
None,
)
);
server.shutdown().await?;
proxy.finish()?;
Ok(())
}
async fn initialize_exec_server(server: &mut ExecServerHarness) -> anyhow::Result<()> {
let initialize_id = server
.send_request(
"initialize",
serde_json::to_value(InitializeParams {
client_name: "cloudflare-affinity-test".to_string(),
resume_session_id: None,
})?,
)
.await?;
let _: Value = wait_for_response(server, initialize_id).await?;
server
.send_notification("initialized", serde_json::json!({}))
.await
}
async fn execute_http_request(
server: &mut ExecServerHarness,
url: &str,
request_id: &str,
) -> anyhow::Result<HttpRequestResponse> {
let response_id = server
.send_request(
"http/request",
serde_json::to_value(HttpRequestParams {
method: "POST".to_string(),
url: url.to_string(),
headers: Vec::new(),
body: None,
timeout_ms: Some(5_000),
redirect_policy: HttpRedirectPolicy::Follow,
request_id: request_id.to_string(),
stream_response: false,
})?,
)
.await?;
wait_for_response(server, response_id).await
}
async fn wait_for_response<T>(
server: &mut ExecServerHarness,
request_id: RequestId,
) -> anyhow::Result<T>
where
T: DeserializeOwned,
{
let message = server
.wait_for_event(|event| match event {
JSONRPCMessage::Response(JSONRPCResponse { id, .. })
| JSONRPCMessage::Error(codex_exec_server_protocol::JSONRPCError { id, .. }) => {
id == &request_id
}
_ => false,
})
.await?;
match message {
JSONRPCMessage::Response(JSONRPCResponse { result, .. }) => {
Ok(serde_json::from_value(result)?)
}
JSONRPCMessage::Error(error) => {
anyhow::bail!("exec-server returned an error for {request_id:?}: {error:?}")
}
_ => unreachable!("predicate only accepts responses for the requested id"),
}
}

View File

@@ -91,11 +91,9 @@ private_startup_value = "unselected-private-value"
base_dir: PathUri::from_abs_path(&dot_codex),
toml: toml::to_string(&projected_toml)?,
}],
cloud_insertion_index: 0,
},
requirements: EnvironmentConfigLayerStack {
layers: Vec::new(),
cloud_insertion_index: 0,
},
}
);
@@ -128,7 +126,6 @@ private_startup_value = "unselected-private-value"
requirements_paths: Vec::new(),
})
.await?;
assert_eq!(preference.config.cloud_insertion_index, 0);
assert_eq!(preference.config.layers.len(), 2);
let configured = &preference.config.layers[0];
let startup = &preference.config.layers[1];