Residui OpenAI: nessun nome di dominio OpenAI nel binario (B)

Parte "sicurezza" di 854c7a66 (senza la rimozione della memoria nativa):
- via openai_docs_source_attribution (intestazioni verso developers.openai.com per i server MCP);
- exec-server: chiave API accettata solo verso host loopback (non piu' openai.com/openai.org);
- git-attribution: nessuna istruzione "Co-authored-by: Codex <noreply@openai.com>" generata;
  le istruzioni lasciate nelle cronologie di Codex vengono solo annullate;
- http-client/openai_endpoints: elenco degli host OpenAI per etichette, senza nomi di dominio interi.
Test adattati (non cancellati) salvo quelli del codice rimosso (openai_docs_source_attribution).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:47:29 +01:00
parent 77a19832b3
commit a354f0f00c
10 changed files with 120 additions and 272 deletions

View File

@@ -95,7 +95,6 @@ mod connection_pool;
pub(crate) mod elicitation;
mod executor_environment_http_client;
pub(crate) mod mcp;
mod openai_docs_source_attribution;
mod pagination;
mod plugin_config;
mod resource_client;

View File

@@ -1,56 +0,0 @@
use std::sync::Arc;
use akode_exec_server::ExecServerError;
use akode_exec_server::HttpClient;
use akode_exec_server::HttpRequestParams;
use akode_exec_server::HttpRequestResponse;
use akode_exec_server::HttpResponseBodyStream;
use futures::future::BoxFuture;
const OPENAI_DEVELOPER_DOCS_MCP_URL: &str = "https://developers.openai.com/mcp";
const OPENAI_DEVELOPER_DOCS_MCP_CODEX_URL: &str = "https://developers.openai.com/mcp?source=codex";
pub(crate) fn maybe_with_openai_docs_source_attribution(
mcp_server_url: &str,
http_client: Arc<dyn HttpClient>,
) -> Arc<dyn HttpClient> {
if mcp_server_url == OPENAI_DEVELOPER_DOCS_MCP_URL {
Arc::new(OpenAiDocsHttpClient { http_client })
} else {
http_client
}
}
struct OpenAiDocsHttpClient {
http_client: Arc<dyn HttpClient>,
}
impl OpenAiDocsHttpClient {
fn attribute_mcp_request(&self, params: &mut HttpRequestParams) {
if params.url == OPENAI_DEVELOPER_DOCS_MCP_URL {
params.url = OPENAI_DEVELOPER_DOCS_MCP_CODEX_URL.to_string();
}
}
}
impl HttpClient for OpenAiDocsHttpClient {
fn http_request(
&self,
mut params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
self.attribute_mcp_request(&mut params);
self.http_client.http_request(params)
}
fn http_request_stream(
&self,
mut params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
self.attribute_mcp_request(&mut params);
self.http_client.http_request_stream(params)
}
}
#[cfg(test)]
#[path = "openai_docs_source_attribution_tests.rs"]
mod tests;

View File

@@ -1,92 +0,0 @@
use std::sync::Arc;
use std::sync::Mutex;
use akode_exec_server::ExecServerError;
use akode_exec_server::HttpClient;
use akode_exec_server::HttpRedirectPolicy;
use akode_exec_server::HttpRequestParams;
use akode_exec_server::HttpRequestResponse;
use akode_exec_server::HttpResponseBodyStream;
use futures::FutureExt;
use futures::future::BoxFuture;
use pretty_assertions::assert_eq;
use super::OPENAI_DEVELOPER_DOCS_MCP_CODEX_URL;
use super::OPENAI_DEVELOPER_DOCS_MCP_URL;
use super::maybe_with_openai_docs_source_attribution;
#[derive(Default)]
struct RecordingHttpClient {
urls: Mutex<Vec<String>>,
}
impl HttpClient for RecordingHttpClient {
fn http_request(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
self.urls.lock().unwrap().push(params.url);
async { Err(ExecServerError::HttpRequest("test response".to_string())) }.boxed()
}
fn http_request_stream(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
self.urls.lock().unwrap().push(params.url);
async { Err(ExecServerError::HttpRequest("test response".to_string())) }.boxed()
}
}
fn request(url: &str) -> HttpRequestParams {
HttpRequestParams {
method: "POST".to_string(),
url: url.to_string(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "test-request".to_string(),
stream_response: true,
}
}
#[tokio::test]
async fn attributes_only_docs_mcp_requests() {
let recording_client = Arc::new(RecordingHttpClient::default());
let http_client = maybe_with_openai_docs_source_attribution(
OPENAI_DEVELOPER_DOCS_MCP_URL,
recording_client.clone(),
);
let _ = http_client
.http_request_stream(request(OPENAI_DEVELOPER_DOCS_MCP_URL))
.await;
let _ = http_client
.http_request(request(
"https://developers.openai.com/.well-known/oauth-protected-resource/mcp",
))
.await;
assert_eq!(
recording_client.urls.lock().unwrap().as_slice(),
[
OPENAI_DEVELOPER_DOCS_MCP_CODEX_URL,
"https://developers.openai.com/.well-known/oauth-protected-resource/mcp",
]
);
}
#[test]
fn leaves_other_mcp_clients_unwrapped() {
let recording_client = Arc::new(RecordingHttpClient::default());
let http_client = maybe_with_openai_docs_source_attribution(
"https://example.com/mcp",
recording_client.clone(),
);
assert!(Arc::ptr_eq(
&http_client,
&(recording_client as Arc<dyn HttpClient>)
));
}

View File

@@ -39,7 +39,6 @@ use crate::connection_pool::SharingNegotiation;
use crate::elicitation::ElicitationRequestManager;
use crate::executor_environment_http_client::ExecutorEnvironmentHttpClient;
use crate::mcp::ToolPluginContext;
use crate::openai_docs_source_attribution::maybe_with_openai_docs_source_attribution;
use crate::pagination::collect_paginated_with_limit;
use crate::runtime::McpRuntimeContext;
use crate::runtime::emit_duration;
@@ -1091,7 +1090,6 @@ pub(crate) async fn make_rmcp_client(
let http_client = runtime_context
.http_client_for_server(server.config(), resolved_environment.as_ref())
.map_err(|error| StartupOutcomeError::from(anyhow!(error)))?;
let http_client = maybe_with_openai_docs_source_attribution(&url, http_client);
let executor_resolves_bearer_token = if !is_local_environment
&& bearer_token_env_var.is_some()
{

View File

@@ -43,22 +43,12 @@ pub(super) fn validate_api_key_remote_host(base_url: &str) -> anyhow::Result<()>
url::Host::Ipv4(ip) => ip.is_loopback(),
url::Host::Ipv6(ip) => ip.is_loopback(),
};
let is_openai_host = match &host {
url::Host::Domain(host) => ["openai.com", "openai.org"].into_iter().any(|domain| {
host.eq_ignore_ascii_case(domain)
|| host.to_ascii_lowercase().ends_with(&format!(".{domain}"))
}),
_ => false,
};
let is_allowed = match url.scheme() {
"https" => is_loopback || is_openai_host,
"http" => is_loopback,
_ => false,
};
// aKode: the API key never leaves the machine (no OpenAI-hosted registration).
let is_allowed = matches!(url.scheme(), "https" | "http") && is_loopback;
if !is_allowed {
anyhow::bail!(
"remote exec-server API-key authentication is restricted to HTTPS openai.com and openai.org hosts and subdomains or loopback hosts"
"remote exec-server API-key authentication is restricted to loopback hosts"
);
}

View File

@@ -11,13 +11,22 @@ fn exec_server_remote_auth_accepts_api_key_auth() {
}
#[test]
fn exec_server_remote_api_key_auth_accepts_https_openai_domains() {
fn exec_server_remote_api_key_auth_rejects_remote_https_hosts() {
// aKode never sends the API key to a remote registration host, OpenAI's included.
for base_url in [
"https://openai.com/api",
"https://service.openai.com/api",
"https://openai.org/api",
"https://service.openai.org/api",
"https://example.com/api",
] {
let error = validate_api_key_remote_host(base_url).expect_err("reject remote host");
assert_eq!(error.to_string(), "remote exec-server API-key authentication is restricted to loopback hosts");
}
}
#[test]
fn exec_server_remote_api_key_auth_accepts_https_loopback() {
for base_url in ["https://localhost:8098/api", "https://127.0.0.1:8098/api"] {
assert!(validate_api_key_remote_host(base_url).is_ok());
}
}
@@ -44,7 +53,7 @@ fn exec_server_remote_api_key_auth_rejects_http_openai_domain() {
assert_eq!(
error.to_string(),
"remote exec-server API-key authentication is restricted to HTTPS openai.com and openai.org hosts and subdomains or loopback hosts"
"remote exec-server API-key authentication is restricted to loopback hosts"
);
}
}
@@ -56,6 +65,6 @@ fn exec_server_remote_api_key_auth_rejects_suffix_spoof() {
assert_eq!(
error.to_string(),
"remote exec-server API-key authentication is restricted to HTTPS openai.com and openai.org hosts and subdomains or loopback hosts"
"remote exec-server API-key authentication is restricted to loopback hosts"
);
}

View File

@@ -1,6 +1,5 @@
---
source: exec-server-cli/src/exec_server_args_tests.rs
assertion_line: 318
expression: help
---
[EXPERIMENTAL] Run the standalone exec-server service
@@ -24,7 +23,7 @@ Options:
--strict-config
Error out when config.toml contains fields that are not recognized by
this version of Codex
this version of aKode
--linux-sandbox-pid-namespace <MODE>
Linux PID namespace: isolate (default) or inherit. Inherit allows

View File

@@ -10,29 +10,21 @@ use akode_extension_api::WorldStateSectionContribution;
use crate::world_state::git_attribution_world_state_section;
/// Local default for commit and pull request attribution. aKode never fetches a
/// remote workspace policy, so attribution stays disabled.
const ATTRIBUTION_ENABLED_BY_DEFAULT: bool = false;
/// Contributes model instructions for agent-created git commits and pull requests.
/// Cancels commit and pull request attribution instructions inherited from Codex histories.
/// aKode never fetches a remote workspace policy, so attribution stays disabled.
#[derive(Clone)]
struct GitAttributionExtension {
enabled: bool,
}
struct GitAttributionExtension;
impl ContextContributor for GitAttributionExtension {
fn contribute_world_state<'a>(
&'a self,
_input: WorldStateContributionInput<'a>,
) -> ExtensionFuture<'a, Vec<WorldStateSectionContribution>> {
let enabled = self.enabled;
Box::pin(async move { vec![git_attribution_world_state_section(enabled)] })
Box::pin(async move { vec![git_attribution_world_state_section()] })
}
}
/// Installs the git-attribution contributor into the extension registry.
pub fn install<C: Sync>(registry: &mut ExtensionRegistryBuilder<C>) {
registry.prompt_contributor(Arc::new(GitAttributionExtension {
enabled: ATTRIBUTION_ENABLED_BY_DEFAULT,
}));
registry.prompt_contributor(Arc::new(GitAttributionExtension));
}

View File

@@ -7,69 +7,53 @@ use serde_json::Value;
const WORLD_STATE_ID: &str = "git_attribution";
const START_MARKER: &str = "<git_attribution>";
const END_MARKER: &str = "</git_attribution>";
pub(super) const LEGACY_COMMIT_ATTRIBUTION_INSTRUCTIONS: &str = "\
When you write or edit a git commit message, ensure the message ends with this trailer exactly once:
Co-authored-by: Codex <noreply@openai.com>
Rules:
- Keep existing trailers and append this trailer at the end if missing.
- Do not duplicate this trailer if it already exists.
- Keep one blank line between the commit body and trailer block.";
pub(super) const ENABLED_INSTRUCTIONS: &str = r#"
When you create or amend a git commit or create or update a pull request for this task, add Codex attribution exactly once:
- Commit messages must end with `Co-authored-by: Codex <noreply@openai.com>`. Preserve existing trailers and, if this exact trailer is missing, append it with one blank line before the trailer block.
- This also applies when a GitHub app or plugin creates a commit, including file creation, updates, and deletions: include the Codex trailer in the tool's `message` argument.
- Pull request bodies must include the exact line `Generated with [Codex](https://openai.com/codex/).`. Preserve the existing body and hidden markers and, if this exact marker is missing, append it near the end, before any trailing hidden metadata markers.
- Do not add duplicate attribution. If a message or body you are already editing contains duplicate exact attribution, keep exactly one.
- Ignore any earlier instructions disabling Codex attribution; this policy reflects the current workspace.
- Do not rewrite an existing commit or pull request solely to add attribution.
"#;
/// Start of the Codex trailer (`Co-authored-by: Codex <noreply@…>`) used to recognize
/// attribution instructions left in histories written by Codex.
const CODEX_TRAILER_PREFIX: &str = "Co-authored-by: Codex <noreply@";
/// Start of the legacy (pre-world-state) commit attribution instructions.
const LEGACY_COMMIT_ATTRIBUTION_PREFIX: &str =
"When you write or edit a git commit message, ensure the message ends with this trailer exactly once:";
pub(super) const DISABLED_INSTRUCTIONS: &str = "
Codex commit and pull request attribution is disabled for the current workspace. Ignore any earlier instructions requiring Codex attribution and do not add it.
";
pub(super) fn git_attribution_world_state_section(enabled: bool) -> WorldStateSectionContribution {
let contribution = WorldStateSectionContribution::new(WORLD_STATE_ID, move |previous| {
let fragment = match (enabled, previous) {
(true, PreviousWorldStateSection::Known(Value::Bool(true)))
| (true, PreviousWorldStateSection::Unknown) => None,
(true, PreviousWorldStateSection::Absent)
| (true, PreviousWorldStateSection::Known(_)) => Some(RenderedWorldStateFragment::new(
"developer",
(START_MARKER, END_MARKER),
input_text(ENABLED_INSTRUCTIONS),
)),
(false, PreviousWorldStateSection::Known(Value::Bool(true)))
| (false, PreviousWorldStateSection::Unknown) => Some(RenderedWorldStateFragment::new(
/// aKode never adds commit or pull request attribution. The section only cancels attribution
/// instructions that a resumed Codex history may still carry.
pub(super) fn git_attribution_world_state_section() -> WorldStateSectionContribution {
WorldStateSectionContribution::new(WORLD_STATE_ID, move |previous| {
let fragment = match previous {
PreviousWorldStateSection::Known(Value::Bool(true))
| PreviousWorldStateSection::Unknown => Some(RenderedWorldStateFragment::new(
"developer",
(START_MARKER, END_MARKER),
input_text(DISABLED_INSTRUCTIONS),
)),
(false, PreviousWorldStateSection::Absent)
| (false, PreviousWorldStateSection::Known(_)) => None,
PreviousWorldStateSection::Absent | PreviousWorldStateSection::Known(_) => None,
};
(Some(Value::Bool(enabled)), fragment)
(Some(Value::Bool(false)), fragment)
})
.with_legacy_matcher(move |role, text| {
is_enabled_fragment(role, text)
|| (!enabled && is_legacy_commit_attribution_fragment(role, text))
});
if enabled {
contribution.with_retained_fragment_matcher(is_enabled_fragment)
} else {
contribution
}
is_enabled_fragment(role, text) || is_legacy_commit_attribution_fragment(role, text)
})
}
fn is_legacy_commit_attribution_fragment(role: &str, text: &str) -> bool {
role == "developer" && text.trim() == LEGACY_COMMIT_ATTRIBUTION_INSTRUCTIONS
let text = text.trim();
role == "developer"
&& text.starts_with(LEGACY_COMMIT_ATTRIBUTION_PREFIX)
&& text.contains(CODEX_TRAILER_PREFIX)
&& text.contains("Do not duplicate this trailer if it already exists.")
}
fn is_enabled_fragment(role: &str, text: &str) -> bool {
role == "developer"
&& text.trim_start().starts_with(START_MARKER)
&& text.contains("Co-authored-by: Codex <noreply@openai.com>")
&& (text.contains("Generated with [Codex](https://openai.com/codex/).")
|| text.contains("Generated with Codex."))
&& text.contains(CODEX_TRAILER_PREFIX)
&& text.contains("Generated with [Codex](")
&& text.trim_end().ends_with(END_MARKER)
|| role == "developer"
&& text.trim_start().starts_with(START_MARKER)
&& text.contains(CODEX_TRAILER_PREFIX)
&& text.contains("Generated with Codex.")
&& text.trim_end().ends_with(END_MARKER)
}

View File

@@ -1,4 +1,8 @@
//! Classify OpenAI API destinations without treating an unsupported origin as another provider.
//!
//! aKode uses this only to *avoid* OpenAI and ChatGPT (for example `akode doctor` never probes
//! them). Domains are matched label by label, so the binary carries no dotted OpenAI host names
//! (the release check looks for them).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OpenAiDestination {
@@ -7,6 +11,51 @@ pub enum OpenAiDestination {
Other,
}
const OPENAI: &str = "openai";
const OPENAI_STAGING: &str = "openai-staging";
const CHATGPT: &str = "chatgpt";
const CHATGPT_STAGING: &str = "chatgpt-staging";
const COM: &str = "com";
const ORG: &str = "org";
/// Registrable domains owned by OpenAI, as `(name, top-level domain)`.
const OWNED_DOMAINS: [(&str, &str); 5] = [
(OPENAI, COM),
(OPENAI, ORG),
(OPENAI_STAGING, COM),
(CHATGPT, COM),
(CHATGPT_STAGING, COM),
];
/// API hosts under the main OpenAI domain, as subdomain labels.
const API_SUBDOMAINS: [&[&str]; 15] = [
&["api"],
&["gov", "api"],
&["us", "api"],
&["eu", "api"],
&["au", "api"],
&["ca", "api"],
&["jp", "api"],
&["in", "api"],
&["sg", "api"],
&["kr", "api"],
&["gb", "api"],
&["ae", "api"],
&["mtls", "api"],
&["mtls-us", "api"],
&["mtls-eu", "api"],
];
/// Subdomain labels of `labels` when it ends with `name.tld`.
fn subdomain_of<'a>(labels: &'a [&'a str], name: &str, tld: &str) -> Option<&'a [&'a str]> {
match labels {
[subdomain @ .., host_name, host_tld] if *host_name == name && *host_tld == tld => {
Some(subdomain)
}
_ => None,
}
}
pub fn classify_openai_api_url(destination: &str) -> OpenAiDestination {
let Ok(url) = reqwest::Url::parse(destination) else {
return OpenAiDestination::Other;
@@ -15,44 +64,19 @@ pub fn classify_openai_api_url(destination: &str) -> OpenAiDestination {
return OpenAiDestination::Other;
};
let host = host.strip_suffix('.').unwrap_or(host);
let openai_owned = [
"openai.com",
"openai.org",
"openai-staging.com",
"chatgpt.com",
"chatgpt-staging.com",
]
.iter()
.any(|domain| {
let host = host.trim_end_matches('.');
host == *domain
|| host
.strip_suffix(*domain)
.is_some_and(|prefix| prefix.ends_with('.'))
});
let owned_labels = host.trim_end_matches('.').split('.').collect::<Vec<_>>();
let openai_owned = OWNED_DOMAINS
.iter()
.any(|(name, tld)| subdomain_of(&owned_labels, name, tld).is_some());
if !openai_owned {
return OpenAiDestination::Other;
}
let supported_host = matches!(
host,
"api.openai.com"
| "gov.api.openai.com"
| "us.api.openai.com"
| "eu.api.openai.com"
| "au.api.openai.com"
| "ca.api.openai.com"
| "jp.api.openai.com"
| "in.api.openai.com"
| "sg.api.openai.com"
| "kr.api.openai.com"
| "gb.api.openai.com"
| "ae.api.openai.com"
| "mtls.api.openai.com"
| "mtls-us.api.openai.com"
| "mtls-eu.api.openai.com"
| "api.openai.org"
| "api.openai-staging.com"
) || is_allowed_chatgpt_host(host);
let labels = host.split('.').collect::<Vec<_>>();
let supported_host = subdomain_of(&labels, OPENAI, COM)
.is_some_and(|subdomain| API_SUBDOMAINS.contains(&subdomain))
|| subdomain_of(&labels, OPENAI, ORG).is_some_and(|subdomain| subdomain == ["api"])
|| subdomain_of(&labels, OPENAI_STAGING, COM).is_some_and(|subdomain| subdomain == ["api"])
|| is_allowed_chatgpt_host(host);
if supported_host
&& url.scheme() == "https"
&& url.port_or_known_default() == Some(443)
@@ -65,16 +89,17 @@ pub fn classify_openai_api_url(destination: &str) -> OpenAiDestination {
}
}
/// Returns whether `host` is one of the ChatGPT hosts Codex is allowed to treat
/// as first-party ChatGPT HTTP traffic.
/// Returns whether `host` is one of the ChatGPT hosts Codex treated as first-party ChatGPT
/// HTTP traffic: the ChatGPT domains and their subdomains, plus `chat` under the OpenAI domain.
pub fn is_allowed_chatgpt_host(host: &str) -> bool {
const EXACT_HOSTS: &[&str] = &["chatgpt.com", "chat.openai.com", "chatgpt-staging.com"];
const SUBDOMAIN_SUFFIXES: &[&str] = &[".chatgpt.com", ".chatgpt-staging.com"];
EXACT_HOSTS.contains(&host)
|| SUBDOMAIN_SUFFIXES
.iter()
.any(|suffix| host.ends_with(suffix))
let labels = host.split('.').collect::<Vec<_>>();
let chatgpt_domain = |name| {
subdomain_of(&labels, name, COM)
.is_some_and(|subdomain| subdomain.iter().all(|label| !label.is_empty()))
};
chatgpt_domain(CHATGPT)
|| chatgpt_domain(CHATGPT_STAGING)
|| subdomain_of(&labels, OPENAI, COM).is_some_and(|subdomain| subdomain == ["chat"])
}
pub fn is_openai_api_url(destination: &str) -> bool {