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

@@ -242,28 +242,6 @@ fn print_startup_config_preserves_project_login_restrictions() -> Result<()> {
Ok(())
}
#[test]
fn print_startup_config_rejects_sign_out_with_environment_access_token() -> Result<()> {
let home = TempDir::new()?;
let auth_path = home.path().join("auth.json");
let saved_auth = br#"{"OPENAI_API_KEY":"saved-test-key"}"#;
std::fs::write(&auth_path, saved_auth)?;
for token in ["at-test-token", "header.payload.signature"] {
let output = codex_command(home.path())?
.env("CODEX_ACCESS_TOKEN", token)
.args(["app-server", "--print-startup-config", "--startup-sign-out"])
.assert()
.failure();
let value: serde_json::Value = serde_json::from_slice(&output.get_output().stdout)?;
assert_eq!(
value["error"]["message"],
"Configured external authentication is owned by the app-server host and cannot be changed during startup recovery."
);
assert_eq!(std::fs::read(&auth_path)?, saved_auth);
}
Ok(())
}
#[test]
fn print_startup_config_validates_configuration() -> Result<()> {
let home = TempDir::new()?;

View File

@@ -1,688 +0,0 @@
use std::process::Output;
use std::process::Stdio;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_config::ConfigLoadOptions;
use codex_config::types::AuthCredentialsStoreMode;
use codex_core::config::load_config_toml_with_layer_stack;
use codex_core::config::load_global_mcp_servers;
use codex_core_plugins::installed_marketplaces::marketplace_install_root;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::net::TcpStream;
use tokio::process::Command;
use tokio::time::timeout;
use url::Url;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_string_contains;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
const MANAGED_SERVER_NAME: &str = "managed-slack";
const MANAGED_CLIENT_ID: &str = "managed-oauth-client";
const MANAGED_SCOPE: &str = "managed.read";
const MOCK_ACCESS_TOKEN: &str = "mock-managed-access-token";
const MOCK_REFRESH_TOKEN: &str = "mock-managed-refresh-token";
struct CloudManagedConfigFixture {
server: MockServer,
codex_home: TempDir,
user_config: String,
mcp_url: String,
}
impl CloudManagedConfigFixture {
async fn for_backend() -> Result<Option<Self>> {
let server = MockServer::start().await;
let chatgpt_base_url = format!("{}/backend-api", server.uri());
let codex_home = TempDir::new()?;
let user_config = format!(
"cli_auth_credentials_store = \"file\"\nchatgpt_base_url = \"{chatgpt_base_url}\"\n"
);
std::fs::write(codex_home.path().join("config.toml"), &user_config)?;
let bootstrap_config = load_config_toml_with_layer_stack(
codex_home.path(),
Some(&AbsolutePathBuf::from_absolute_path(codex_home.path())?),
Vec::new(),
ConfigLoadOptions::default(),
)
.await?;
if bootstrap_config.config_toml.cli_auth_credentials_store
!= Some(AuthCredentialsStoreMode::File)
|| bootstrap_config.config_toml.chatgpt_base_url.as_deref()
!= Some(chatgpt_base_url.as_str())
{
eprintln!(
"skipping cloud-managed subprocess: host-managed authentication or backend routing prevents isolated mock credentials"
);
return Ok(None);
}
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("workspace-123")
.chatgpt_account_id("workspace-123")
.chatgpt_user_id("user-123")
.plan_type("enterprise"),
AuthCredentialsStoreMode::File,
)?;
let mcp_url = format!("{}/mcp", server.uri());
Ok(Some(Self {
server,
codex_home,
user_config,
mcp_url,
}))
}
async fn new() -> Result<Option<Self>> {
let Some(fixture) = Self::for_backend().await? else {
return Ok(None);
};
let mcp_url = &fixture.mcp_url;
let managed_config = format!(
"mcp_oauth_credentials_store = \"file\"\n\n\
[mcp_servers.{MANAGED_SERVER_NAME}]\n\
url = \"{mcp_url}\"\n\
auth = \"oauth\"\n\
scopes = [\"{MANAGED_SCOPE}\"]\n\n\
[mcp_servers.{MANAGED_SERVER_NAME}.oauth]\n\
client_id = \"{MANAGED_CLIENT_ID}\"\n\n\
[marketplaces.managed]\n\
source_type = \"git\"\n\
source = \"https://github.com/owner/repo.git\"\n"
);
Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "workspace-123"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"config_toml": {
"enterprise_managed": [{
"id": "managed-config",
"name": "Managed resources",
"contents": managed_config,
}],
},
})))
.expect(1)
.mount(&fixture.server)
.await;
Ok(Some(fixture))
}
fn command(&self, args: &[&str]) -> Result<Command> {
let mut command = Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
command
.kill_on_drop(true)
.current_dir(self.codex_home.path())
.env("CODEX_HOME", self.codex_home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove("OPENAI_FEDERATION_RULE_ID")
.env_remove("OPENAI_IDENTITY_TOKEN_FILE")
.env_remove("OPENAI_WORKLOAD_IDENTITY_CONTEXT")
.args(args);
Ok(command)
}
async fn output(&self, args: &[&str]) -> Result<Output> {
let output = self.command(args)?.output().await?;
ensure!(
output.status.success(),
"codex {} failed with status {}: stdout={}; stderr={}",
args.join(" "),
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
Ok(output)
}
fn assert_user_config_unchanged(&self) -> Result<()> {
assert_eq!(
std::fs::read_to_string(self.codex_home.path().join("config.toml"))?,
self.user_config
);
Ok(())
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn list_and_get_resolve_cloud_managed_mcp_without_writing_user_config() -> Result<()> {
let Some(fixture) = CloudManagedConfigFixture::new().await? else {
return Ok(());
};
let output = fixture.output(&["mcp", "list", "--json"]).await?;
let entries: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(entries[0]["name"], MANAGED_SERVER_NAME);
assert_eq!(entries[0]["transport"]["type"], "streamable_http");
assert_eq!(entries[0]["transport"]["url"], fixture.mcp_url);
let output = fixture
.output(&["mcp", "get", MANAGED_SERVER_NAME, "--json"])
.await?;
let entry: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(entry["name"], MANAGED_SERVER_NAME);
assert_eq!(entry["transport"]["url"], fixture.mcp_url);
assert!(
fixture
.codex_home
.path()
.join("cloud-config-bundle-cache.json")
.exists()
);
fixture.assert_user_config_unchanged()?;
fixture.server.verify().await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn login_and_logout_persist_only_cloud_managed_mcp_oauth_credentials() -> Result<()> {
let Some(fixture) = CloudManagedConfigFixture::new().await? else {
return Ok(());
};
let challenge = format!(
"Bearer resource_metadata=\"{}/oauth-resource\"",
fixture.server.uri()
);
Mock::given(method("GET"))
.and(path("/mcp"))
.respond_with(ResponseTemplate::new(401).insert_header("WWW-Authenticate", challenge))
.mount(&fixture.server)
.await;
Mock::given(method("GET"))
.and(path("/oauth-resource"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"resource": fixture.mcp_url,
"authorization_servers": [fixture.server.uri()],
})))
.mount(&fixture.server)
.await;
let oauth_metadata = json!({
"issuer": fixture.server.uri(),
"authorization_endpoint": format!("{}/oauth/authorize", fixture.server.uri()),
"token_endpoint": format!("{}/oauth/token", fixture.server.uri()),
"response_types_supported": ["code"],
"code_challenge_methods_supported": ["S256"],
"scopes_supported": [MANAGED_SCOPE],
});
for metadata_path in [
"/.well-known/oauth-authorization-server",
"/.well-known/oauth-authorization-server/mcp",
] {
Mock::given(method("GET"))
.and(path(metadata_path))
.respond_with(ResponseTemplate::new(200).set_body_json(oauth_metadata.clone()))
.mount(&fixture.server)
.await;
}
Mock::given(method("POST"))
.and(path("/oauth/token"))
.and(body_string_contains(format!(
"client_id={MANAGED_CLIENT_ID}"
)))
.and(body_string_contains("grant_type=authorization_code"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"access_token": MOCK_ACCESS_TOKEN,
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": MOCK_REFRESH_TOKEN,
"scope": MANAGED_SCOPE,
})))
.expect(1)
.mount(&fixture.server)
.await;
let mut command = fixture.command(&["mcp", "login", MANAGED_SERVER_NAME, "--no-browser"])?;
command
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit());
let mut child = command.spawn()?;
// Keep input open through child.wait() so the HTTP callback cannot race EOF.
let _stdin = child
.stdin
.take()
.context("MCP login did not provide stdin")?;
let stdout = child
.stdout
.take()
.context("MCP login did not provide captured stdout")?;
let mut lines = BufReader::new(stdout).lines();
let authorization_url = timeout(Duration::from_secs(30), async {
while let Some(line) = lines.next_line().await? {
if line.starts_with("http://") || line.starts_with("https://") {
return Ok::<_, anyhow::Error>(Url::parse(line.trim())?);
}
}
anyhow::bail!("MCP login exited before printing its OAuth authorization URL")
})
.await
.context("timed out waiting for the managed MCP authorization URL")??;
let query_pairs: Vec<_> = authorization_url.query_pairs().into_owned().collect();
let state = query_pairs
.iter()
.find(|(name, _)| name == "state")
.map(|(_, value)| value.as_str())
.context("managed MCP authorization URL did not contain OAuth state")?;
assert_eq!(
query_pairs
.iter()
.find(|(name, _)| name == "client_id")
.map(|(_, value)| value.as_str()),
Some(MANAGED_CLIENT_ID)
);
assert_eq!(
query_pairs
.iter()
.find(|(name, _)| name == "scope")
.map(|(_, value)| value.as_str()),
Some(MANAGED_SCOPE)
);
let redirect_uri = query_pairs
.iter()
.find(|(name, _)| name == "redirect_uri")
.map(|(_, value)| value.as_str())
.context("managed MCP authorization URL did not contain a callback")?;
let mut callback_url = Url::parse(redirect_uri)?;
callback_url
.query_pairs_mut()
.append_pair("code", "mock-managed-authorization-code")
.append_pair("state", state);
let callback_host = callback_url
.host_str()
.context("managed MCP callback did not contain a host")?;
let callback_port = callback_url
.port_or_known_default()
.context("managed MCP callback did not contain a port")?;
let callback_path = match callback_url.query() {
Some(query) => format!("{}?{query}", callback_url.path()),
None => callback_url.path().to_string(),
};
let callback_response = timeout(Duration::from_secs(30), async {
let mut callback = TcpStream::connect((callback_host, callback_port)).await?;
callback
.write_all(
format!(
"GET {callback_path} HTTP/1.1\r\nHost: {callback_host}:{callback_port}\r\nConnection: close\r\n\r\n"
)
.as_bytes(),
)
.await?;
let mut response_lines = BufReader::new(callback).lines();
response_lines
.next_line()
.await?
.context("managed MCP OAuth callback returned an empty HTTP response")
})
.await
.context("timed out waiting for the managed MCP OAuth callback response")??;
ensure!(
callback_response.starts_with("HTTP/1.1 200")
|| callback_response.starts_with("HTTP/1.0 200"),
"managed MCP OAuth callback failed: {callback_response}"
);
let login_status = timeout(Duration::from_secs(30), child.wait())
.await
.context("timed out waiting for managed MCP login")??;
ensure!(
login_status.success(),
"managed MCP login failed: status={login_status}"
);
timeout(Duration::from_secs(30), async {
while let Some(line) = lines.next_line().await? {
if line.contains("Successfully logged in to MCP server 'managed-slack'.") {
return Ok::<_, anyhow::Error>(());
}
}
anyhow::bail!("managed MCP login exited before printing its success message")
})
.await
.context("timed out waiting for the managed MCP login success message")??;
let credentials_path = fixture.codex_home.path().join(".credentials.json");
let credentials: Value = serde_json::from_slice(&std::fs::read(&credentials_path)?)?;
let entries = credentials
.as_object()
.context("MCP credentials should be a JSON object")?;
assert_eq!(entries.len(), 1);
let credential = entries
.values()
.next()
.context("managed MCP OAuth credentials were not persisted")?;
assert_eq!(credential["server_name"], MANAGED_SERVER_NAME);
assert_eq!(credential["server_url"], fixture.mcp_url);
assert_eq!(credential["client_id"], MANAGED_CLIENT_ID);
assert_eq!(credential["access_token"], MOCK_ACCESS_TOKEN);
assert_eq!(credential["refresh_token"], MOCK_REFRESH_TOKEN);
assert_eq!(credential["scopes"], json!([MANAGED_SCOPE]));
fixture.assert_user_config_unchanged()?;
let list_output = fixture.output(&["mcp", "list", "--json"]).await?;
let entries: Value = serde_json::from_slice(&list_output.stdout)?;
assert_eq!(entries[0]["name"], MANAGED_SERVER_NAME);
assert_eq!(entries[0]["auth_status"], "o_auth");
let logout_output = fixture
.output(&["mcp", "logout", MANAGED_SERVER_NAME])
.await?;
assert!(
String::from_utf8(logout_output.stdout)?
.contains("Removed OAuth credentials for 'managed-slack'.")
);
assert!(!credentials_path.exists());
fixture.assert_user_config_unchanged()?;
fixture.server.verify().await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn add_and_remove_preserve_cloud_managed_resources() -> Result<()> {
let Some(fixture) = CloudManagedConfigFixture::new().await? else {
return Ok(());
};
let installed_root = marketplace_install_root(fixture.codex_home.path()).join("managed");
std::fs::create_dir_all(&installed_root)?;
let marker = installed_root.join("marker.txt");
std::fs::write(&marker, "installed")?;
// Exercise both the initial fetch and the cached bundle without a user entry.
for _ in 0..2 {
let output = fixture
.command(&["plugin", "marketplace", "remove", "managed"])?
.output()
.await?;
assert!(!output.status.success());
assert!(String::from_utf8(output.stderr)?.contains(
"marketplace `managed` is configured in enterprise-managed (Managed resources, managed-config); remove it from that configuration source instead"
));
fixture.assert_user_config_unchanged()?;
assert_eq!(std::fs::read_to_string(&marker)?, "installed");
}
fixture
.output(&["mcp", "get", MANAGED_SERVER_NAME, "--json"])
.await?;
fixture
.output(&["mcp", "add", "local-docs", "--", "echo", "hello"])
.await?;
let local_servers = load_global_mcp_servers(fixture.codex_home.path()).await?;
assert!(local_servers.contains_key("local-docs"));
assert!(!local_servers.contains_key(MANAGED_SERVER_NAME));
let output = fixture
.output(&["mcp", "remove", MANAGED_SERVER_NAME])
.await?;
assert!(
String::from_utf8(output.stdout)?.contains("No MCP server named 'managed-slack' found.")
);
let local_servers = load_global_mcp_servers(fixture.codex_home.path()).await?;
assert!(local_servers.contains_key("local-docs"));
assert!(!local_servers.contains_key(MANAGED_SERVER_NAME));
fixture.output(&["mcp", "remove", "local-docs"]).await?;
assert!(
load_global_mcp_servers(fixture.codex_home.path())
.await?
.is_empty()
);
fixture
.output(&["mcp", "get", MANAGED_SERVER_NAME, "--json"])
.await?;
fixture.server.verify().await;
Ok(())
}
async fn mock_startup_bundle(server: &MockServer, status: u16, config: &str, requirements: &str) {
server.reset().await;
let layer = |contents: &str| {
json!({
"enterprise_managed": [{"id": "startup", "name": "Startup policy", "contents": contents}]
})
};
Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.and(header("authorization", "Bearer chatgpt-token"))
.respond_with(ResponseTemplate::new(status).set_body_json(json!({
"config_toml": layer(config), "requirements_toml": layer(requirements),
})))
.expect(1..)
.mount(server)
.await;
}
async fn successful_json(command: &mut Command) -> Result<Value> {
let output = command.output().await?;
ensure!(output.status.success(), "{output:?}");
Ok(serde_json::from_slice(&output.stdout)?)
}
#[tokio::test]
async fn startup_config_loads_managed_policy_or_reports_cloud_failure() -> Result<()> {
for status in [200, 401, 503] {
let Some(fixture) = CloudManagedConfigFixture::new().await? else {
return Ok(());
};
mock_startup_bundle(
&fixture.server,
status,
"forced_login_method = 'api'\n",
"[application.network.domains]\n'127.0.0.1' = 'allow'\n'example.com' = 'allow'\n",
)
.await;
let sqlite_home = TempDir::new()?;
let history_path = sqlite_home.path().join("state_5.sqlite");
std::fs::write(&history_path, b"history must not be repaired")?;
let output = fixture
.command(&["app-server", "--print-startup-config"])?
.env("CODEX_SQLITE_HOME", sqlite_home.path())
.env(
"CODEX_REFRESH_TOKEN_URL_OVERRIDE",
format!("{}/refresh", fixture.server.uri()),
)
.output()
.await?;
let value: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(output.status.success(), status == 200, "{value}");
if status == 200 {
let requirements = &value["configRequirements"]["requirements"];
assert_eq!(requirements["allowedLoginMethods"], json!(["api"]));
assert_eq!(
requirements["application"]["network"]["domains"]["example.com"],
"allow"
);
} else {
assert_eq!(value["error"]["data"]["reason"], "cloudConfigBundle");
assert!(value.get("configRequirements").is_none());
}
assert_eq!(
std::fs::read(&history_path)?,
b"history must not be repaired"
);
assert_eq!(std::fs::read_dir(sqlite_home.path())?.count(), 1);
fixture.server.verify().await;
}
Ok(())
}
#[tokio::test]
async fn startup_config_sign_out_reloads_policy_without_starting_runtime() -> Result<()> {
for (status, provider) in [(200, None), (503, None), (503, Some("amazon-bedrock"))] {
let Some(mut fixture) = CloudManagedConfigFixture::new().await? else {
return Ok(());
};
if let Some(provider) = provider {
fixture
.user_config
.push_str(&format!("model_provider = \"{provider}\"\n"));
}
std::fs::write(
fixture.codex_home.path().join("config.toml"),
&fixture.user_config,
)?;
mock_startup_bundle(
&fixture.server, status, "forced_login_method = 'api'\n",
"cli_auth_credentials_store = 'ephemeral'\nenforce_residency = 'us'\n[application.network.domains]\n'127.0.0.1' = 'allow'\n[windows]\nrequire_mxc = true\n",
).await;
let mut revoke = Mock::given(method("POST")).and(path("/revoke"));
if status == 200 {
revoke = revoke.and(header("x-openai-internal-codex-residency", "us"));
}
revoke
.respond_with(ResponseTemplate::new(200))
.expect(1)
.mount(&fixture.server)
.await;
let signed_out_home = TempDir::new()?;
std::fs::write(
signed_out_home.path().join("config.toml"),
&fixture.user_config,
)?;
let baseline = successful_json(
fixture
.command(&["app-server", "--print-startup-config"])?
.env("CODEX_HOME", signed_out_home.path()),
)
.await?;
let sqlite_home = TempDir::new()?;
let value = successful_json(
fixture
.command(&["app-server", "--print-startup-config", "--startup-sign-out"])?
.env("CODEX_SQLITE_HOME", sqlite_home.path())
.env(
"CODEX_REVOKE_TOKEN_URL_OVERRIDE",
format!("{}/revoke", fixture.server.uri()),
),
)
.await?;
assert_eq!(value["configRequirements"], baseline["configRequirements"]);
assert_eq!(std::fs::read_dir(sqlite_home.path())?.count(), 0);
let user_config: toml::Value = toml::from_str(&std::fs::read_to_string(
fixture.codex_home.path().join("config.toml"),
)?)?;
assert!(user_config.get("model_provider").is_none());
let status = fixture.command(&["login", "status"])?.output().await?;
assert!(!status.status.success());
fixture.server.verify().await;
}
Ok(())
}
const BUNDLE: &str = "/backend-api/wham/config/bundle";
const REGISTER: &str = "/cloud/environment/test/register";
const REGISTRATION_REACHED: &str = "registration reached";
#[tokio::test]
async fn remote_exec_server_loads_cloud_provider_with_chatgpt_auth() -> Result<()> {
check_registration(
"forced_login_method = 'chatgpt'\nmodel_provider = 'cloud-provider'",
Some((
"[model_providers.cloud-provider]\nname = 'Cloud provider'\nwire_api = 'responses'",
"",
)),
"Bearer chatgpt-token",
REGISTRATION_REACHED,
&[BUNDLE, REGISTER],
)
.await
}
#[tokio::test]
async fn remote_exec_server_api_key_skips_chatgpt_cloud_config() -> Result<()> {
check_registration(
"",
/*bundle*/ None,
"Bearer test-api-key",
REGISTRATION_REACHED,
&[REGISTER],
)
.await
}
#[tokio::test]
async fn remote_exec_server_cloud_policy_denies_registration() -> Result<()> {
check_registration(
"forced_login_method = 'chatgpt'",
Some(("", "[application.network]\nenabled = true\n[application.network.domains]\n'gateway.example.com' = 'allow'")),
"Bearer chatgpt-token",
"destination denied by application network policy",
&[BUNDLE],
)
.await
}
async fn check_registration(
config: &str,
bundle: Option<(&str, &str)>,
registration_auth: &str,
expected_error: &str,
expected_paths: &[&str],
) -> Result<()> {
let fixture = CloudManagedConfigFixture::for_backend()
.await?
.context("remote registration test requires isolated mock credentials")?;
let server = &fixture.server;
if let Some((config, requirements)) = bundle {
mock_startup_bundle(server, /*status*/ 200, config, requirements).await;
}
Mock::given(method("POST"))
.and(path(REGISTER))
.and(header("authorization", registration_auth))
.respond_with(ResponseTemplate::new(400).set_body_string(REGISTRATION_REACHED))
.mount(server)
.await;
std::fs::write(
fixture.codex_home.path().join("config.toml"),
format!("{}{config}\n", fixture.user_config),
)?;
let mut command = fixture.command(&[
"exec-server",
"--remote",
&server.uri(),
"--environment-id",
"test",
])?;
command.env("CODEX_API_KEY", "test-api-key");
let output = timeout(Duration::from_secs(30), command.output()).await??;
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
!output.status.success() && stderr.contains(expected_error),
"{stderr}"
);
let requests = server
.received_requests()
.await
.context("mock request log")?;
let paths: Vec<_> = requests.iter().map(|request| request.url.path()).collect();
assert_eq!(paths, expected_paths);
Ok(())
}

View File

@@ -5,9 +5,6 @@ use std::process::Stdio;
use anyhow::Context as _;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_config::types::AuthCredentialsStoreMode;
use codex_state::SqliteConfig;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
@@ -170,7 +167,7 @@ async fn network_only_reports_recoverable_config_warnings_and_effective_config()
},
"config": {
"summary": "config loaded",
"scope": "invocation config, including cloud-managed policy",
"scope": "invocation config, including managed policy",
"provider": "local",
"startupWarnings": baseline_warning_count + 1,
"startupWarning": "Ignoring invalid `otel.span_attributes` config: configured span attribute key must not be empty",
@@ -247,124 +244,6 @@ async fn network_only_config_failure_human_output() -> Result<()> {
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn doctor_reports_cloud_filesystem_policy_and_rejects_invalid_requirements() -> Result<()> {
for valid_requirements in [true, false] {
let server = MockServer::start().await;
let codex_home = TempDir::new()?;
let workspace = TempDir::new()?;
let workspace_key = serde_json::to_string(workspace.path())?;
let private_path = workspace.path().join("private-doctor-control");
let glob = format!("{}/**/*.doctor-secret", workspace.path().display());
let requirements = if valid_requirements {
format!("[permissions.filesystem]\ndeny_read = [{private_path:?}, {glob:?}]\n")
} else {
"[permissions.filesystem]\ndeny_read = false\n".to_string()
};
std::fs::write(
codex_home.path().join("config.toml"),
format!(
r#"
cli_auth_credentials_store = "ephemeral"
chatgpt_base_url = "{}/backend-api"
model_provider = "local"
[model_providers.local]
name = "local"
base_url = "{}/v1"
wire_api = "responses"
[windows]
sandbox = "elevated"
[projects.{workspace_key}]
trust_level = "trusted"
"#,
server.uri(),
server.uri(),
),
)?;
// Cloud authentication must use the project selected by --cd.
std::fs::create_dir(workspace.path().join(".codex"))?;
std::fs::write(
workspace.path().join(".codex/config.toml"),
"cli_auth_credentials_store = \"file\"\n",
)?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("doctor-test-token")
.account_id("doctor-workspace")
.chatgpt_account_id("doctor-workspace")
.chatgpt_user_id("doctor-user")
.plan_type("enterprise"),
AuthCredentialsStoreMode::File,
)?;
Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"requirements_toml": {
"enterprise_managed": [{
"id": "doctor-policy",
"name": "Doctor policy fixture",
"contents": requirements,
}],
},
})))
.expect(1)
.mount(&server)
.await;
let output = Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
.current_dir(codex_home.path())
.env("CODEX_HOME", codex_home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.arg("--cd")
.arg(workspace.path())
.args(["doctor", "--json"])
.stdin(Stdio::null())
.output()?;
let report: Value = serde_json::from_slice(&output.stdout)?;
if valid_requirements {
let config = &report["checks"]["config.load"];
let sandbox = &report["checks"]["sandbox.helpers"]["details"];
assert_eq!(config["status"], "ok", "{config:#}");
assert_eq!(
config["details"]["cwd"],
workspace.path().display().to_string()
);
insta::assert_snapshot!(
serde_json::to_string_pretty(&json!({
"scope": config["details"]["configuration scope"],
"activeThreadOverrides": config["details"]["active thread overrides"],
"denyRules": sandbox["denied-read rules"],
"denyGlobs": sandbox["denied-read glob rules"],
"scanDepth": sandbox["glob scan max depth"],
"managedFilesystemSource": sandbox["managed filesystem source"],
}))?,
@r#"
{
"scope": "invocation config, including cloud-managed policy",
"activeThreadOverrides": "not inspected",
"denyRules": "2",
"denyGlobs": "1",
"scanDepth": "unbounded",
"managedFilesystemSource": "cloud"
}
"#
);
let stdout = String::from_utf8(output.stdout)?;
assert!(!stdout.contains("doctor-secret"));
assert!(!stdout.contains("private-doctor-control"));
} else {
assert_eq!(report["checks"]["config.load"]["status"], "fail");
assert!(report["checks"].get("sandbox.helpers").is_none());
}
server.verify().await;
}
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn invalid_custom_ca_falls_back_to_system_roots() -> Result<()> {
let server = MockServer::start().await;

View File

@@ -2,9 +2,6 @@
#[path = "exec_server/pid_namespace_tests.rs"]
mod pid_namespace_tests;
#[path = "exec_server/auth_refresh_tests.rs"]
mod auth_refresh_tests;
use std::collections::HashMap;
#[cfg(unix)]
use std::io::BufRead as _;
@@ -206,250 +203,6 @@ fn local_exec_server_allows_disabled_parent_lifetime_environment_variable() -> R
Ok(())
}
enum PatCredentialChange {
Rotate,
SwitchAccount,
Logout,
Unchanged,
UnavailableReplacement,
SlowReplacement,
}
async fn assert_pat_registry_reload(change: PatCredentialChange) -> Result<()> {
let home = TempDir::new()?;
let config_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.and(header("authorization", "Bearer at-synthetic-executor-pat"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"config_toml": {"enterprise_managed": []},
"requirements_toml": {"enterprise_managed": []},
})))
.expect(1)
.mount(&config_server)
.await;
std::fs::write(
home.path().join("config.toml"),
format!(
"cli_auth_credentials_store = 'file'\nchatgpt_base_url = '{}/backend-api'\n",
config_server.uri(),
),
)?;
let auth_path = home.path().join("auth.json");
std::fs::write(
&auth_path,
serde_json::to_vec(&serde_json::json!({
"personal_access_token": "at-synthetic-executor-pat",
}))?,
)?;
let auth_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/v1/user-auth-credential/whoami"))
.and(header("authorization", "Bearer at-synthetic-executor-pat"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"chatgpt_user_id": "user-pat-test",
"chatgpt_account_id": "account-pat-test",
"chatgpt_plan_type": "enterprise",
"chatgpt_account_is_fedramp": false,
})))
// Cloud-config bootstrap and executor startup each hydrate once.
// Later registry requests must reuse metadata for the unchanged PAT.
.with_priority(1)
.up_to_n_times(2)
.expect(2)
.mount(&auth_server)
.await;
Mock::given(method("GET"))
.and(path("/v1/user-auth-credential/whoami"))
.respond_with(ResponseTemplate::new(503))
.with_priority(10)
.expect(0)
.mount(&auth_server)
.await;
if !matches!(
change,
PatCredentialChange::Logout | PatCredentialChange::Unchanged
) {
let account = match change {
PatCredentialChange::Rotate
| PatCredentialChange::UnavailableReplacement
| PatCredentialChange::SlowReplacement => "account-pat-test",
PatCredentialChange::SwitchAccount => "another-account",
PatCredentialChange::Logout | PatCredentialChange::Unchanged => unreachable!(),
};
if matches!(change, PatCredentialChange::UnavailableReplacement) {
Mock::given(method("GET"))
.and(path("/v1/user-auth-credential/whoami"))
.and(header(
"authorization",
"Bearer at-synthetic-replacement-pat",
))
.respond_with(ResponseTemplate::new(503))
.with_priority(1)
.up_to_n_times(1)
.expect(1)
.mount(&auth_server)
.await;
}
let response = ResponseTemplate::new(200).set_body_json(serde_json::json!({
"chatgpt_user_id": "user-pat-test",
"chatgpt_account_id": account,
"chatgpt_plan_type": "enterprise",
"chatgpt_account_is_fedramp": false,
}));
// Exceed registration's 10-second deadline while the detached auth
// resolution can still finish within its own 30-second budget.
let response = if matches!(change, PatCredentialChange::SlowReplacement) {
response.set_delay(Duration::from_secs(11))
} else {
response
};
Mock::given(method("GET"))
.and(path("/v1/user-auth-credential/whoami"))
.and(header(
"authorization",
"Bearer at-synthetic-replacement-pat",
))
.respond_with(response)
.with_priority(2)
.expect(1)
.mount(&auth_server)
.await;
}
let expected_registry_requests = match change {
PatCredentialChange::Rotate
| PatCredentialChange::Unchanged
| PatCredentialChange::UnavailableReplacement
| PatCredentialChange::SlowReplacement => 2,
PatCredentialChange::SwitchAccount | PatCredentialChange::Logout => 1,
};
let second_bearer = if matches!(change, PatCredentialChange::Unchanged) {
"Bearer at-synthetic-executor-pat"
} else {
"Bearer at-synthetic-replacement-pat"
};
let registry = MockServer::start().await;
let registration_path = "/cloud/environment/environment-pat-test/register";
let (credential_change_tx, mut credential_change_rx) = tokio::sync::mpsc::unbounded_channel();
Mock::given(method("POST"))
.and(path(registration_path))
.and(header("authorization", "Bearer at-synthetic-executor-pat"))
.and(header("chatgpt-account-id", "account-pat-test"))
.respond_with(move |_: &wiremock::Request| {
let result = match change {
PatCredentialChange::Rotate
| PatCredentialChange::SwitchAccount
| PatCredentialChange::UnavailableReplacement
| PatCredentialChange::SlowReplacement => std::fs::write(
&auth_path,
r#"{"personal_access_token":"at-synthetic-replacement-pat"}"#,
),
PatCredentialChange::Logout => std::fs::remove_file(&auth_path),
PatCredentialChange::Unchanged => Ok(()),
};
let _ = credential_change_tx.send(result);
ResponseTemplate::new(502).set_body_json(serde_json::json!({
"detail": {"code": "authentication_service_unavailable"},
}))
})
.with_priority(1)
.up_to_n_times(1)
.expect(1)
.mount(&registry)
.await;
Mock::given(method("POST"))
.and(path(registration_path))
.and(header("authorization", second_bearer))
.and(header("chatgpt-account-id", "account-pat-test"))
.respond_with(ResponseTemplate::new(403))
.with_priority(2)
.expect(expected_registry_requests - 1)
.mount(&registry)
.await;
let mut command = tokio::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
command
.current_dir(home.path())
.env("CODEX_HOME", home.path())
.env_remove("CODEX_ACCESS_TOKEN")
.env("CODEX_AUTHAPI_BASE_URL", auth_server.uri())
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.args([
"exec-server",
"--remote",
&registry.uri(),
"--environment-id",
"environment-pat-test",
])
.kill_on_drop(true);
// A same-owner replacement reaches the second registry request, whose denial
// stops the executor. Logout or a different owner must fail before that request.
let result = tokio::time::timeout(Duration::from_secs(30), command.output()).await;
assert!(
result.is_ok(),
"executor timed out (AuthAPI request count: {:?})",
auth_server
.received_requests()
.await
.map(|requests| requests.len()),
);
let output = result??;
let credential_update = credential_change_rx.try_recv();
assert!(
credential_update.is_ok(),
"registration did not update the credential fixture ({}): {}",
output.status,
String::from_utf8_lossy(&output.stderr),
);
credential_update?.context("update the stored PAT fixture")?;
assert!(!output.status.success());
registry.verify().await;
auth_server.verify().await;
config_server.verify().await;
assert_eq!(
registry
.received_requests()
.await
.context("registry request recording is disabled")?
.len(),
expected_registry_requests as usize
);
Ok(())
}
#[tokio::test]
async fn remote_exec_server_pat_follows_stored_rotation() -> Result<()> {
assert_pat_registry_reload(PatCredentialChange::Rotate).await
}
#[tokio::test]
async fn remote_exec_server_pat_rejects_account_switch() -> Result<()> {
assert_pat_registry_reload(PatCredentialChange::SwitchAccount).await
}
#[tokio::test]
async fn remote_exec_server_pat_stops_using_removed_credentials() -> Result<()> {
assert_pat_registry_reload(PatCredentialChange::Logout).await
}
#[tokio::test]
async fn remote_exec_server_pat_reuses_metadata_during_authapi_outage() -> Result<()> {
assert_pat_registry_reload(PatCredentialChange::Unchanged).await
}
#[tokio::test]
async fn remote_exec_server_pat_recovers_after_replacement_metadata_outage() -> Result<()> {
assert_pat_registry_reload(PatCredentialChange::UnavailableReplacement).await
}
#[tokio::test]
async fn remote_exec_server_pat_recovers_after_replacement_metadata_timeout() -> Result<()> {
assert_pat_registry_reload(PatCredentialChange::SlowReplacement).await
}
#[tokio::test]
async fn remote_exec_server_gracefully_stops_when_parent_stdin_closes() -> Result<()> {
const ENVIRONMENT_ID: &str = "environment-parent-lifetime";
@@ -1121,3 +874,55 @@ async fn wait_for_response(
}
}
}
/// API-key registration authenticates directly and never fetches account-managed
/// cloud configuration before registering.
#[tokio::test]
async fn remote_exec_server_api_key_registers_without_cloud_config() -> Result<()> {
const REGISTER: &str = "/cloud/environment/test/register";
const REGISTRATION_REACHED: &str = "registration reached";
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path(REGISTER))
.and(header("authorization", "Bearer test-api-key"))
.respond_with(ResponseTemplate::new(400).set_body_string(REGISTRATION_REACHED))
.mount(&server)
.await;
let home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
"cli_auth_credentials_store = \"file\"\n",
)?;
let output = tokio::time::timeout(
Duration::from_secs(30),
tokio::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
.kill_on_drop(true)
.current_dir(home.path())
.env("CODEX_HOME", home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("OPENAI_API_KEY")
.env("CODEX_API_KEY", "test-api-key")
.args([
"exec-server",
"--remote",
&server.uri(),
"--environment-id",
"test",
])
.output(),
)
.await??;
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
!output.status.success() && stderr.contains(REGISTRATION_REACHED),
"{stderr}"
);
let requests = server
.received_requests()
.await
.context("mock request log")?;
let paths: Vec<_> = requests.iter().map(|request| request.url.path()).collect();
assert_eq!(paths, vec![REGISTER]);
Ok(())
}

View File

@@ -1,178 +0,0 @@
//! Verify authentication updates across the running CLI executor process.
use std::process::Stdio;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_login::AuthCredentialsStoreMode;
use tempfile::TempDir;
use tokio::net::TcpListener;
use tokio_tungstenite::accept_async;
use tokio_tungstenite::accept_hdr_async;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::path;
#[tokio::test]
async fn executor_startup_rejects_agent_identity_before_cloud_config() -> Result<()> {
let home = TempDir::new()?;
let server = MockServer::start().await;
Mock::given(wiremock::matchers::any())
.respond_with(ResponseTemplate::new(503))
.expect(0)
.mount(&server)
.await;
let manager = codex_login::test_support::auth_manager_with_agent_identity().await?;
let Some(codex_login::CodexAuth::AgentIdentity(agent)) = manager.auth_cached() else {
anyhow::bail!("expected Agent Identity fixture");
};
let mut record = agent.record().clone();
record.task_id = None;
std::fs::write(
home.path().join("auth.json"),
serde_json::to_vec(&serde_json::json!({
"auth_mode": codex_protocol::auth::AuthMode::AgentIdentity,
"agent_identity": record,
}))?,
)?;
std::fs::write(
home.path().join("config.toml"),
"cli_auth_credentials_store = 'file'\n",
)?;
let mut command = tokio::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
command
.current_dir(home.path())
.env("CODEX_HOME", home.path())
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove("CODEX_ACCESS_TOKEN")
.env("CODEX_AGENT_IDENTITY_AUTHAPI_BASE_URL", server.uri())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.args([
"exec-server",
"--remote",
&server.uri(),
"--environment-id",
"env",
])
.kill_on_drop(true);
let output =
tokio::time::timeout(std::time::Duration::from_secs(20), command.output()).await??;
assert!(!output.status.success());
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("requires ChatGPT authentication or API key authentication"),
"{stderr}"
);
server.verify().await;
Ok(())
}
#[tokio::test]
async fn noise_executor_refreshes_on_401_and_reloads_rotated_credentials() -> Result<()> {
let home = TempDir::new()?;
let registry = MockServer::start().await;
let listener = TcpListener::bind("127.0.0.1:0").await?;
std::fs::write(
home.path().join("config.toml"),
"cli_auth_credentials_store = 'file'\n",
)?;
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new("old-token")
.account_id("account")
.chatgpt_user_id("user"),
AuthCredentialsStoreMode::File,
)?;
Mock::given(path("/refresh"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"access_token": "refreshed-token", "refresh_token": "new-refresh-token",
})))
.expect(1)
.mount(&registry)
.await;
Mock::given(path("/cloud/environment/env/register"))
.and(header("authorization", "Bearer old-token"))
.respond_with(ResponseTemplate::new(401))
.expect(1)
.mount(&registry)
.await;
for token in ["refreshed-token", "rotated-token"] {
Mock::given(path("/cloud/environment/env/register"))
.and(header("authorization", format!("Bearer {token}")))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"environment_id": "env", "url": format!("ws://{}", listener.local_addr()?),
"executor_registration_id": "registration", "security_profile": "noise_hybrid_ik_v1",
})))
.with_priority(1)
.up_to_n_times(1)
.expect(1)
.mount(&registry)
.await;
}
// The later registration sees the stored rotation before sending a stale
// request. The initial 401 above still exercises bounded auth recovery.
Mock::given(path("/cloud/environment/env/register"))
.and(header("authorization", "Bearer refreshed-token"))
.respond_with(ResponseTemplate::new(401))
.expect(0)
.mount(&registry)
.await;
let mut child = tokio::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
.current_dir(home.path())
.env("CODEX_HOME", home.path())
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove("CODEX_ACCESS_TOKEN")
.env(
"CODEX_REFRESH_TOKEN_URL_OVERRIDE",
format!("{}/refresh", registry.uri()),
)
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.args([
"exec-server",
"--remote",
&registry.uri(),
"--environment-id",
"env",
"--exit-on-stdin-close",
])
.stdin(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()?;
let stdin = child.stdin.take();
let (socket, _) = listener.accept().await?;
let mut websocket = accept_async(socket).await?;
// Update storage while the executor is alive, then force a new registration.
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new("rotated-token")
.account_id("account")
.chatgpt_user_id("user"),
AuthCredentialsStoreMode::File,
)?;
websocket.close(None).await?;
drop(websocket);
let (socket, _) = listener.accept().await?;
let rejected = accept_hdr_async(socket, |_: &_, _: _| {
Err(http::Response::builder().status(401).body(None).unwrap())
})
.await;
assert!(rejected.is_err());
let (socket, _) = listener.accept().await?;
let _websocket = accept_async(socket).await?;
drop(stdin);
let output = child.wait_with_output().await?;
anyhow::ensure!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
Ok(())
}

View File

@@ -1,23 +1,9 @@
use std::path::Path;
use anyhow::Context;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_config::ConfigLoadOptions;
use codex_config::types::AuthCredentialsStoreMode;
use codex_core::config::load_config_toml_with_layer_stack;
use codex_utils_absolute_path::AbsolutePathBuf;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
@@ -234,101 +220,6 @@ async fn features_list_is_sorted_alphabetically_by_feature_name() -> Result<()>
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn features_list_honors_cloud_managed_feature_requirements() -> Result<()> {
let server = MockServer::start().await;
let chatgpt_base_url = format!("{}/backend-api", server.uri());
let codex_home = TempDir::new()?;
let user_config = format!(
"cli_auth_credentials_store = \"file\"\nchatgpt_base_url = \"{chatgpt_base_url}\"\n\n[features]\nfast_mode = true\nin_app_voice = true\n"
);
std::fs::write(codex_home.path().join("config.toml"), &user_config)?;
let bootstrap_config = load_config_toml_with_layer_stack(
codex_home.path(),
Some(&AbsolutePathBuf::from_absolute_path(codex_home.path())?),
Vec::new(),
ConfigLoadOptions::default(),
)
.await?;
if bootstrap_config.config_toml.cli_auth_credentials_store
!= Some(AuthCredentialsStoreMode::File)
|| bootstrap_config.config_toml.chatgpt_base_url.as_deref()
!= Some(chatgpt_base_url.as_str())
{
eprintln!(
"skipping cloud-managed feature subprocess: host-managed authentication or backend routing prevents isolated mock credentials"
);
return Ok(());
}
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("workspace-123")
.chatgpt_account_id("workspace-123")
.chatgpt_user_id("user-123")
.plan_type("enterprise"),
AuthCredentialsStoreMode::File,
)?;
Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "workspace-123"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"requirements_toml": {
"enterprise_managed": [{
"id": "managed-feature-requirements",
"name": "Managed feature requirements",
"contents": "[features]\nfast_mode = false\nin_app_voice = false\n",
}],
},
})))
.expect(1)
.mount(&server)
.await;
let mut cmd = codex_command(codex_home.path())?;
let output = cmd
.current_dir(codex_home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.args(["features", "list"])
.assert()
.success()
.get_output()
.stdout
.clone();
let stdout = String::from_utf8(output)?;
let fast_mode = stdout
.lines()
.find(|line| line.starts_with("fast_mode "))
.context("feature list should include fast_mode")?;
assert_eq!(
fast_mode.split_whitespace().collect::<Vec<_>>(),
["fast_mode", "stable", "false"]
);
let in_app_voice = stdout
.lines()
.find(|line| line.starts_with("in_app_voice "))
.context("feature list should include in_app_voice")?;
insta::assert_snapshot!(
in_app_voice.split_whitespace().collect::<Vec<_>>().join(" "),
@"in_app_voice stable false"
);
assert_eq!(
std::fs::read_to_string(codex_home.path().join("config.toml"))?,
user_config
);
server.verify().await;
Ok(())
}
#[test]
fn remote_start_rejects_add_dir_before_connecting() -> Result<()> {
let home = TempDir::new()?;

View File

@@ -1,31 +1,14 @@
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use anyhow::Context;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_config::types::AuthCredentialsStoreMode;
use codex_login::AuthKeyringBackendKind;
use codex_login::CLIENT_ID;
use codex_login::CODEX_ACCESS_TOKEN_ENV_VAR;
use codex_login::REVOKE_TOKEN_URL_OVERRIDE_ENV_VAR;
use codex_login::login_with_bedrock_access_keys;
use codex_protocol::shell_environment::OPENAI_FEDERATION_RULE_ID_ENV_VAR;
use codex_protocol::shell_environment::OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
@@ -73,9 +56,6 @@ fn login_with_api_key_reads_stdin_and_writes_auth_json() -> Result<()> {
assert!(auth.get("agent_identity").is_none());
let status = codex_command(codex_home.path())?
.env_remove(CODEX_ACCESS_TOKEN_ENV_VAR)
.env_remove(OPENAI_FEDERATION_RULE_ID_ENV_VAR)
.env_remove(OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR)
.args(["login", "status"])
.assert()
.success();
@@ -84,13 +64,19 @@ fn login_with_api_key_reads_stdin_and_writes_auth_json() -> Result<()> {
Authentication is checked when you send a request.
");
for args in [vec!["login"], vec!["login", "--device-auth"]] {
codex_command(codex_home.path())?
.args(["-c", "forced_login_method=\"api\"", "login"])
.assert()
.failure()
.stderr(contains("Only API key login is supported"));
assert_eq!(read_auth_json(codex_home.path())?, auth);
for removed_flag in ["--device-auth", "--with-access-token"] {
codex_command(codex_home.path())?
.args(["-c", "forced_login_method=\"api\""])
.args(args)
.args(["login", removed_flag])
.write_stdin("token\n")
.assert()
.failure()
.stderr(contains("ChatGPT login is disabled"));
.stderr(contains("unexpected argument"));
assert_eq!(read_auth_json(codex_home.path())?, auth);
}
@@ -150,29 +136,35 @@ fn login_status_reports_auth_storage_errors() -> Result<()> {
}
#[test]
fn login_status_validates_configured_workload_identity() -> Result<()> {
fn legacy_chatgpt_auth_is_reported_as_not_logged_in_and_logout_removes_it() -> Result<()> {
let codex_home = TempDir::new()?;
write_file_auth_config(codex_home.path())?;
let missing_assertion = codex_home.path().join("missing-identity-token");
std::fs::write(
codex_home.path().join("auth.json"),
serde_json::to_vec(&json!({
"auth_mode": "chatgpt",
"OPENAI_API_KEY": null,
"tokens": {
"id_token": "eyJhbGciOiJub25lIn0.e30.c2ln",
"access_token": "old-access",
"refresh_token": "old-refresh",
},
}))?,
)?;
for login_method in ["chatgpt", "api"] {
let mut command = codex_command(codex_home.path())?;
command
.env_remove(CODEX_ACCESS_TOKEN_ENV_VAR)
.env(OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR, &missing_assertion)
.env(OPENAI_FEDERATION_RULE_ID_ENV_VAR, "rule-test")
.args([
"-c",
&format!("forced_login_method=\"{login_method}\""),
"login",
"status",
]);
command
.assert()
.failure()
.stderr(contains("could not read workload identity assertion file"));
}
codex_command(codex_home.path())?
.env_remove("CODEX_API_KEY")
.args(["login", "status"])
.assert()
.failure()
.stderr(contains("Not logged in"));
codex_command(codex_home.path())?
.arg("logout")
.assert()
.success()
.stderr(contains("Successfully logged out"));
assert!(!codex_home.path().join("auth.json").exists());
Ok(())
}
@@ -239,7 +231,6 @@ fn logout_clears_only_the_selected_bedrock_provider() -> Result<()> {
};
codex_command(codex_home.path())?
.env_remove(CODEX_ACCESS_TOKEN_ENV_VAR)
.env("AWS_ACCESS_KEY_ID", "environment-access-key-id")
.env("AWS_SECRET_ACCESS_KEY", "environment-secret-access-key")
.args(["logout"])
@@ -254,242 +245,3 @@ fn logout_clears_only_the_selected_bedrock_provider() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn logout_survives_enterprise_cleanup_failure_with_xaa_disabled() -> Result<()> {
let server = MockServer::start().await;
Mock::given(path("/backend-api/wham/config/bundle"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"config_toml": {"enterprise_managed": []},
"requirements_toml": {"enterprise_managed": []},
})))
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/oauth/revoke"))
.respond_with(ResponseTemplate::new(200))
.expect(1)
.mount(&server)
.await;
let home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
format!(
"cli_auth_credentials_store = \"file\"\nchatgpt_base_url = \"{}/backend-api\"\n[features]\nuse_xaa = false\n[mcp_enterprise_managed_auth.idp]\nissuer = \"https://idp.example\"\nclient_id = \"enterprise-client\"\n[mcp_servers.enterprise]\nurl = \"https://resource.example/mcp\"\nauth = \"ema_auth\"\nbearer_token_env_var = \"UNUSED_TOKEN\"\n",
server.uri()
),
)?;
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new("account-access")
.account_id("workspace")
.chatgpt_user_id("user"),
AuthCredentialsStoreMode::File,
)?;
// Fail before touching the real keyring; the subprocess owns this isolated home.
std::fs::write(home.path().join("mcp-oauth-locks"), "not a directory")?;
for enabled in [false, true] {
codex_command(home.path())?
.current_dir(home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove(CODEX_ACCESS_TOKEN_ENV_VAR)
.args([
"-c",
&format!("features.use_xaa={enabled}"),
"mcp",
"logout",
"enterprise",
])
.assert()
.failure()
.stderr(contains("failed to delete enterprise authorization"));
assert!(home.path().join("auth.json").exists());
}
codex_command(home.path())?
.current_dir(home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env(
REVOKE_TOKEN_URL_OVERRIDE_ENV_VAR,
format!("{}/oauth/revoke", server.uri()),
)
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove(CODEX_ACCESS_TOKEN_ENV_VAR)
.args(["logout"])
.assert()
.success()
.stderr(contains("continuing account logout"))
.stderr(contains("Successfully logged out"));
assert!(!home.path().join("auth.json").exists());
Ok(())
}
#[test]
fn login_with_access_token_rejects_invalid_jwt() -> Result<()> {
let codex_home = TempDir::new()?;
write_file_auth_config(codex_home.path())?;
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["login", "--with-access-token"])
.write_stdin("not-a-jwt\n")
.assert()
.failure()
.stderr(contains("Error logging in with access token"));
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn debug_prompt_input_follows_authenticated_attribution_setting() -> Result<()> {
let server = MockServer::start().await;
let request_count = Arc::new(AtomicUsize::new(0));
Mock::given(method("GET"))
.and(path("/backend-api/wham/settings/user"))
.and(header("chatgpt-account-id", "workspace-123"))
.respond_with(move |_request: &wiremock::Request| {
ResponseTemplate::new(200).set_body_json(json!({
"commit_attribution_enabled": request_count.fetch_add(1, Ordering::SeqCst) == 0,
}))
})
.expect(2)
.mount(&server)
.await;
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
format!(
"cli_auth_credentials_store = \"file\"\nchatgpt_base_url = \"{}/backend-api\"\n",
server.uri()
),
)?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("workspace-123")
.plan_type("enterprise"),
AuthCredentialsStoreMode::File,
)?;
for enabled in [true, false] {
let output = codex_command(codex_home.path())?
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("OPENAI_API_KEY")
.args(["debug", "prompt-input"])
.output()?;
assert!(output.status.success());
let prompt = String::from_utf8(output.stdout)?;
assert_eq!(
prompt.contains("Co-authored-by: Codex <noreply@openai.com>"),
enabled
);
assert!(!prompt.contains("attribution is disabled for the current workspace"));
}
server.verify().await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn device_login_revokes_existing_auth_before_requesting_new_tokens() -> Result<()> {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/oauth/revoke"))
.respond_with(ResponseTemplate::new(200))
.expect(1)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/api/accounts/deviceauth/usercode"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"device_auth_id": "device-auth-123",
"user_code": "CODE-12345",
"interval": "0",
})))
.expect(1)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/api/accounts/deviceauth/token"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"authorization_code": "authorization-code-123",
"code_challenge": "code-challenge-123",
"code_verifier": "code-verifier-123",
})))
.expect(1)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/oauth/token"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"id_token": "eyJhbGciOiJub25lIn0.e30.c2ln",
"access_token": "new-access",
"refresh_token": "new-refresh",
})))
.expect(1)
.mount(&server)
.await;
let codex_home = TempDir::new()?;
write_file_auth_config(codex_home.path())?;
std::fs::write(
codex_home.path().join("auth.json"),
serde_json::to_vec(&json!({
"auth_mode": "chatgpt",
"OPENAI_API_KEY": null,
"tokens": {
"id_token": "eyJhbGciOiJub25lIn0.e30.c2ln",
"access_token": "old-access",
"refresh_token": "old-refresh",
"account_id": "old-account",
},
}))?,
)?;
let issuer = server.uri();
let mut cmd = codex_command(codex_home.path())?;
cmd.env(
REVOKE_TOKEN_URL_OVERRIDE_ENV_VAR,
format!("{issuer}/oauth/revoke"),
)
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("OPENAI_API_KEY")
.args(["login", "--device-auth", "--experimental_issuer", &issuer])
.assert()
.success()
.stderr(contains("Successfully logged in"));
let requests = server
.received_requests()
.await
.context("failed to read mock OAuth requests")?;
let paths: Vec<&str> = requests.iter().map(|request| request.url.path()).collect();
assert_eq!(
paths,
vec![
"/oauth/revoke",
"/api/accounts/deviceauth/usercode",
"/api/accounts/deviceauth/token",
"/oauth/token",
]
);
assert_eq!(
requests[0]
.body_json::<Value>()
.context("revoke request should be JSON")?,
json!({
"token": "old-refresh",
"token_type_hint": "refresh_token",
"client_id": CLIENT_ID,
})
);
let auth = read_auth_json(codex_home.path())?;
assert_eq!(auth["tokens"]["refresh_token"], "new-refresh");
Ok(())
}

View File

@@ -1,36 +1,18 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_config::CONFIG_TOML_FILE;
use codex_config::MarketplaceConfigUpdate;
use codex_config::record_user_marketplace;
use codex_config::types::AuthCredentialsStoreMode;
use codex_utils_absolute_path::canonicalize_existing_preserving_symlinks;
use flate2::Compression;
use flate2::write::GzEncoder;
use predicates::prelude::PredicateBooleanExt;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::path::Path;
use std::process::Output;
use std::process::Stdio;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use tempfile::TempDir;
use tokio::io::AsyncReadExt;
use tokio::process::Command;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::query_param;
const MARKETPLACE_HEADER: &str = "MARKETPLACE";
const MARKETPLACE_LIST_HEADER: &str = "MARKETPLACE ROOT";
@@ -1186,753 +1168,3 @@ async fn plugin_add_rejects_cached_plugins_without_authorizing_marketplace_snaps
Ok(())
}
const REMOTE_ID: &str = "b1234567-89ab-4cde-8f01-234567890abc";
const MARKETPLACE: &str = "openai-curated-remote";
const PLUGIN_KEY: &str = "sample@openai-curated-remote";
fn sample_remote_plugin_bundle() -> Result<Vec<u8>> {
let mut archive = tar::Builder::new(GzEncoder::new(Vec::new(), Compression::default()));
for (path, contents) in [
(
".codex-plugin/plugin.json",
r#"{"name":"sample","version":"1.2.3"}"#,
),
(
"skills/sample/SKILL.md",
"---\nname: sample\ndescription: Sample remote skill\n---\nSample instructions.\n",
),
] {
let mut header = tar::Header::new_gnu();
header.set_size(contents.len() as u64);
header.set_mode(/*mode*/ 0o644);
header.set_cksum();
archive.append_data(&mut header, path, contents.as_bytes())?;
}
Ok(archive.into_inner()?.finish()?)
}
struct RemoteMarketplaceFixture {
home: TempDir,
server: MockServer,
plugin: Value,
}
impl RemoteMarketplaceFixture {
async fn new() -> Result<Self> {
let home = TempDir::new()?;
let server = MockServer::start().await;
std::fs::write(
home.path().join("config.toml"),
format!(
"cli_auth_credentials_store = 'file'\nchatgpt_base_url = '{}/backend-api'\n[features]\nplugins = true\nremote_plugin = true\n",
server.uri()
),
)?;
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.chatgpt_account_id("account-123"),
AuthCredentialsStoreMode::File,
)?;
let plugin = json!({
"id": REMOTE_ID, "name": "sample", "scope": "GLOBAL",
"installation_policy": "AVAILABLE", "authentication_policy": "ON_USE",
"release": {"version": "1.2.3", "display_name": "Sample", "description": "Remote sample",
"interface": {}, "bundle_download_url": format!("{}/bundle.tar.gz", server.uri())}
});
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/list"))
.and(query_param("scope", "GLOBAL"))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "account-123"))
.respond_with(ResponseTemplate::new(200).set_body_json(
json!({"plugins": [plugin.clone()], "pagination": {"next_page_token": null}}),
))
.mount(&server)
.await;
Ok(Self {
home,
server,
plugin,
})
}
fn write_local_curated_marketplace(&self) -> Result<Value> {
let source = canonicalize_existing_preserving_symlinks(self.home.path())?
.join(".tmp")
.join("plugins");
let mut manifest = json!({
"name": "openai-curated",
"plugins": [{
"name": "sample",
"source": {"source": "local", "path": "./plugins/sample"}
}]
});
write_marketplace_source_with_manifest(&source, &manifest.to_string())?;
std::fs::write(
self.home.path().join(".tmp").join("plugins.sha"),
"local-curated",
)?;
manifest["name"] = json!("openai-api-curated");
std::fs::write(
source
.join(".agents")
.join("plugins")
.join("api_marketplace.json"),
manifest.to_string(),
)?;
Ok(json!({
"pluginId": "sample@openai-curated", "name": "sample",
"marketplaceName": "openai-curated", "version": "1.2.3",
"installed": false, "enabled": false,
"source": {"source": "local", "path": source.join("plugins").join("sample")},
"installPolicy": "AVAILABLE", "authPolicy": "ON_INSTALL"
}))
}
async fn run(&self, args: &[&str]) -> Result<Output> {
Ok(Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
.current_dir(self.home.path())
.env("CODEX_HOME", self.home.path())
.env("HOME", self.home.path())
.env_remove("OPENAI_API_KEY")
.env_remove("CODEX_API_KEY")
.env_remove("CODEX_ACCESS_TOKEN")
.env("CODEX_TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS", "1")
.args(args)
.output()
.await?)
}
async fn success(&self, args: &[&str]) -> Result<String> {
let output = self.run(args).await?;
ensure!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
Ok(String::from_utf8(output.stdout)?)
}
}
#[tokio::test]
async fn remote_plugin_listing_replaces_local_curated_catalog() -> Result<()> {
let fixture = RemoteMarketplaceFixture::new().await?;
let mut local_plugin = fixture.write_local_curated_marketplace()?;
fixture
.success(&["plugin", "add", "sample@openai-curated"])
.await?;
local_plugin["installed"] = json!(true);
local_plugin["enabled"] = json!(true);
local_plugin["version"] = json!("local-curated");
let mut installed_plugin = fixture.plugin.clone();
installed_plugin["enabled"] = json!(true);
Mock::given(path("/backend-api/ps/plugins/installed"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [installed_plugin], "pagination": {"next_page_token": null}
})))
.mount(&fixture.server)
.await;
let listed = fixture
.success(&["plugin", "list", "--available", "--json"])
.await?;
assert_eq!(
serde_json::from_str::<Value>(&listed)?,
json!({"installed": [{
"pluginId": PLUGIN_KEY, "name": "sample", "marketplaceName": MARKETPLACE,
"version": "1.2.3", "installed": true, "enabled": true,
"source": {"source": "remote", "id": REMOTE_ID},
"installPolicy": "AVAILABLE", "authPolicy": "ON_USE"
}], "available": []})
);
let table = fixture.success(&["plugin", "list"]).await?;
insta::assert_snapshot!(table, @r"
Marketplace `openai-curated-remote`
Remote catalog
PLUGIN STATUS VERSION SOURCE
sample@openai-curated-remote installed, enabled 1.2.3 b1234567-89ab-4cde-8f01-234567890abc
");
fixture.server.reset().await;
let listed = fixture
.success(&["plugin", "list", "-m", "openai-curated", "--json"])
.await?;
assert_eq!(
serde_json::from_str::<Value>(&listed)?,
json!({"installed": [local_plugin], "available": []})
);
assert!(fixture.server.received_requests().await.unwrap().is_empty());
Ok(())
}
#[tokio::test]
async fn remote_plugin_listing_preserves_local_curated_only_when_fetch_fails() -> Result<()> {
for status in [200, 403] {
let fixture = RemoteMarketplaceFixture::new().await?;
fixture.server.reset().await;
let local_plugin = fixture.write_local_curated_marketplace()?;
let response = ResponseTemplate::new(status).set_body_json(json!({
"plugins": [], "pagination": {"next_page_token": null}
}));
let _catalog = Mock::given(path("/backend-api/ps/plugins/list"))
.respond_with(response)
.mount_as_scoped(&fixture.server)
.await;
Mock::given(path("/backend-api/ps/plugins/installed"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [], "pagination": {"next_page_token": null}
})))
.mount(&fixture.server)
.await;
let listed = fixture
.success(&["plugin", "list", "--available", "--json"])
.await?;
let available = if status == 200 {
Vec::new()
} else {
vec![local_plugin]
};
assert_eq!(
serde_json::from_str::<Value>(&listed)?,
json!({"installed": [], "available": available}),
"catalog response status: {status}"
);
}
Ok(())
}
#[tokio::test]
async fn remote_plugin_add_list_and_remove() -> Result<()> {
let fixture = RemoteMarketplaceFixture::new().await?;
let installed = Arc::new(AtomicBool::new(false));
let installed_for_list = Arc::clone(&installed);
let mut installed_plugin = fixture.plugin.clone();
installed_plugin["enabled"] = json!(true);
Mock::given(path("/backend-api/ps/plugins/installed"))
.respond_with(move |_: &wiremock::Request| {
let plugins = if installed_for_list.load(Ordering::SeqCst) {
vec![installed_plugin.clone()]
} else {
Vec::new()
};
ResponseTemplate::new(200)
.set_body_json(json!({"plugins": plugins, "pagination": {"next_page_token": null}}))
})
.mount(&fixture.server)
.await;
Mock::given(path(format!("/backend-api/ps/plugins/{REMOTE_ID}")))
.respond_with(ResponseTemplate::new(200).set_body_json(&fixture.plugin))
.mount(&fixture.server)
.await;
Mock::given(path("/bundle.tar.gz"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(sample_remote_plugin_bundle()?))
.expect(1)
.mount(&fixture.server)
.await;
let installed_root = canonicalize_existing_preserving_symlinks(fixture.home.path())?
.join("plugins")
.join("cache")
.join(MARKETPLACE)
.join("sample")
.join("1.2.3");
let manifest = installed_root.join(".codex-plugin/plugin.json");
let installed_for_add = Arc::clone(&installed);
Mock::given(method("POST"))
.and(path(format!("/backend-api/ps/plugins/{REMOTE_ID}/install")))
.and(query_param("includeAppsNeedingAuth", "true"))
.and(header("authorization", "Bearer chatgpt-token"))
.respond_with(move |_: &wiremock::Request| {
assert!(
manifest.is_file(),
"cache must exist before backend install"
);
installed_for_add.store(true, Ordering::SeqCst);
ResponseTemplate::new(200).set_body_json(json!({"id": REMOTE_ID, "enabled": true}))
})
.expect(1)
.mount(&fixture.server)
.await;
Mock::given(method("POST"))
.and(path(format!(
"/backend-api/ps/plugins/{REMOTE_ID}/uninstall"
)))
.and(header("authorization", "Bearer chatgpt-token"))
.respond_with(move |_: &wiremock::Request| {
installed.store(false, Ordering::SeqCst);
ResponseTemplate::new(200).set_body_json(json!({"id": REMOTE_ID, "enabled": false}))
})
.expect(1)
.mount(&fixture.server)
.await;
let available = json!({
"pluginId": PLUGIN_KEY, "name": "sample", "marketplaceName": MARKETPLACE,
"version": "1.2.3", "installed": false, "enabled": false,
"source": {"source": "remote", "id": REMOTE_ID}, "installPolicy": "AVAILABLE", "authPolicy": "ON_USE"
});
let listed = fixture
.success(&["plugin", "list", "--available", "--json"])
.await?;
assert_eq!(
serde_json::from_str::<Value>(&listed)?,
json!({"installed": [], "available": [available.clone()]})
);
let table = fixture
.success(&["plugin", "list", "-m", MARKETPLACE])
.await?;
insta::assert_snapshot!(table, @r"
Marketplace `openai-curated-remote`
Remote catalog
PLUGIN STATUS VERSION SOURCE
sample@openai-curated-remote not installed 1.2.3 b1234567-89ab-4cde-8f01-234567890abc
");
let added = fixture
.success(&["plugin", "add", PLUGIN_KEY, "--json"])
.await?;
assert_eq!(
serde_json::from_str::<Value>(&added)?,
json!({
"pluginId": PLUGIN_KEY, "name": "sample", "marketplaceName": MARKETPLACE,
"version": "1.2.3", "installedPath": installed_root, "authPolicy": "ON_USE"
})
);
assert_eq!(
fixture
.server
.received_requests()
.await
.unwrap()
.iter()
.filter(|request| request.url.path() == "/backend-api/ps/plugins/list")
.count(),
1,
"installing a cached name must not refetch the catalog"
);
assert!(installed_root.join("skills/sample/SKILL.md").is_file());
let mut expected = available;
expected["installed"] = json!(true);
expected["enabled"] = json!(true);
let listed = fixture
.success(&["plugin", "list", "-m", MARKETPLACE, "--json"])
.await?;
assert_eq!(
serde_json::from_str::<Value>(&listed)?,
json!({"installed": [expected], "available": []})
);
let _delisted = Mock::given(path("/backend-api/ps/plugins/list"))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(json!({"plugins": [], "pagination": {"next_page_token": null}})),
)
.mount_as_scoped(&fixture.server)
.await;
let removed = fixture
.success(&[
"-c",
"features.remote_plugin=false",
"plugin",
"remove",
"sample",
"-m",
MARKETPLACE,
"--json",
])
.await?;
assert_eq!(
serde_json::from_str::<Value>(&removed)?,
json!({"pluginId": PLUGIN_KEY, "name": "sample", "marketplaceName": MARKETPLACE})
);
assert!(!installed_root.exists());
let listed = fixture.success(&["plugin", "list", "--json"]).await?;
assert_eq!(
serde_json::from_str::<Value>(&listed)?,
json!({"installed": [], "available": []})
);
Ok(())
}
#[tokio::test]
async fn remote_plugin_add_refreshes_cached_catalog_on_name_miss() -> Result<()> {
for (remote_plugin_config, collection) in [
("features.remote_plugin=true", None),
("features.remote_plugin=false", Some("vertical")),
] {
let fixture = RemoteMarketplaceFixture::new().await?;
fixture.server.reset().await;
let published = Arc::new(AtomicBool::new(false));
let published_for_list = Arc::clone(&published);
let plugin = fixture.plugin.clone();
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/list"))
.and(query_param("scope", "GLOBAL"))
.respond_with(move |_: &wiremock::Request| {
let plugins = if published_for_list.load(Ordering::SeqCst) {
vec![plugin.clone()]
} else {
Vec::new()
};
ResponseTemplate::new(200).set_body_json(json!({
"plugins": plugins, "pagination": {"next_page_token": null}
}))
})
.expect(2)
.mount(&fixture.server)
.await;
Mock::given(path("/backend-api/ps/plugins/installed"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [], "pagination": {"next_page_token": null}
})))
.mount(&fixture.server)
.await;
Mock::given(path(format!("/backend-api/ps/plugins/{REMOTE_ID}")))
.respond_with(ResponseTemplate::new(200).set_body_json(&fixture.plugin))
.expect(1)
.mount(&fixture.server)
.await;
Mock::given(path("/bundle.tar.gz"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(sample_remote_plugin_bundle()?))
.expect(1)
.mount(&fixture.server)
.await;
Mock::given(method("POST"))
.and(path(format!("/backend-api/ps/plugins/{REMOTE_ID}/install")))
.respond_with(
ResponseTemplate::new(200).set_body_json(json!({"id": REMOTE_ID, "enabled": true})),
)
.expect(1)
.mount(&fixture.server)
.await;
for is_published in [false, true] {
published.store(is_published, Ordering::SeqCst);
let listed = fixture
.success(&[
"-c",
remote_plugin_config,
"plugin",
"list",
"-m",
MARKETPLACE,
"--available",
"--json",
])
.await?;
assert_eq!(
serde_json::from_str::<Value>(&listed)?,
json!({"installed": [], "available": []}),
"normal listing must keep using the fresh catalog cache"
);
}
let added = fixture
.success(&[
"-c",
remote_plugin_config,
"plugin",
"add",
PLUGIN_KEY,
"--json",
])
.await?;
let installed_root = canonicalize_existing_preserving_symlinks(fixture.home.path())?
.join("plugins")
.join("cache")
.join(MARKETPLACE)
.join("sample")
.join("1.2.3");
assert_eq!(
serde_json::from_str::<Value>(&added)?,
json!({
"pluginId": PLUGIN_KEY, "name": "sample", "marketplaceName": MARKETPLACE,
"version": "1.2.3", "installedPath": installed_root, "authPolicy": "ON_USE"
})
);
assert!(
installed_root
.join("skills")
.join("sample")
.join("SKILL.md")
.is_file()
);
let requests = fixture.server.received_requests().await.unwrap();
let catalog_collections = requests
.iter()
.filter(|request| request.url.path() == "/backend-api/ps/plugins/list")
.map(|request| {
request
.url
.query_pairs()
.find_map(|(key, value)| (key == "collection").then(|| value.into_owned()))
})
.collect::<Vec<_>>();
assert_eq!(catalog_collections, vec![collection.map(str::to_owned); 2]);
}
Ok(())
}
#[tokio::test]
async fn remote_plugin_add_limits_catalog_refresh_without_mutation() -> Result<()> {
enum CatalogCache {
Missing,
Fresh,
Expired,
}
for (remote_plugin_config, collection) in [
("features.remote_plugin=true", None),
("features.remote_plugin=false", Some("vertical")),
] {
for (cache, plugin_count, status, catalog_fetches, error) in [
(
CatalogCache::Missing,
0,
200,
1,
"was not found in remote marketplace",
),
(
CatalogCache::Fresh,
0,
200,
2,
"was not found in remote marketplace",
),
(
CatalogCache::Expired,
0,
200,
2,
"was not found in remote marketplace",
),
(
CatalogCache::Missing,
2,
200,
1,
"matched multiple remote plugins",
),
(
CatalogCache::Missing,
0,
403,
1,
"failed to list remote marketplace plugins",
),
] {
let fixture = RemoteMarketplaceFixture::new().await?;
fixture.server.reset().await;
let mut duplicate = fixture.plugin.clone();
duplicate["id"] = json!("c1234567-89ab-4cde-8f01-234567890abc");
let plugins = [fixture.plugin.clone(), duplicate]
.into_iter()
.take(plugin_count)
.collect::<Vec<_>>();
Mock::given(path("/backend-api/ps/plugins/list"))
.and(query_param("scope", "GLOBAL"))
.respond_with(ResponseTemplate::new(status).set_body_json(json!({
"plugins": plugins, "pagination": {"next_page_token": null}
})))
.expect(catalog_fetches)
.mount(&fixture.server)
.await;
Mock::given(path("/backend-api/ps/plugins/installed"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [], "pagination": {"next_page_token": null}
})))
.mount(&fixture.server)
.await;
if !matches!(cache, CatalogCache::Missing) {
let listed = fixture
.success(&[
"-c",
remote_plugin_config,
"plugin",
"list",
"-m",
MARKETPLACE,
"--available",
"--json",
])
.await?;
assert_eq!(
serde_json::from_str::<Value>(&listed)?,
json!({"installed": [], "available": []})
);
}
if matches!(cache, CatalogCache::Expired) {
let cache_paths = std::fs::read_dir(
fixture
.home
.path()
.join("cache")
.join("remote_plugin_catalog"),
)?
.map(|entry| entry.map(|entry| entry.path()))
.collect::<std::io::Result<Vec<_>>>()?;
assert_eq!(cache_paths.len(), 1);
let cache_path = &cache_paths[0];
let mut cached_catalog: Value =
serde_json::from_slice(&std::fs::read(cache_path)?)?;
cached_catalog["fetched_at"] = json!("2000-01-01T00:00:00Z");
std::fs::write(cache_path, serde_json::to_vec(&cached_catalog)?)?;
}
let output = fixture
.run(&["-c", remote_plugin_config, "plugin", "add", PLUGIN_KEY])
.await?;
assert!(!output.status.success());
let stderr = String::from_utf8(output.stderr)?;
assert!(stderr.contains(error), "{stderr}");
let requests = fixture.server.received_requests().await.unwrap();
let catalog_collections = requests
.iter()
.filter(|request| request.url.path() == "/backend-api/ps/plugins/list")
.map(|request| {
request
.url
.query_pairs()
.find_map(|(key, value)| (key == "collection").then(|| value.into_owned()))
})
.collect::<Vec<_>>();
assert_eq!(
catalog_collections,
vec![collection.map(str::to_owned); catalog_fetches as usize]
);
assert!(requests.iter().all(|request| {
request.method == "GET"
&& matches!(
request.url.path(),
"/backend-api/ps/plugins/list" | "/backend-api/ps/plugins/installed"
)
}));
assert!(
!fixture
.home
.path()
.join("plugins")
.join("cache")
.join(MARKETPLACE)
.exists()
);
}
}
Ok(())
}
#[tokio::test]
async fn remote_plugin_install_checks_policy_and_bundle_before_mutation() -> Result<()> {
let fixture = RemoteMarketplaceFixture::new().await?;
Mock::given(path("/backend-api/ps/plugins/installed"))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(json!({"plugins": [], "pagination": {"next_page_token": null}})),
)
.mount(&fixture.server)
.await;
for (field, value, error) in [
("status", "DISABLED_BY_ADMIN", "disabled by admin"),
(
"installation_policy",
"NOT_AVAILABLE",
"not available for install",
),
("status", "ENABLED", "failed to read plugin bundle tar"),
] {
let mut plugin = fixture.plugin.clone();
plugin[field] = json!(value);
let _detail = Mock::given(path(format!("/backend-api/ps/plugins/{REMOTE_ID}")))
.respond_with(ResponseTemplate::new(200).set_body_json(plugin))
.mount_as_scoped(&fixture.server)
.await;
let _bundle = Mock::given(path("/bundle.tar.gz"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"bad gzip"))
.mount_as_scoped(&fixture.server)
.await;
let output = fixture
.run(&["plugin", "add", "sample", "-m", MARKETPLACE])
.await?;
assert!(!output.status.success());
let stderr = String::from_utf8(output.stderr)?;
assert!(stderr.contains(error), "{stderr}");
}
let requests = fixture.server.received_requests().await.unwrap();
assert!(requests.iter().all(|request| request.method != "POST"));
assert_eq!(
requests
.iter()
.filter(|request| request.url.path() == "/backend-api/ps/plugins/list")
.count(),
1,
"installation policy and bundle failures must not refetch the catalog"
);
Ok(())
}
#[tokio::test]
async fn remote_plugin_listing_uses_collection_when_remote_catalog_is_disabled() -> Result<()> {
let fixture = RemoteMarketplaceFixture::new().await?;
let mut local_plugin = fixture.write_local_curated_marketplace()?;
Mock::given(path("/backend-api/ps/plugins/installed"))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(json!({"plugins": [], "pagination": {"next_page_token": null}})),
)
.mount(&fixture.server)
.await;
let listed = fixture
.success(&[
"-c",
"features.remote_plugin=false",
"plugin",
"list",
"--available",
"--json",
])
.await?;
assert_eq!(
serde_json::from_str::<Value>(&listed)?,
json!({"installed": [], "available": [local_plugin.clone(), {
"pluginId": PLUGIN_KEY, "name": "sample", "marketplaceName": MARKETPLACE,
"version": "1.2.3", "installed": false, "enabled": false,
"source": {"source": "remote", "id": REMOTE_ID},
"installPolicy": "AVAILABLE", "authPolicy": "ON_USE"
}]})
);
let requests = fixture.server.received_requests().await.unwrap();
let listing = requests
.iter()
.find(|request| request.url.path().ends_with("/list"))
.unwrap();
assert!(
listing
.url
.query_pairs()
.any(|(key, value)| key == "collection" && value == "vertical")
);
fixture.server.reset().await;
fixture
.success(&["-c", "features.plugins=false", "plugin", "list"])
.await?;
fixture
.success(&["plugin", "list", "-m", "local-only"])
.await?;
assert!(fixture.server.received_requests().await.unwrap().is_empty());
std::fs::remove_file(fixture.home.path().join("auth.json"))?;
let output = fixture.run(&["plugin", "list", "-m", MARKETPLACE]).await?;
assert!(!output.status.success());
assert!(String::from_utf8(output.stderr)?.contains("chatgpt authentication required"));
let listed = fixture
.success(&["plugin", "list", "--available", "--json"])
.await?;
local_plugin["pluginId"] = json!("sample@openai-api-curated");
local_plugin["marketplaceName"] = json!("openai-api-curated");
assert_eq!(
serde_json::from_str::<Value>(&listed)?,
json!({"installed": [], "available": [local_plugin]})
);
Ok(())
}

View File

@@ -1,184 +0,0 @@
use std::process::Command;
use anyhow::Context;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_config::ConfigLoadOptions;
use codex_config::types::AuthCredentialsStoreMode;
use codex_core::config::load_config_toml_with_layer_stack;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
const CLOUD_MANAGED_PERMISSION_PROFILE_REQUIREMENTS: &str = r#"
default_permissions = "managed-cloud"
[allowed_permission_profiles]
managed-cloud = true
[permissions.managed-cloud]
extends = ":workspace"
[permissions.managed-cloud.network]
enabled = true
"#;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn sandbox_fetches_and_enforces_cloud_managed_permission_profile() -> Result<()> {
let requirements = json!({"enterprise_managed": [{
"id": "req-managed-cloud", "name": "Managed permissions",
"contents": CLOUD_MANAGED_PERMISSION_PROFILE_REQUIREMENTS,
}]});
let Some(codex_home) = run_cloud_sandbox(
&["-P", "managed-cloud", "--include-managed-config"],
json!({"requirements_toml": requirements}),
)
.await?
else {
return Ok(());
};
let cache: Value = serde_json::from_slice(&std::fs::read(
codex_home.path().join("cloud-config-bundle-cache.json"),
)?)?;
let payload = &cache["signed_payload"];
assert_eq!(payload["chatgpt_user_id"], "user-123");
assert_eq!(payload["account_id"], "workspace-123");
assert_eq!(payload["bundle"]["requirements_toml"], requirements);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn sandbox_loads_cloud_provider_for_cua_style_invocation() -> Result<()> {
run_cloud_sandbox(
&[
"-c",
"model_provider='cloud-provider'",
"-c",
"default_permissions='cua'",
"-c",
"permissions.cua={extends=':workspace',network={enabled=true}}",
"-c",
"approval_policy='never'",
],
json!({"config_toml": {"enterprise_managed": [{
"id": "cloud-provider", "name": "Cloud provider",
"contents": "[model_providers.cloud-provider]\nname = 'Cloud provider'\nwire_api = 'responses'",
}]}}),
)
.await?;
Ok(())
}
async fn run_cloud_sandbox(args: &[&str], bundle: Value) -> Result<Option<TempDir>> {
let server = MockServer::start().await;
let chatgpt_base_url = format!("{}/backend-api", server.uri());
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
format!(
"cli_auth_credentials_store = \"file\"\nchatgpt_base_url = \"{chatgpt_base_url}\"\n",
),
)?;
let bootstrap_config = load_config_toml_with_layer_stack(
codex_home.path(),
Some(&AbsolutePathBuf::from_absolute_path(codex_home.path())?),
vec![
(
"cli_auth_credentials_store".to_string(),
toml::Value::String("file".to_string()),
),
(
"chatgpt_base_url".to_string(),
toml::Value::String(chatgpt_base_url.clone()),
),
],
ConfigLoadOptions::default(),
)
.await?;
if bootstrap_config.config_toml.cli_auth_credentials_store
!= Some(AuthCredentialsStoreMode::File)
|| bootstrap_config.config_toml.chatgpt_base_url.as_deref()
!= Some(chatgpt_base_url.as_str())
{
eprintln!(
"skipping cloud-managed sandbox subprocess: host-managed authentication or backend routing prevents isolated mock credentials"
);
return Ok(None);
}
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("workspace-123")
.chatgpt_account_id("workspace-123")
.chatgpt_user_id("user-123")
.plan_type("enterprise"),
AuthCredentialsStoreMode::File,
)?;
Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "workspace-123"))
.respond_with(ResponseTemplate::new(200).set_body_json(bundle))
.expect(1)
.mount(&server)
.await;
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
let chatgpt_base_url_override = format!("chatgpt_base_url=\"{chatgpt_base_url}\"");
let output = Command::new(&codex)
.current_dir(codex_home.path())
.env("CODEX_HOME", codex_home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("OPENAI_API_KEY")
.env_remove("OPENAI_FEDERATION_RULE_ID")
.env_remove("OPENAI_IDENTITY_TOKEN_FILE")
.env_remove("OPENAI_WORKLOAD_IDENTITY_CONTEXT")
.args(["-c", "cli_auth_credentials_store=\"file\""])
.args(["-c", chatgpt_base_url_override.as_str()])
.arg("sandbox")
.args(args)
.arg("--")
.arg(&codex)
.arg("--version")
.output()?;
let cloud_bundle_request_paths: Vec<_> = server
.received_requests()
.await
.context("failed to read mock cloud configuration requests")?
.into_iter()
.map(|request| request.url.path().to_string())
.collect();
let stderr = String::from_utf8_lossy(&output.stderr);
let nested_macos_sandbox_unavailable = cfg!(target_os = "macos")
&& output.status.code() == Some(71)
&& stderr.contains("sandbox-exec: sandbox_apply: Operation not permitted");
assert!(
output.status.success() || nested_macos_sandbox_unavailable,
"cloud-managed sandbox profile was not enforced: status={:?}; stdout={}; stderr={}; cloud bundle requests={cloud_bundle_request_paths:?}",
output.status.code(),
String::from_utf8_lossy(&output.stdout),
stderr,
);
if !nested_macos_sandbox_unavailable {
assert!(
String::from_utf8(output.stdout)?.starts_with("codex"),
"expected the sandboxed Codex version command to run",
);
}
server.verify().await;
Ok(Some(codex_home))
}

View File

@@ -223,14 +223,11 @@ trust_level = "trusted"
source.join(".codex/config.toml"),
"model = \"source-model\"\n",
)?;
app_test_support::write_chatgpt_auth(
codex_login::login_with_api_key(
&home,
app_test_support::ChatGptAuthFixture::new("test-token")
.account_id("workspace-123")
.chatgpt_account_id("workspace-123")
.chatgpt_user_id("user-123")
.plan_type("enterprise"),
"sk-test-token",
codex_config::types::AuthCredentialsStoreMode::File,
codex_login::AuthKeyringBackendKind::default(),
)?;
let program = codex_utils_cargo_bin::cargo_bin("codex")?;
// Keep cold Rosetta translation outside the timed startup assertions.