Base: codex-main originale (prima del fork aKode)
This commit is contained in:
361
codex-rs/cli/tests/app_server.rs
Normal file
361
codex-rs/cli/tests/app_server.rs
Normal file
@@ -0,0 +1,361 @@
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::Result;
|
||||
use app_test_support::app_server_json_shutdown_event;
|
||||
use predicates::str::contains;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
|
||||
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
cmd.env("CODEX_HOME", codex_home)
|
||||
.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");
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_config_rejects_unknown_config_fields_for_app_server() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
r#"
|
||||
foo = "bar"
|
||||
"#,
|
||||
)?;
|
||||
|
||||
let mut cmd = codex_command(codex_home.path())?;
|
||||
cmd.args(["app-server", "--strict-config", "--listen", "off"])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("unknown configuration field"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_server_preserves_config_overrides_across_subcommand() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
codex_command(home.path())?
|
||||
.args([
|
||||
"-c",
|
||||
"missing-equals",
|
||||
"app-server",
|
||||
"--print-startup-config",
|
||||
"-c",
|
||||
"model=example",
|
||||
])
|
||||
.assert()
|
||||
.failure()
|
||||
.stdout(contains("Invalid override (missing '='): missing-equals"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agents_accept_interactive_configuration_overrides() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
for args in [
|
||||
["-c", "features.multi_agent_mode=true", "agents"].as_slice(),
|
||||
["--enable", "multi_agent_mode", "agents"].as_slice(),
|
||||
["--yolo", "agents"].as_slice(),
|
||||
["--no-daemon", "agents"].as_slice(),
|
||||
["agents", "--no-daemon"].as_slice(),
|
||||
["--search", "agents"].as_slice(),
|
||||
["--model", "gpt-5", "agents"].as_slice(),
|
||||
["--approve-for-me", "agents"].as_slice(),
|
||||
["--cd", ".", "agents"].as_slice(),
|
||||
] {
|
||||
let mut cmd = codex_command(codex_home.path())?;
|
||||
cmd.env("TERM", "xterm-256color").args(args);
|
||||
|
||||
cmd.assert()
|
||||
.failure()
|
||||
.stderr(contains("stdin is not a terminal"));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agents_reject_inputs_that_cannot_be_applied() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
for (args, expected_error) in [
|
||||
(
|
||||
["--image=image.png", "agents"].as_slice(),
|
||||
"does not accept an initial prompt or images",
|
||||
),
|
||||
(
|
||||
["--oss", "agents", "--remote", "ws://127.0.0.1:4512"].as_slice(),
|
||||
"cannot apply local provider or additional-directory overrides",
|
||||
),
|
||||
(
|
||||
[
|
||||
"--add-dir",
|
||||
".",
|
||||
"agents",
|
||||
"--remote",
|
||||
"ws://127.0.0.1:4512",
|
||||
]
|
||||
.as_slice(),
|
||||
"cannot apply local provider or additional-directory overrides",
|
||||
),
|
||||
(
|
||||
[
|
||||
"-c",
|
||||
"sandbox_workspace_write.writable_roots=[\"../shared\"]",
|
||||
"agents",
|
||||
"--remote",
|
||||
"ws://127.0.0.1:4512",
|
||||
]
|
||||
.as_slice(),
|
||||
"cannot apply local provider or additional-directory overrides",
|
||||
),
|
||||
] {
|
||||
let mut cmd = codex_command(codex_home.path())?;
|
||||
cmd.args(args)
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains(expected_error));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_server_emits_json_info_events() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let event = app_server_json_shutdown_event("codex", &["app-server"], codex_home.path())?;
|
||||
|
||||
assert_eq!(
|
||||
event,
|
||||
json!({
|
||||
"level": "INFO",
|
||||
"fields": {
|
||||
"message": "processor task exited",
|
||||
"exit_reason": "stdio_connection_closed",
|
||||
"remaining_connection_count": 0,
|
||||
"shutdown_forced": false,
|
||||
},
|
||||
"target": "codex_app_server",
|
||||
})
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_server_keeps_sqlite_logs_in_overridden_sqlite_home() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let sqlite_home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
"[features]\nplugins = false\n",
|
||||
)?;
|
||||
|
||||
codex_command(home.path())?
|
||||
.env("CODEX_SQLITE_HOME", sqlite_home.path())
|
||||
.env(
|
||||
"CODEX_APP_SERVER_MANAGED_CONFIG_PATH",
|
||||
home.path().join("managed_config.toml"),
|
||||
)
|
||||
.arg("app-server")
|
||||
.write_stdin("")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
assert!(sqlite_home.path().join("state_5.sqlite").is_file());
|
||||
assert!(std::fs::metadata(sqlite_home.path().join("logs_2.sqlite"))?.len() > 0);
|
||||
assert!(!home.path().join("logs_2.sqlite").exists());
|
||||
assert!(!home.path().join("log/logs_2.sqlite").exists());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn app_server_preserves_the_existing_sqlite_logs_symlink() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let external_logs = TempDir::new()?;
|
||||
let target = external_logs.path().join("logs_2.sqlite");
|
||||
let link = home.path().join("logs_2.sqlite");
|
||||
std::os::unix::fs::symlink(&target, &link)?;
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
"[features]\nplugins = false\n",
|
||||
)?;
|
||||
|
||||
codex_command(home.path())?
|
||||
.env_remove("CODEX_SQLITE_HOME")
|
||||
.env(
|
||||
"CODEX_APP_SERVER_MANAGED_CONFIG_PATH",
|
||||
home.path().join("managed_config.toml"),
|
||||
)
|
||||
.arg("app-server")
|
||||
.write_stdin("")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
assert_eq!(std::fs::read_link(&link)?, target);
|
||||
assert!(std::fs::metadata(&target)?.len() > 0);
|
||||
assert!(home.path().join("state_5.sqlite").is_file());
|
||||
assert!(!home.path().join("log/logs_2.sqlite").exists());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_startup_config_preserves_project_login_restrictions() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let project = TempDir::new()?;
|
||||
let project_key =
|
||||
serde_json::to_string(&codex_config::loader::project_trust_key(project.path()))?;
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!("[projects.{project_key}]\ntrust_level = \"trusted\"\n"),
|
||||
)?;
|
||||
std::fs::create_dir(project.path().join(".git"))?;
|
||||
std::fs::create_dir(project.path().join(".codex"))?;
|
||||
for method in ["chatgpt", "api"] {
|
||||
std::fs::write(
|
||||
project.path().join(".codex/config.toml"),
|
||||
format!("forced_login_method = '{method}'\n"),
|
||||
)?;
|
||||
for sign_out in [None, Some("--startup-sign-out")] {
|
||||
let mut command = codex_command(home.path())?;
|
||||
command
|
||||
.current_dir(project.path())
|
||||
.args(["app-server", "--print-startup-config"])
|
||||
.args(sign_out);
|
||||
let output = command.assert().success();
|
||||
let value: serde_json::Value = serde_json::from_slice(&output.get_output().stdout)?;
|
||||
assert_eq!(
|
||||
value["configRequirements"]["requirements"]["allowedLoginMethods"],
|
||||
json!([method])
|
||||
);
|
||||
}
|
||||
}
|
||||
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()?;
|
||||
let config_path = home.path().join("config.toml");
|
||||
for (config, strict_arg, error) in [
|
||||
("[broken\n", None, Some("failed to load configuration")),
|
||||
(
|
||||
"unknown_future_setting = true\n",
|
||||
Some("--strict-config"),
|
||||
Some("unknown configuration field"),
|
||||
),
|
||||
("unknown_future_setting = true\n", None, None),
|
||||
] {
|
||||
std::fs::write(&config_path, config)?;
|
||||
let output = codex_command(home.path())?
|
||||
.args(["app-server", "--print-startup-config"])
|
||||
.args(strict_arg)
|
||||
.assert();
|
||||
let value: serde_json::Value = serde_json::from_slice(&output.get_output().stdout)?;
|
||||
if let Some(error) = error {
|
||||
output.failure().stdout(contains(error));
|
||||
assert_eq!(value["error"]["data"]["reason"], "configLoad");
|
||||
assert_eq!(
|
||||
Path::new(value["error"]["data"]["filePath"].as_str().unwrap()).canonicalize()?,
|
||||
config_path.canonicalize()?
|
||||
);
|
||||
assert!(value["error"]["data"]["line"].as_u64().is_some());
|
||||
assert!(value.get("configRequirements").is_none());
|
||||
} else {
|
||||
output.success();
|
||||
assert_eq!(value["appServerVersion"], env!("CARGO_PKG_VERSION"));
|
||||
assert!(value["configRequirements"].get("requirements").is_some());
|
||||
assert!(value.get("config").is_none());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn print_startup_config_is_independent_of_a_locked_history_database() -> Result<()> {
|
||||
use sqlx::Executor;
|
||||
use std::time::Duration;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
|
||||
let home = TempDir::new()?;
|
||||
let sqlite = TempDir::new()?;
|
||||
let binary = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
let mut command = Command::new(&binary);
|
||||
command
|
||||
.env("CODEX_HOME", home.path())
|
||||
.env("CODEX_SQLITE_HOME", sqlite.path())
|
||||
.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(["app-server", "--print-startup-config"])
|
||||
.kill_on_drop(true);
|
||||
let baseline = timeout(Duration::from_secs(10), command.output()).await??;
|
||||
assert!(baseline.status.success());
|
||||
let path = sqlite.path().join("state_5.sqlite");
|
||||
let sqlite_config = codex_state::SqliteConfig::new_for_testing(
|
||||
codex_utils_absolute_path::AbsolutePathBuf::from_absolute_path(sqlite.path())?,
|
||||
);
|
||||
let pool = sqlite_config.open_read_write_pool(&path).await?;
|
||||
let mut database = pool.acquire().await?;
|
||||
database
|
||||
.execute("CREATE TABLE synthetic_history (id INTEGER)")
|
||||
.await?;
|
||||
database.execute("PRAGMA journal_mode=DELETE").await?;
|
||||
let readers = sqlite_config
|
||||
.open_read_only_pool(&path, Some(Duration::ZERO))
|
||||
.await?;
|
||||
let mut reader = readers.acquire().await?;
|
||||
database.execute("BEGIN EXCLUSIVE").await?;
|
||||
assert!(
|
||||
reader
|
||||
.execute("SELECT * FROM synthetic_history")
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let before = std::fs::read(&path)?;
|
||||
let output = timeout(Duration::from_secs(10), command.output()).await??;
|
||||
assert!(output.status.success());
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<serde_json::Value>(&output.stdout)?,
|
||||
serde_json::from_slice::<serde_json::Value>(&baseline.stdout)?
|
||||
);
|
||||
assert_eq!(std::fs::read(&path)?, before);
|
||||
|
||||
database.execute("ROLLBACK").await?;
|
||||
Ok(())
|
||||
}
|
||||
552
codex-rs/cli/tests/app_server_daemon.rs
Normal file
552
codex-rs/cli/tests/app_server_daemon.rs
Normal file
@@ -0,0 +1,552 @@
|
||||
//! Managed daemon lifecycle through the public CLI, using isolated standalone fixtures.
|
||||
#![cfg(unix)]
|
||||
|
||||
#[path = "app_server_daemon/support.rs"]
|
||||
mod support;
|
||||
|
||||
use support::TestDaemon;
|
||||
use support::signal;
|
||||
use support::wait_for_exit;
|
||||
|
||||
use std::process::Command;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
|
||||
#[test]
|
||||
fn managed_daemon_restarts_from_deleted_working_directory() -> Result<()> {
|
||||
let daemon = TestDaemon::new()?;
|
||||
let project = daemon.home.path().join("project");
|
||||
std::fs::create_dir(&project)?;
|
||||
let started = daemon
|
||||
.command()
|
||||
.current_dir(&project)
|
||||
.args(["app-server", "daemon", "start"])
|
||||
.output()?;
|
||||
ensure!(
|
||||
started.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&started.stderr)
|
||||
);
|
||||
let old_pid = daemon.pid("app-server.pid")?;
|
||||
let old_updater_pid = daemon.pid("app-server-updater.pid")?;
|
||||
signal(old_updater_pid, libc::SIGTERM)?;
|
||||
wait_for_exit(old_updater_pid)?;
|
||||
|
||||
// Delete the restart caller's cwd without changing the test process's cwd.
|
||||
let restarted = Command::new("/bin/sh")
|
||||
.args([
|
||||
"-c",
|
||||
"rmdir \"$1\" && exec \"$2\" app-server daemon restart",
|
||||
"restart",
|
||||
])
|
||||
.arg(&project)
|
||||
.arg(&daemon.codex)
|
||||
.current_dir(&project)
|
||||
.env("CODEX_HOME", daemon.home.path())
|
||||
.output()?;
|
||||
ensure!(
|
||||
restarted.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&restarted.stderr)
|
||||
);
|
||||
let restarted: Value = serde_json::from_slice(&restarted.stdout)?;
|
||||
assert_eq!(restarted["status"], "restarted");
|
||||
assert_ne!(daemon.pid("app-server.pid")?, old_pid);
|
||||
assert_ne!(daemon.pid("app-server-updater.pid")?, old_updater_pid);
|
||||
assert_eq!(daemon.lifecycle("version")?["status"], "running");
|
||||
let updater_socket = daemon
|
||||
.home
|
||||
.path()
|
||||
.join("app-server-daemon/app-server-updater.sock");
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while std::os::unix::net::UnixStream::connect(&updater_socket).is_err() {
|
||||
ensure!(
|
||||
Instant::now() < deadline,
|
||||
"replacement updater did not become ready"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bootstrap_updater_is_ready_in_deep_codex_home() -> Result<()> {
|
||||
let mut daemon = TestDaemon::new()?;
|
||||
let deep_home = tempfile::Builder::new()
|
||||
.prefix(&"deep-codex-home-".repeat(8))
|
||||
.tempdir_in("/tmp")?;
|
||||
for name in ["packages", "app-server-daemon"] {
|
||||
std::fs::rename(daemon.home.path().join(name), deep_home.path().join(name))?;
|
||||
}
|
||||
daemon.home = deep_home;
|
||||
let state = daemon.home.path().join("app-server-daemon");
|
||||
std::fs::write(
|
||||
state.join("settings.json"),
|
||||
br#"{"shutdownGraceSeconds":0}"#,
|
||||
)?;
|
||||
let socket = state.join("app-server-updater.sock");
|
||||
let result = daemon.lifecycle("bootstrap")?;
|
||||
assert_eq!(result["autoUpdateEnabled"], true);
|
||||
assert_eq!(result["status"], "bootstrapped");
|
||||
signal(daemon.pid("app-server-updater.pid")?, /*signal*/ 0)?;
|
||||
let target = socket.canonicalize()?;
|
||||
let _connection = std::os::unix::net::UnixStream::connect(target)?;
|
||||
assert_eq!(daemon.lifecycle("version")?["status"], "running");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bootstrap_reports_updater_bind_failure() -> Result<()> {
|
||||
let daemon = TestDaemon::new()?;
|
||||
let state = daemon.home.path().join("app-server-daemon");
|
||||
std::fs::write(
|
||||
state.join("settings.json"),
|
||||
br#"{"shutdownGraceSeconds":0}"#,
|
||||
)?;
|
||||
let socket = state.join("app-server-updater.sock");
|
||||
std::fs::write(&socket, b"not a socket")?;
|
||||
let result = daemon
|
||||
.command()
|
||||
.args(["app-server", "daemon", "bootstrap"])
|
||||
.output()?;
|
||||
assert!(!result.status.success());
|
||||
assert_eq!(std::fs::read(socket)?, b"not a socket");
|
||||
assert_eq!(daemon.lifecycle("version")?["status"], "running");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_restart_applies_feature_overrides_and_preserves_saved_settings() -> Result<()> {
|
||||
let daemon = TestDaemon::new()?;
|
||||
let settings_path = daemon.home.path().join("app-server-daemon/settings.json");
|
||||
std::fs::write(
|
||||
&settings_path,
|
||||
serde_json::to_vec(&serde_json::json!({
|
||||
"shutdownGraceSeconds": 0,
|
||||
"updater": { "autoUpdateEnabled": false },
|
||||
"featureOverrides": {
|
||||
"api_key_model_discovery": false,
|
||||
"auth_elicitation": true,
|
||||
"connectors": true,
|
||||
"apps": true
|
||||
}
|
||||
}))?,
|
||||
)?;
|
||||
let mut previous_pid = None;
|
||||
// Start from a stopped daemon, change running settings, and restart again
|
||||
// with omitted flags. Every explicit restart replaces the process.
|
||||
for (args, discovery) in [
|
||||
(
|
||||
vec![
|
||||
"--enable",
|
||||
"api_key_model_discovery",
|
||||
"--disable",
|
||||
"connectors",
|
||||
"-c",
|
||||
"features.network_proxy.enabled=false",
|
||||
],
|
||||
true,
|
||||
),
|
||||
(vec!["--disable", "api_key_model_discovery"], false),
|
||||
(vec!["-c", "features.api_key_model_discovery=true"], true),
|
||||
(vec![], true),
|
||||
] {
|
||||
let output = daemon
|
||||
.command()
|
||||
.args(["app-server", "daemon", "restart"])
|
||||
.args(args)
|
||||
.output()?;
|
||||
ensure!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let output: Value = serde_json::from_slice(&output.stdout)?;
|
||||
assert_eq!(output["status"], "restarted");
|
||||
let pid = output["pid"].as_u64().context("restarted daemon PID")?;
|
||||
assert_ne!(Some(pid), previous_pid);
|
||||
previous_pid = Some(pid);
|
||||
let settings: Value = serde_json::from_slice(&std::fs::read(&settings_path)?)?;
|
||||
assert_eq!(
|
||||
settings["featureOverrides"],
|
||||
serde_json::json!({
|
||||
"api_key_model_discovery": discovery,
|
||||
"auth_elicitation": true,
|
||||
"apps": false,
|
||||
"network_proxy": false
|
||||
})
|
||||
);
|
||||
assert_eq!(settings["updater"]["autoUpdateEnabled"], false);
|
||||
}
|
||||
// Non-toggle config keys must fail before stopping the daemon or saving settings.
|
||||
let saved_settings = std::fs::read(&settings_path)?;
|
||||
let output = daemon
|
||||
.command()
|
||||
.args([
|
||||
"app-server",
|
||||
"daemon",
|
||||
"restart",
|
||||
"--enable",
|
||||
"tool_registry",
|
||||
])
|
||||
.output()?;
|
||||
assert!(!output.status.success());
|
||||
insta::assert_snapshot!(
|
||||
String::from_utf8(output.stderr)?,
|
||||
@"Error: daemon restart requires a boolean feature toggle: tool_registry"
|
||||
);
|
||||
assert_eq!(std::fs::read(&settings_path)?, saved_settings);
|
||||
assert_eq!(Some(u64::from(daemon.pid("app-server.pid")?)), previous_pid);
|
||||
assert_eq!(daemon.lifecycle("version")?["status"], "running");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
#[test]
|
||||
fn managed_identity_survives_locale_and_timezone_changes() -> Result<()> {
|
||||
let daemon = TestDaemon::new()?;
|
||||
let mut original = Vec::new();
|
||||
let mut updater_pid = 0;
|
||||
let pid_file = daemon.home.path().join("app-server-daemon/app-server.pid");
|
||||
for (action, locale, timezone, expected_status) in [
|
||||
("start", "C", "UTC0", "started"),
|
||||
("version", "en_AU.UTF-8", "PST8PDT", "running"),
|
||||
("restart", "en_AU.UTF-8", "PST8PDT", "restarted"),
|
||||
("stop", "C", "UTC0", "stopped"),
|
||||
] {
|
||||
let output = daemon
|
||||
.command()
|
||||
.args(["app-server", "daemon", action])
|
||||
.env("LC_ALL", locale)
|
||||
.env("TZ", timezone)
|
||||
.output()?;
|
||||
ensure!(
|
||||
output.status.success(),
|
||||
"daemon {action} failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let output: Value = serde_json::from_slice(&output.stdout)?;
|
||||
assert_eq!(output["status"], expected_status);
|
||||
if action == "start" {
|
||||
updater_pid = daemon.pid("app-server-updater.pid")?;
|
||||
original = std::fs::read(&pid_file)?;
|
||||
let record: Value = serde_json::from_slice(&original)?;
|
||||
assert!(record["processIdentity"].is_object());
|
||||
// Older clients still receive the original, unnormalized ps value.
|
||||
let legacy = Command::new("ps")
|
||||
.args([
|
||||
"-p",
|
||||
&daemon.pid("app-server.pid")?.to_string(),
|
||||
"-o",
|
||||
"lstart=",
|
||||
])
|
||||
.env("LC_ALL", locale)
|
||||
.env("TZ", timezone)
|
||||
.output()?;
|
||||
ensure!(legacy.status.success(), "failed to read legacy start time");
|
||||
assert_eq!(
|
||||
record["processStartTime"],
|
||||
String::from_utf8(legacy.stdout)?.trim()
|
||||
);
|
||||
} else if action == "version" {
|
||||
assert_eq!(output["backend"], "pid");
|
||||
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
|
||||
assert_eq!(std::fs::read(&pid_file)?, original);
|
||||
|
||||
// Finish startup promotion before deliberately restoring a legacy record.
|
||||
let updater_socket = daemon
|
||||
.home
|
||||
.path()
|
||||
.join("app-server-daemon/app-server-updater.sock");
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while !updater_socket.exists() {
|
||||
ensure!(Instant::now() < deadline, "updater did not become ready");
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
let mut legacy: Value = serde_json::from_slice(&original)?;
|
||||
legacy
|
||||
.as_object_mut()
|
||||
.context("PID record object")?
|
||||
.remove("processIdentity");
|
||||
let legacy_bytes = serde_json::to_vec(&legacy)?;
|
||||
std::fs::write(&pid_file, &legacy_bytes)?;
|
||||
let result = daemon
|
||||
.command()
|
||||
.args(["app-server", "daemon", "version"])
|
||||
.env("LC_ALL", locale)
|
||||
.env("TZ", timezone)
|
||||
.output();
|
||||
let preserved = std::fs::read(&pid_file);
|
||||
// Restore the native identity before assertions so Drop can stop the daemon.
|
||||
std::fs::write(&pid_file, &original)?;
|
||||
let result = result?;
|
||||
assert!(!result.status.success());
|
||||
assert_eq!(preserved?, legacy_bytes);
|
||||
let stderr =
|
||||
String::from_utf8(result.stderr)?.replace(&legacy["pid"].to_string(), "[PID]");
|
||||
insta::assert_snapshot!(stderr, @"Error: cannot verify pid-managed process [PID]: legacy start time changed; PID record retained. Retry with the locale and timezone used to start the daemon. If the system clock changed, stop the original process before restarting the daemon");
|
||||
}
|
||||
if action == "restart" {
|
||||
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
|
||||
}
|
||||
}
|
||||
assert!(!pid_file.exists());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_ownership_check_does_not_start_an_updater() -> Result<()> {
|
||||
let daemon = TestDaemon::new()?;
|
||||
let output = daemon
|
||||
.command()
|
||||
.args([
|
||||
"app-server",
|
||||
"daemon",
|
||||
"pid-update-loop",
|
||||
"--check-package-ownership",
|
||||
])
|
||||
.output()?;
|
||||
ensure!(
|
||||
output.status.success(),
|
||||
"ownership check failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let state = daemon.home.path().join("app-server-daemon");
|
||||
assert!(!state.join("app-server-updater.pid").exists());
|
||||
assert!(!state.join("daemon-updater.pid").exists());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_starts_ensure_one_updater_and_recover_a_missing_one() -> Result<()> {
|
||||
let daemon = TestDaemon::new()?;
|
||||
assert_eq!(daemon.lifecycle("start")?["status"], "started");
|
||||
let backend_pid = daemon.pid("app-server.pid")?;
|
||||
let updater_pid = daemon.pid("app-server-updater.pid")?;
|
||||
assert_ne!(backend_pid, updater_pid);
|
||||
|
||||
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
|
||||
assert_eq!(daemon.pid("app-server.pid")?, backend_pid);
|
||||
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
|
||||
|
||||
signal(updater_pid, libc::SIGTERM)?;
|
||||
wait_for_exit(updater_pid)?;
|
||||
// A replacement updater also upgrades still-verifiable records left by an old CLI.
|
||||
let server_record_path = daemon.home.path().join("app-server-daemon/app-server.pid");
|
||||
let mut legacy: Value = serde_json::from_slice(&std::fs::read(&server_record_path)?)?;
|
||||
let native = legacy.as_object_mut().unwrap().remove("processIdentity");
|
||||
std::fs::write(&server_record_path, serde_json::to_vec(&legacy)?)?;
|
||||
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
|
||||
assert_eq!(daemon.pid("app-server.pid")?, backend_pid);
|
||||
let replacement_pid = daemon.pid("app-server-updater.pid")?;
|
||||
assert_ne!(replacement_pid, updater_pid);
|
||||
if let Some(native) = native {
|
||||
legacy["processIdentity"] = native;
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
let record: Value = serde_json::from_slice(&std::fs::read(&server_record_path)?)?;
|
||||
if record == legacy {
|
||||
break;
|
||||
}
|
||||
ensure!(
|
||||
Instant::now() < deadline,
|
||||
"legacy record was not upgraded: {record}"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
assert_eq!(daemon.lifecycle("restart")?["status"], "restarted");
|
||||
assert_ne!(daemon.pid("app-server.pid")?, backend_pid);
|
||||
assert_eq!(daemon.pid("app-server-updater.pid")?, replacement_pid);
|
||||
daemon.lifecycle("stop")?;
|
||||
assert!(
|
||||
!daemon
|
||||
.home
|
||||
.path()
|
||||
.join("app-server-daemon/app-server.pid")
|
||||
.exists()
|
||||
);
|
||||
assert_eq!(daemon.lifecycle("start")?["status"], "started");
|
||||
assert!(
|
||||
!daemon
|
||||
.home
|
||||
.path()
|
||||
.join("packages/app-server-daemon")
|
||||
.exists()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_start_succeeds_when_updater_record_is_invalid() -> Result<()> {
|
||||
let daemon = TestDaemon::new()?;
|
||||
let state_dir = daemon.home.path().join("app-server-daemon");
|
||||
std::fs::create_dir_all(&state_dir)?;
|
||||
std::fs::write(state_dir.join("app-server-updater.pid"), "not a PID record")?;
|
||||
|
||||
assert_eq!(daemon.lifecycle("start")?["status"], "started");
|
||||
let server_pid = daemon.pid("app-server.pid")?;
|
||||
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
|
||||
assert_eq!(daemon.pid("app-server.pid")?, server_pid);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
#[test]
|
||||
fn wall_clock_shift_keeps_server_and_updater_managed() -> Result<()> {
|
||||
let daemon = TestDaemon::new()?;
|
||||
assert_eq!(daemon.lifecycle("start")?["status"], "started");
|
||||
let server_pid = daemon.pid("app-server.pid")?;
|
||||
let updater_pid = daemon.pid("app-server-updater.pid")?;
|
||||
for name in ["app-server.pid", "app-server-updater.pid"] {
|
||||
let path = daemon.home.path().join("app-server-daemon").join(name);
|
||||
let mut record: Value = serde_json::from_slice(&std::fs::read(&path)?)?;
|
||||
record["processStartTime"] = "historical wall-clock start time".into();
|
||||
let replacement = path.with_extension("replacement");
|
||||
std::fs::write(&replacement, serde_json::to_vec(&record)?)?;
|
||||
std::fs::rename(replacement, path)?;
|
||||
}
|
||||
|
||||
let version = daemon.lifecycle("version")?;
|
||||
assert_eq!(version["status"], "running");
|
||||
assert_eq!(version["backend"], "pid");
|
||||
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
|
||||
assert_eq!(daemon.pid("app-server.pid")?, server_pid);
|
||||
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
|
||||
assert_eq!(daemon.lifecycle("restart")?["status"], "restarted");
|
||||
wait_for_exit(server_pid)?;
|
||||
assert_ne!(daemon.pid("app-server.pid")?, server_pid);
|
||||
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_start_keeps_updater_on_marker_mismatch_but_stops_it_for_pin() -> Result<()> {
|
||||
let daemon = TestDaemon::new()?;
|
||||
assert_eq!(daemon.lifecycle("start")?["status"], "started");
|
||||
let updater_pid = daemon.pid("app-server-updater.pid")?;
|
||||
let marker = daemon
|
||||
.home
|
||||
.path()
|
||||
.join("packages/standalone/auto-update-version");
|
||||
std::fs::write(&marker, "0.1.0-other-target")?;
|
||||
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
|
||||
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
|
||||
std::thread::sleep(Duration::from_millis(250));
|
||||
let updater_state = Command::new("/bin/ps")
|
||||
.args(["-p", &updater_pid.to_string(), "-o", "stat="])
|
||||
.output()?;
|
||||
ensure!(
|
||||
updater_state.status.success()
|
||||
&& !String::from_utf8_lossy(&updater_state.stdout)
|
||||
.trim()
|
||||
.starts_with('Z'),
|
||||
"updater exited during the latest marker transition"
|
||||
);
|
||||
|
||||
std::fs::remove_file(marker)?;
|
||||
|
||||
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
|
||||
wait_for_exit(updater_pid)?;
|
||||
assert!(
|
||||
!daemon
|
||||
.home
|
||||
.path()
|
||||
.join("app-server-daemon/app-server-updater.pid")
|
||||
.exists()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_applies_saved_updater_preference() -> Result<()> {
|
||||
let daemon = TestDaemon::new()?;
|
||||
assert_eq!(daemon.lifecycle("start")?["status"], "started");
|
||||
let updater_pid = daemon.pid("app-server-updater.pid")?;
|
||||
let settings = daemon.home.path().join("app-server-daemon/settings.json");
|
||||
std::fs::write(
|
||||
&settings,
|
||||
serde_json::to_vec(&serde_json::json!({
|
||||
"updater": {"autoUpdateEnabled": false, "updateIntervalMinutes": 2},
|
||||
}))?,
|
||||
)?;
|
||||
assert_eq!(daemon.lifecycle("restart")?["status"], "restarted");
|
||||
wait_for_exit(updater_pid)?;
|
||||
assert!(daemon.pid("app-server-updater.pid").is_err());
|
||||
assert_eq!(daemon.lifecycle("bootstrap")?["autoUpdateEnabled"], false);
|
||||
assert!(daemon.pid("app-server-updater.pid").is_err());
|
||||
|
||||
std::fs::write(
|
||||
&settings,
|
||||
serde_json::to_vec(&serde_json::json!({
|
||||
"updater": {"autoUpdateEnabled": true, "updateIntervalMinutes": 2},
|
||||
}))?,
|
||||
)?;
|
||||
assert_eq!(daemon.lifecycle("restart")?["status"], "restarted");
|
||||
assert_ne!(daemon.pid("app-server-updater.pid")?, updater_pid);
|
||||
|
||||
std::fs::write(&settings, "{malformed")?;
|
||||
assert_eq!(daemon.lifecycle("stop")?["status"], "stopped");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmanaged_app_server_does_not_launch_updater() -> Result<()> {
|
||||
let mut daemon = TestDaemon::new()?;
|
||||
daemon.unmanaged = Some(
|
||||
daemon
|
||||
.command()
|
||||
.args(["app-server", "--listen", "unix://"])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()?,
|
||||
);
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while !daemon
|
||||
.command()
|
||||
.args(["app-server", "daemon", "version"])
|
||||
.output()?
|
||||
.status
|
||||
.success()
|
||||
{
|
||||
ensure!(Instant::now() < deadline, "app server did not become ready");
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
|
||||
let output = daemon.lifecycle("start")?;
|
||||
assert_eq!(output["status"], "alreadyRunning");
|
||||
assert_eq!(output["backend"], Value::Null);
|
||||
assert_eq!(daemon.lifecycle("update")?["status"], "unsupported");
|
||||
assert!(
|
||||
!daemon
|
||||
.home
|
||||
.path()
|
||||
.join("app-server-daemon/app-server-updater.pid")
|
||||
.exists()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manual_update_rejects_an_unowned_installation() -> Result<()> {
|
||||
let daemon = TestDaemon::new()?;
|
||||
std::fs::remove_file(
|
||||
daemon
|
||||
.home
|
||||
.path()
|
||||
.join("packages/standalone/current/bin/codex"),
|
||||
)?;
|
||||
|
||||
assert_eq!(daemon.lifecycle("update")?["status"], "unsupported");
|
||||
assert!(daemon.pid("app-server.pid").is_err());
|
||||
assert!(daemon.pid("app-server-updater.pid").is_err());
|
||||
Ok(())
|
||||
}
|
||||
219
codex-rs/cli/tests/app_server_daemon/package.rs
Normal file
219
codex-rs/cli/tests/app_server_daemon/package.rs
Normal file
@@ -0,0 +1,219 @@
|
||||
//! Real package installation and replacement through the daemon CLI.
|
||||
//! Keep these I/O-heavy cases separate from ordinary lifecycle coverage.
|
||||
#![cfg(unix)]
|
||||
|
||||
mod support;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use support::TestDaemon;
|
||||
use support::wait_for_exit;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum InitialDaemon {
|
||||
Missing,
|
||||
Legacy,
|
||||
}
|
||||
|
||||
fn packaged_daemon_launch(action: &str, initial: InitialDaemon) -> Result<()> {
|
||||
let mut daemon = TestDaemon::new()?;
|
||||
let standalone = daemon.home.path().join("packages/standalone");
|
||||
let package = if action == "start" && initial == InitialDaemon::Missing {
|
||||
standalone.join("releases/caller")
|
||||
} else {
|
||||
daemon.home.path().join("cli-package")
|
||||
};
|
||||
for directory in ["bin", "codex-path", "codex-resources"] {
|
||||
std::fs::create_dir_all(package.join(directory))?;
|
||||
}
|
||||
// Both paths are in this test's temp home and therefore on the same filesystem.
|
||||
// Reuse its prepared (and on Intel macOS, translated) executable. The installer
|
||||
// still makes a real independent package copy; only fixture setup shares this inode.
|
||||
std::fs::hard_link(
|
||||
standalone.join("current/bin/codex"),
|
||||
package.join("bin/codex"),
|
||||
)?;
|
||||
daemon.codex = package.join("bin/codex");
|
||||
for helper in [
|
||||
"bin/codex-code-mode-host",
|
||||
"codex-path/rg",
|
||||
"codex-resources/bwrap",
|
||||
] {
|
||||
codex_utils_cargo_bin::write_executable(&package.join(helper), "runtime fixture")?;
|
||||
}
|
||||
let target = format!(
|
||||
"{}-{}",
|
||||
std::env::consts::ARCH,
|
||||
if cfg!(target_os = "macos") {
|
||||
"apple-darwin"
|
||||
} else if cfg!(target_env = "gnu") {
|
||||
"unknown-linux-gnu"
|
||||
} else {
|
||||
"unknown-linux-musl"
|
||||
}
|
||||
);
|
||||
std::fs::write(
|
||||
package.join("codex-package.json"),
|
||||
serde_json::to_vec(&serde_json::json!({
|
||||
"version": env!("CARGO_PKG_VERSION"), "target": target, "entrypoint": "bin/codex"
|
||||
}))?,
|
||||
)?;
|
||||
if action == "start" && initial == InitialDaemon::Missing {
|
||||
std::fs::remove_file(standalone.join("current"))?;
|
||||
std::os::unix::fs::symlink(&package, standalone.join("current"))?;
|
||||
}
|
||||
let cli_selection = standalone.join("current").canonicalize()?;
|
||||
let state = daemon.home.path().join("app-server-daemon");
|
||||
if initial == InitialDaemon::Missing {
|
||||
std::fs::remove_file(state.join("app-server.stderr.log"))?;
|
||||
}
|
||||
std::fs::write(
|
||||
state.join("settings.json"),
|
||||
br#"{"shutdownGraceSeconds":0}"#,
|
||||
)?;
|
||||
let cli_before = daemon.codex.canonicalize()?;
|
||||
let result = daemon
|
||||
.command()
|
||||
.args(["app-server", "daemon", action])
|
||||
.output()
|
||||
.context("failed to launch packaged daemon fixture")?;
|
||||
ensure!(
|
||||
result.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
assert_eq!(
|
||||
String::from_utf8_lossy(&result.stderr).contains("Installing daemon from CLI version"),
|
||||
initial == InitialDaemon::Missing
|
||||
);
|
||||
let output: Value = serde_json::from_slice(&result.stdout)?;
|
||||
let dedicated = daemon
|
||||
.home
|
||||
.path()
|
||||
.canonicalize()?
|
||||
.join("packages/app-server-daemon");
|
||||
let (initial_root, initial_pid_file) = match initial {
|
||||
InitialDaemon::Missing => (&dedicated, "daemon.pid"),
|
||||
InitialDaemon::Legacy => (&standalone, "app-server.pid"),
|
||||
};
|
||||
assert_eq!(
|
||||
output["managedCodexPath"],
|
||||
initial_root
|
||||
.canonicalize()?
|
||||
.join("current/bin/codex")
|
||||
.to_str()
|
||||
.context("managed path is not UTF-8")?
|
||||
);
|
||||
assert_eq!(daemon.codex.canonicalize()?, cli_before);
|
||||
assert_eq!(standalone.join("current").canonicalize()?, cli_selection);
|
||||
assert!(state.join(initial_pid_file).exists());
|
||||
let legacy_updater = match initial {
|
||||
InitialDaemon::Missing => {
|
||||
assert!(!state.join("app-server-updater.pid").exists());
|
||||
None
|
||||
}
|
||||
InitialDaemon::Legacy => Some(daemon.pid("app-server-updater.pid")?),
|
||||
};
|
||||
if action == "start" {
|
||||
let initial_current = initial_root.join("current");
|
||||
let current = dedicated.join("current");
|
||||
let original = initial_current.canonicalize()?;
|
||||
let original_pid = daemon.pid(initial_pid_file)?;
|
||||
let settings_before = std::fs::read(state.join("settings.json"))?;
|
||||
let refused = daemon
|
||||
.command()
|
||||
.args(["app-server", "daemon", "update", "--from-cli"])
|
||||
.output()?;
|
||||
assert!(!refused.status.success());
|
||||
assert!(String::from_utf8_lossy(&refused.stderr).contains("rerun with --yes"));
|
||||
assert_eq!(daemon.pid(initial_pid_file)?, original_pid);
|
||||
assert_eq!(initial_current.canonicalize()?, original);
|
||||
if initial == InitialDaemon::Legacy {
|
||||
assert!(!current.exists());
|
||||
}
|
||||
|
||||
std::fs::remove_file(package.join("bin/codex-code-mode-host"))?;
|
||||
let invalid = daemon
|
||||
.command()
|
||||
.args(["app-server", "daemon", "update", "--from-cli", "--yes"])
|
||||
.output()?;
|
||||
assert!(!invalid.status.success());
|
||||
assert_eq!(daemon.pid(initial_pid_file)?, original_pid);
|
||||
assert_eq!(initial_current.canonicalize()?, original);
|
||||
if initial == InitialDaemon::Legacy {
|
||||
assert!(!current.exists());
|
||||
}
|
||||
codex_utils_cargo_bin::write_executable(
|
||||
&package.join("bin/codex-code-mode-host"),
|
||||
"replacement helper",
|
||||
)?;
|
||||
let replaced = daemon
|
||||
.command()
|
||||
.args(["app-server", "daemon", "update", "--from-cli", "--yes"])
|
||||
.output()?;
|
||||
ensure!(
|
||||
replaced.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&replaced.stderr)
|
||||
);
|
||||
let output: Value = serde_json::from_slice(&replaced.stdout)?;
|
||||
assert_eq!(output["status"], "updated");
|
||||
assert_ne!(daemon.pid("daemon.pid")?, original_pid);
|
||||
wait_for_exit(original_pid)?;
|
||||
if let Some(pid) = legacy_updater {
|
||||
wait_for_exit(pid)?;
|
||||
}
|
||||
assert!(!state.join("app-server.pid").exists());
|
||||
assert!(!state.join("app-server-updater.pid").exists());
|
||||
assert_eq!(
|
||||
output["managedCodexPath"],
|
||||
current
|
||||
.join("bin/codex")
|
||||
.to_str()
|
||||
.context("managed path is not UTF-8")?
|
||||
);
|
||||
assert_ne!(current.canonicalize()?, original);
|
||||
assert!(!dedicated.join("auto-update-version").exists());
|
||||
assert_eq!(std::fs::read(state.join("settings.json"))?, settings_before);
|
||||
assert_eq!(
|
||||
std::fs::read(current.join("bin/codex-code-mode-host"))?,
|
||||
b"replacement helper"
|
||||
);
|
||||
if initial == InitialDaemon::Missing {
|
||||
assert_eq!(
|
||||
std::fs::read(original.join("bin/codex-code-mode-host"))?,
|
||||
b"runtime fixture"
|
||||
);
|
||||
}
|
||||
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
|
||||
assert_eq!(daemon.lifecycle("stop")?["status"], "stopped");
|
||||
assert_eq!(standalone.join("current").canonicalize()?, cli_selection);
|
||||
}
|
||||
if action == "bootstrap" {
|
||||
assert_eq!(output["autoUpdateEnabled"], false);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packaged_daemon_start_and_explicit_replacement() -> Result<()> {
|
||||
packaged_daemon_launch("start", InitialDaemon::Missing)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packaged_daemon_restart_seeds_local_package() -> Result<()> {
|
||||
packaged_daemon_launch("restart", InitialDaemon::Missing)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packaged_daemon_bootstrap_seeds_local_package() -> Result<()> {
|
||||
packaged_daemon_launch("bootstrap", InitialDaemon::Missing)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packaged_daemon_explicit_replacement_migrates_running_legacy() -> Result<()> {
|
||||
packaged_daemon_launch("start", InitialDaemon::Legacy)
|
||||
}
|
||||
140
codex-rs/cli/tests/app_server_daemon/support.rs
Normal file
140
codex-rs/cli/tests/app_server_daemon/support.rs
Normal file
@@ -0,0 +1,140 @@
|
||||
//! Isolated installed-CLI fixtures and PID cleanup for Unix daemon integration tests.
|
||||
//! Every test owns its home and CLI selection; only immutable executable contents are shared.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::Child;
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use codex_utils_cargo_bin::copy_executable;
|
||||
use serde_json::Value;
|
||||
use tempfile::TempDir;
|
||||
|
||||
pub(super) struct TestDaemon {
|
||||
pub(super) home: TempDir,
|
||||
pub(super) codex: PathBuf,
|
||||
pub(super) unmanaged: Option<Child>,
|
||||
}
|
||||
|
||||
impl TestDaemon {
|
||||
pub(super) fn new() -> Result<Self> {
|
||||
let home = tempfile::Builder::new().tempdir_in("/tmp")?;
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
let codex_source = std::fs::canonicalize(&codex)?;
|
||||
let target = if cfg!(target_os = "macos") {
|
||||
format!("{}-apple-darwin", std::env::consts::ARCH)
|
||||
} else {
|
||||
format!("{}-unknown-linux-musl", std::env::consts::ARCH)
|
||||
};
|
||||
let standalone = home.path().join("packages/standalone");
|
||||
let release_name = format!("0.0.0-{target}");
|
||||
let managed = standalone
|
||||
.join("releases")
|
||||
.join(&release_name)
|
||||
.join("bin/codex");
|
||||
std::fs::create_dir_all(managed.parent().context("managed bin parent")?)?;
|
||||
// Preserve the installed path without invalidating the shared CLI's Rosetta cache.
|
||||
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
|
||||
{
|
||||
copy_executable(&codex_source, &managed)?;
|
||||
// Translate the fixture before timed daemon capability and readiness checks.
|
||||
ensure!(
|
||||
Command::new(&managed)
|
||||
.env("CODEX_HOME", home.path())
|
||||
.arg("--version")
|
||||
.output()?
|
||||
.status
|
||||
.success(),
|
||||
"failed to prepare managed test executable"
|
||||
);
|
||||
}
|
||||
#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]
|
||||
if std::fs::hard_link(&codex_source, &managed).is_err() {
|
||||
copy_executable(&codex_source, &managed)?;
|
||||
}
|
||||
std::fs::write(standalone.join("auto-update-version"), &release_name)?;
|
||||
std::os::unix::fs::symlink(
|
||||
PathBuf::from("releases").join(release_name),
|
||||
standalone.join("current"),
|
||||
)?;
|
||||
// Model a daemon that was previously launched and is currently stopped.
|
||||
let state = home.path().join("app-server-daemon");
|
||||
std::fs::create_dir(&state)?;
|
||||
std::fs::write(state.join("app-server.stderr.log"), b"")?;
|
||||
Ok(Self {
|
||||
home,
|
||||
codex,
|
||||
unmanaged: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn command(&self) -> Command {
|
||||
let mut command = Command::new(&self.codex);
|
||||
command.env("CODEX_HOME", self.home.path());
|
||||
command
|
||||
}
|
||||
|
||||
pub(super) fn lifecycle(&self, action: &str) -> Result<Value> {
|
||||
let output = self
|
||||
.command()
|
||||
.args(["app-server", "daemon", action])
|
||||
.output()?;
|
||||
ensure!(
|
||||
output.status.success(),
|
||||
"daemon {action} failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
Ok(serde_json::from_slice(&output.stdout)?)
|
||||
}
|
||||
|
||||
pub(super) fn pid(&self, name: &str) -> Result<u32> {
|
||||
let record = std::fs::read(self.home.path().join("app-server-daemon").join(name))
|
||||
.with_context(|| format!("failed to read {name}"))?;
|
||||
Ok(serde_json::from_slice::<Value>(&record)?["pid"]
|
||||
.as_u64()
|
||||
.context("pid missing")? as u32)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestDaemon {
|
||||
fn drop(&mut self) {
|
||||
if let Some(mut child) = self.unmanaged.take() {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
let _ = self.lifecycle("stop");
|
||||
if let Ok(pid) = self.pid("app-server-updater.pid") {
|
||||
let _ = signal(pid, libc::SIGTERM);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn signal(pid: u32, signal: libc::c_int) -> Result<()> {
|
||||
let raw_pid = libc::pid_t::try_from(pid).context("pid out of range")?;
|
||||
ensure!(
|
||||
unsafe { libc::kill(raw_pid, signal) } == 0,
|
||||
"failed to signal pid {pid}: {}",
|
||||
std::io::Error::last_os_error()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn wait_for_exit(pid: u32) -> Result<()> {
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
let output = Command::new("/bin/ps")
|
||||
.args(["-p", &pid.to_string(), "-o", "stat="])
|
||||
.output()
|
||||
.context("failed to invoke ps")?;
|
||||
let state = String::from_utf8_lossy(&output.stdout);
|
||||
if !output.status.success() || state.trim().starts_with('Z') {
|
||||
return Ok(());
|
||||
}
|
||||
ensure!(Instant::now() < deadline, "pid {pid} did not exit: {state}");
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
126
codex-rs/cli/tests/app_server_daemon_windows.rs
Normal file
126
codex-rs/cli/tests/app_server_daemon_windows.rs
Normal file
@@ -0,0 +1,126 @@
|
||||
//! Exercises daemon installation from the Windows WinGet archive layout.
|
||||
#![cfg(windows)]
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use codex_utils_cargo_bin::copy_executable;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn winget_package_starts_and_reselects_daemon() -> Result<()> {
|
||||
if codex_app_server_daemon::is_elevated()? {
|
||||
eprintln!("requires a non-elevated Windows runner");
|
||||
return Ok(());
|
||||
}
|
||||
let temp = tempfile::tempdir()?;
|
||||
let home = temp.path().join("home");
|
||||
let package = temp.path().join("WinGet/Packages/OpenAI.Codex");
|
||||
let target = format!("{}-pc-windows-msvc", std::env::consts::ARCH);
|
||||
let entrypoint = format!("codex-{target}.exe");
|
||||
let codex = package.join(&entrypoint);
|
||||
for directory in ["bin", "codex-path", "codex-resources/voice"] {
|
||||
std::fs::create_dir_all(package.join(directory))?;
|
||||
}
|
||||
copy_executable(&codex_utils_cargo_bin::cargo_bin("codex")?, &codex)?;
|
||||
for helper in [
|
||||
"codex-code-mode-host.exe",
|
||||
"codex-path/rg.exe",
|
||||
"codex-resources/codex-command-runner.exe",
|
||||
"codex-resources/codex-windows-sandbox-setup.exe",
|
||||
] {
|
||||
std::fs::write(package.join(helper), b"runtime fixture")?;
|
||||
}
|
||||
let mut metadata = serde_json::json!({
|
||||
"layoutVersion": 1, "version": env!("CARGO_PKG_VERSION"),
|
||||
"target": target, "entrypoint": entrypoint
|
||||
});
|
||||
let manifest_bytes = serde_json::to_vec(&metadata)?;
|
||||
std::fs::write(package.join("codex-package.json"), &manifest_bytes)?;
|
||||
let checksum = format!("{:x}", Sha256::digest(std::fs::read(&codex)?));
|
||||
let voice_bytes = serde_json::to_vec(&serde_json::json!({
|
||||
"sha256": { &entrypoint: checksum, "codex-resources/voice/runtime": "untouched" }
|
||||
}))?;
|
||||
std::fs::write(
|
||||
package.join("codex-resources/voice/manifest.json"),
|
||||
&voice_bytes,
|
||||
)?;
|
||||
|
||||
let current = home.join("packages/app-server-daemon/current");
|
||||
// Drop before temp so assertion failures also release the managed executable.
|
||||
struct StopDaemon(Command);
|
||||
impl Drop for StopDaemon {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.output();
|
||||
}
|
||||
}
|
||||
let mut stop = Command::new(&codex);
|
||||
stop.env("CODEX_HOME", &home)
|
||||
.args(["app-server", "daemon", "stop"]);
|
||||
let mut daemon = StopDaemon(stop);
|
||||
for args in [
|
||||
vec!["start"],
|
||||
vec!["update", "--from-cli", "--yes"],
|
||||
vec!["update", "--from-cli", "--yes"],
|
||||
] {
|
||||
let output = Command::new(&codex)
|
||||
.env("CODEX_HOME", &home)
|
||||
.args(["app-server", "daemon"])
|
||||
.args(&args)
|
||||
.output()?;
|
||||
ensure!(
|
||||
output.status.success(),
|
||||
"daemon {args:?} failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
let selected_metadata: Value =
|
||||
serde_json::from_slice(&std::fs::read(current.join("codex-package.json"))?)?;
|
||||
metadata["entrypoint"] = "bin/codex.exe".into();
|
||||
assert_eq!(selected_metadata, metadata);
|
||||
let selected_voice: Value = serde_json::from_slice(&std::fs::read(
|
||||
current.join("codex-resources/voice/manifest.json"),
|
||||
)?)?;
|
||||
assert_eq!(
|
||||
selected_voice,
|
||||
serde_json::json!({
|
||||
"sha256": {
|
||||
"bin/codex.exe": checksum,
|
||||
"codex-resources/voice/runtime": "untouched"
|
||||
}
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(current.join("bin/codex-code-mode-host.exe"))?,
|
||||
b"runtime fixture"
|
||||
);
|
||||
let selected = current.canonicalize()?;
|
||||
std::fs::remove_file(package.join("codex-code-mode-host.exe"))?;
|
||||
let invalid = Command::new(&codex)
|
||||
.env("CODEX_HOME", &home)
|
||||
.args(["app-server", "daemon", "update", "--from-cli", "--yes"])
|
||||
.output()?;
|
||||
ensure!(
|
||||
!invalid.status.success(),
|
||||
"an incomplete WinGet package was accepted"
|
||||
);
|
||||
assert_eq!(current.canonicalize()?, selected);
|
||||
assert_eq!(
|
||||
std::fs::read(package.join("codex-package.json"))?,
|
||||
manifest_bytes
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(package.join("codex-resources/voice/manifest.json"))?,
|
||||
voice_bytes
|
||||
);
|
||||
let stopped = daemon.0.output()?;
|
||||
ensure!(
|
||||
stopped.status.success(),
|
||||
"failed to stop daemon: {}",
|
||||
String::from_utf8_lossy(&stopped.stderr)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
113
codex-rs/cli/tests/cloud_auth.rs
Normal file
113
codex-rs/cli/tests/cloud_auth.rs
Normal file
@@ -0,0 +1,113 @@
|
||||
//! Exercise Cloud credential isolation through the CLI using a synthetic login.
|
||||
|
||||
use anyhow::Result;
|
||||
use predicates::str::contains;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
#[tokio::test]
|
||||
async fn cloud_list_respects_the_credential_store_and_trusted_destinations() -> Result<()> {
|
||||
let server = MockServer::start().await;
|
||||
let codex_home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
"cli_auth_credentials_store = 'file'\n",
|
||||
)?;
|
||||
std::fs::write(
|
||||
codex_home.path().join("auth.json"),
|
||||
serde_json::to_vec(&json!({
|
||||
"auth_mode": "chatgpt",
|
||||
"tokens": {
|
||||
"id_token": "eyJhbGciOiJub25lIn0.e30.c2ln",
|
||||
"access_token": "synthetic-cloud-access-token",
|
||||
"refresh_token": "synthetic-cloud-refresh-token",
|
||||
"account_id": "synthetic-cloud-account",
|
||||
},
|
||||
"last_refresh": chrono::Utc::now(),
|
||||
}))?,
|
||||
)?;
|
||||
|
||||
let command = || -> Result<assert_cmd::Command> {
|
||||
let mut command = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
command
|
||||
.current_dir(codex_home.path())
|
||||
.env("CODEX_HOME", codex_home.path())
|
||||
.env_remove("CODEX_ACCESS_TOKEN")
|
||||
.env_remove("OPENAI_API_KEY")
|
||||
.env_remove("CODEX_CLOUD_TASKS_MODE")
|
||||
.env("NO_PROXY", "127.0.0.1,localhost")
|
||||
.env("no_proxy", "127.0.0.1,localhost")
|
||||
.timeout(std::time::Duration::from_secs(15));
|
||||
Ok(command)
|
||||
};
|
||||
// Establish that the isolated profile has a usable ChatGPT login.
|
||||
command()?
|
||||
.args(["login", "status"])
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(contains("Logged in using ChatGPT"));
|
||||
|
||||
let output = command()?
|
||||
.env(
|
||||
"CODEX_CLOUD_TASKS_BASE_URL",
|
||||
format!("{}/backend-api", server.uri()),
|
||||
)
|
||||
.args(["cloud", "list", "--limit", "1", "--json"])
|
||||
.assert()
|
||||
.failure()
|
||||
.get_output()
|
||||
.stderr
|
||||
.clone();
|
||||
insta::assert_snapshot!(String::from_utf8(output)?, @"Error: CODEX_CLOUD_TASKS_BASE_URL must use a trusted HTTPS origin on port 443, without user information, a query, or a fragment; custom backends cannot use saved ChatGPT credentials");
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
|
||||
// An explicit ephemeral store must exclude the saved login for Cloud itself.
|
||||
command()?
|
||||
.env(
|
||||
"CODEX_CLOUD_TASKS_BASE_URL",
|
||||
"https://chatgpt-staging.com/backend-api",
|
||||
)
|
||||
.env("HTTPS_PROXY", server.uri())
|
||||
.env("https_proxy", server.uri())
|
||||
.args([
|
||||
"-c",
|
||||
"cli_auth_credentials_store='ephemeral'",
|
||||
"cloud",
|
||||
"list",
|
||||
"--limit",
|
||||
"1",
|
||||
"--json",
|
||||
])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("Not signed in. Please run 'codex login'"));
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
|
||||
// Staging must reach explicit PAT authentication. Reject the synthetic PAT locally so
|
||||
// this test never sends a request to the real staging backend.
|
||||
let auth_server = MockServer::start().await;
|
||||
Mock::given(path("/v1/user-auth-credential/whoami"))
|
||||
.and(header("authorization", "Bearer at-synthetic-cloud"))
|
||||
.respond_with(ResponseTemplate::new(401))
|
||||
.expect(1)
|
||||
.mount(&auth_server)
|
||||
.await;
|
||||
command()?
|
||||
.env(
|
||||
"CODEX_CLOUD_TASKS_BASE_URL",
|
||||
"https://chatgpt-staging.com/backend-api",
|
||||
)
|
||||
.env("CODEX_ACCESS_TOKEN", "at-synthetic-cloud")
|
||||
.env("CODEX_AUTHAPI_BASE_URL", auth_server.uri())
|
||||
.args(["cloud", "list", "--limit", "1", "--json"])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("Not signed in. Please run 'codex login'"));
|
||||
auth_server.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
688
codex-rs/cli/tests/cloud_config.rs
Normal file
688
codex-rs/cli/tests/cloud_config.rs
Normal file
@@ -0,0 +1,688 @@
|
||||
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(())
|
||||
}
|
||||
633
codex-rs/cli/tests/daemon_startup.rs
Normal file
633
codex-rs/cli/tests/daemon_startup.rs
Normal file
@@ -0,0 +1,633 @@
|
||||
//! Exercises daemon startup and excluded resume/fork pickers with Cargo's CLI executable.
|
||||
|
||||
use anyhow::Context as _;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use std::collections::VecDeque;
|
||||
use std::fs;
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test]
|
||||
#[cfg(unix)]
|
||||
async fn auto_daemon_start_attaches_to_shared_server() -> Result<()> {
|
||||
daemon_startup("start").await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[cfg(unix)]
|
||||
async fn agents_can_offer_restart_for_managed_daemon() -> Result<()> {
|
||||
daemon_startup("agents").await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[cfg(unix)]
|
||||
async fn agents_no_daemon_uses_embedded_even_with_a_running_daemon() -> Result<()> {
|
||||
daemon_startup("agents-no-daemon").await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[cfg(unix)]
|
||||
async fn agents_defers_launch_directory_trust_until_starting_a_task() -> Result<()> {
|
||||
daemon_startup("agents-untrusted").await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[cfg(unix)]
|
||||
async fn discovered_managed_daemon_can_restart_with_auto_start_disabled() -> Result<()> {
|
||||
daemon_startup("discovered").await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[cfg(unix)]
|
||||
async fn incompatible_daemon_can_cancel() -> Result<()> {
|
||||
daemon_startup("mismatch-cancel").await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[cfg(unix)]
|
||||
async fn incompatible_daemon_can_run_embedded() -> Result<()> {
|
||||
daemon_startup("mismatch-embedded").await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[cfg(unix)]
|
||||
async fn incompatible_daemon_can_restart_with_confirmed_settings() -> Result<()> {
|
||||
daemon_startup("mismatch-restart").await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[cfg(unix)]
|
||||
async fn fresh_daemon_requires_confirmation_to_disable_shared_features() -> Result<()> {
|
||||
daemon_startup("mismatch-disable").await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[cfg(unix)]
|
||||
async fn stopped_daemon_requires_confirmation_to_disable_persisted_features() -> Result<()> {
|
||||
daemon_startup("mismatch-disable-persisted").await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn daemon_exclusion_survives_resume_picker() -> Result<()> {
|
||||
daemon_startup("resume").await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn daemon_exclusion_survives_fork_picker() -> Result<()> {
|
||||
daemon_startup("fork").await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn daemon_auto_start_preserves_bedrock_onboarding() -> Result<()> {
|
||||
daemon_startup("bedrock").await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[cfg(windows)]
|
||||
async fn elevated_local_tui_uses_embedded_without_starting_daemon() -> Result<()> {
|
||||
if !codex_app_server_daemon::is_elevated()? {
|
||||
eprintln!("requires an elevated Windows runner");
|
||||
return Ok(());
|
||||
}
|
||||
for command in ["elevated", "elevated-resume", "elevated-fork"] {
|
||||
daemon_startup(command).await?;
|
||||
}
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
let home = tempfile::tempdir()?;
|
||||
for operation in ["start", "restart"] {
|
||||
let output = Command::new(&codex)
|
||||
.env("CODEX_HOME", home.path())
|
||||
.args(["app-server", "daemon", operation])
|
||||
.output()?;
|
||||
ensure!(
|
||||
!output.status.success(),
|
||||
"{operation} must reject elevation"
|
||||
);
|
||||
ensure!(
|
||||
String::from_utf8_lossy(&output.stderr).contains("non-elevated terminal"),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
ensure!(!home.path().join("app-server-daemon").exists());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[cfg(windows)]
|
||||
async fn restrictive_launcher_uses_embedded_if_daemon_cannot_start() -> Result<()> {
|
||||
const CHILD: &str = "CODEX_TEST_RESTRICTIVE_DAEMON_START";
|
||||
if std::env::var_os(CHILD).is_some() {
|
||||
// The PTY creates its own breakaway-permitted job. Add Cargo's
|
||||
// restriction *inside* the PTY so it is the CLI's innermost job.
|
||||
let job = codex_utils_pty::JobObject::create_without_breakaway()?;
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
let mut command = tokio::process::Command::new(codex);
|
||||
command
|
||||
.arg("--no-alt-screen")
|
||||
.stdin(std::process::Stdio::inherit())
|
||||
.stdout(std::process::Stdio::inherit())
|
||||
.stderr(std::process::Stdio::inherit())
|
||||
// This interactive CLI must inherit the PTY console rather than use
|
||||
// the background helper's CREATE_NO_WINDOW launch policy.
|
||||
.creation_flags(windows_sys::Win32::System::Threading::CREATE_SUSPENDED)
|
||||
.kill_on_drop(true);
|
||||
let mut child = command.spawn()?;
|
||||
ensure!(
|
||||
job.assign_and_resume_process(child.id().context("missing CLI pid")?)?
|
||||
.is_some(),
|
||||
"CLI job assignment failed"
|
||||
);
|
||||
let status = child.wait().await?;
|
||||
ensure!(status.success(), "CLI exited: {status}");
|
||||
return Ok(());
|
||||
}
|
||||
daemon_startup("restrictive-job").await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[cfg(unix)]
|
||||
async fn bedrock_onboarding_discovers_credentials_on_the_running_daemon() -> Result<()> {
|
||||
daemon_startup("bedrock-running").await
|
||||
}
|
||||
|
||||
async fn daemon_startup(command: &str) -> Result<()> {
|
||||
#[cfg(windows)]
|
||||
let elevated = codex_app_server_daemon::is_elevated()?;
|
||||
#[cfg(not(windows))]
|
||||
let elevated = false;
|
||||
let elevated_launch = command.starts_with("elevated");
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")?.canonicalize()?;
|
||||
let workspace = tempfile::tempdir()?;
|
||||
let workspace_path = workspace.path().canonicalize()?;
|
||||
#[cfg(unix)]
|
||||
let home = tempfile::Builder::new().tempdir_in("/tmp")?;
|
||||
#[cfg(not(unix))]
|
||||
let home = tempfile::tempdir()?;
|
||||
// Keep cold Rosetta translation outside the timed startup assertions.
|
||||
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
|
||||
anyhow::ensure!(
|
||||
Command::new(&codex)
|
||||
.env("CODEX_HOME", home.path())
|
||||
.arg("--version")
|
||||
.output()?
|
||||
.status
|
||||
.success(),
|
||||
"failed to prepare CLI test executable"
|
||||
);
|
||||
let bedrock_onboarding = matches!(command, "bedrock" | "bedrock-running");
|
||||
fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!(
|
||||
"model = \"gpt-5.6-terra\"\n\
|
||||
cli_auth_credentials_store = \"file\"\n\
|
||||
suppress_unstable_features_warning = true\nanalytics.enabled = false\n\
|
||||
windows.sandbox = \"unelevated\"\n\
|
||||
tui.disable_paste_burst = true\n\
|
||||
{}\n\
|
||||
notice.model_migrations.\"gpt-5.6-terra\" = \"gpt-6-sol\"\n\
|
||||
[projects.{}]\ntrust_level = \"{}\"\n",
|
||||
if command == "discovered" {
|
||||
"tui.status_line=[\"model\",\"thread-id\",\"thread-name\"]\nfeatures.daemon_auto_start=false"
|
||||
} else if bedrock_onboarding {
|
||||
"features.gcp_setup_wizard=false"
|
||||
} else {
|
||||
""
|
||||
},
|
||||
serde_json::to_string(&workspace_path)?,
|
||||
if command == "agents-untrusted" {
|
||||
"untrusted"
|
||||
} else {
|
||||
"trusted"
|
||||
},
|
||||
),
|
||||
)?;
|
||||
let mismatch = command.starts_with("mismatch-");
|
||||
let persisted = command == "mismatch-disable-persisted";
|
||||
let disabling = matches!(command, "mismatch-disable" | "mismatch-disable-persisted");
|
||||
let restart = command == "mismatch-restart" || disabling;
|
||||
if !bedrock_onboarding {
|
||||
fs::write(
|
||||
home.path().join("auth.json"),
|
||||
r#"{"OPENAI_API_KEY":"daemon-startup-test","tokens":null,"last_refresh":null}"#,
|
||||
)?;
|
||||
}
|
||||
let mut env = std::env::vars().collect::<std::collections::HashMap<_, _>>();
|
||||
for key in [
|
||||
"CODEX_EXEC_SERVER_URL",
|
||||
"CODEX_ACCESS_TOKEN",
|
||||
"CODEX_API_KEY",
|
||||
"CODEX_CLOUD_TASKS_MODE",
|
||||
"OPENAI_API_KEY",
|
||||
"OPENAI_FEDERATION_RULE_ID",
|
||||
"OPENAI_IDENTITY_TOKEN_FILE",
|
||||
"OPENAI_WORKLOAD_IDENTITY_CONTEXT",
|
||||
] {
|
||||
env.remove(key);
|
||||
}
|
||||
env.insert("CODEX_HOME".into(), home.path().display().to_string());
|
||||
env.insert(
|
||||
"CODEX_SQLITE_HOME".into(),
|
||||
home.path().display().to_string(),
|
||||
);
|
||||
env.insert("TERM".into(), "xterm-256color".into());
|
||||
let mut args = vec!["--no-alt-screen".to_string()];
|
||||
let mut steps: VecDeque<(&str, &[u8])> = VecDeque::new();
|
||||
if matches!(
|
||||
command,
|
||||
"start"
|
||||
| "agents"
|
||||
| "agents-no-daemon"
|
||||
| "agents-untrusted"
|
||||
| "discovered"
|
||||
| "bedrock"
|
||||
| "bedrock-running"
|
||||
| "restrictive-job"
|
||||
) || mismatch
|
||||
{
|
||||
// A selected package with a stopped daemon avoids installing a release.
|
||||
let managed = home
|
||||
.path()
|
||||
.join("packages/app-server-daemon/current/bin")
|
||||
.join(if cfg!(windows) { "codex.exe" } else { "codex" });
|
||||
fs::create_dir_all(home.path().join("packages/app-server-daemon/current/bin"))?;
|
||||
// Hard links change the executable's ctime and invalidate Rosetta's translation cache.
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(&codex, &managed)?;
|
||||
#[cfg(not(unix))]
|
||||
fs::hard_link(&codex, &managed)
|
||||
.or_else(|_| codex_utils_cargo_bin::copy_executable(&codex, &managed))?;
|
||||
if command != "restrictive-job" {
|
||||
fs::create_dir(home.path().join("app-server-daemon"))?;
|
||||
fs::write(
|
||||
home.path().join("app-server-daemon/settings.json"),
|
||||
if persisted {
|
||||
r#"{"shutdownGraceSeconds":0,"updater":{"autoUpdateEnabled":false},"featureOverrides":{"api_key_model_discovery":true}}"#
|
||||
} else {
|
||||
r#"{"shutdownGraceSeconds":0,"updater":{"autoUpdateEnabled":false}}"#
|
||||
},
|
||||
)?;
|
||||
}
|
||||
}
|
||||
let pid_file = home.path().join("app-server-daemon/daemon.pid");
|
||||
let result = async {
|
||||
let mut existing_daemon = if matches!(command, "bedrock-running" | "discovered" | "agents-no-daemon")
|
||||
|| (mismatch && !disabling)
|
||||
{
|
||||
if command == "bedrock-running" {
|
||||
// This Unix-only case uses a daemon-only token and no ambient profiles.
|
||||
env.insert("AWS_CONFIG_FILE".into(), "/dev/null".into());
|
||||
env.insert("AWS_SHARED_CREDENTIALS_FILE".into(), "/dev/null".into());
|
||||
env.remove("AWS_ACCESS_KEY_ID");
|
||||
env.remove("AWS_SECRET_ACCESS_KEY");
|
||||
env.insert("AWS_BEARER_TOKEN_BEDROCK".into(), "daemon-only-test-token".into());
|
||||
}
|
||||
let started = Command::new(&codex)
|
||||
.env_clear()
|
||||
.envs(&env)
|
||||
.current_dir(&workspace_path)
|
||||
.args(["app-server", "daemon", "start"])
|
||||
.output()?;
|
||||
ensure!(
|
||||
started.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&started.stderr)
|
||||
);
|
||||
Some(fs::read(&pid_file)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let expected = if command == "start" {
|
||||
// The draft header is visible before the session's command composer is ready.
|
||||
steps.push_back(("GPT-5.6-Terra", b"/status\r"));
|
||||
"Server:Localbackgroundserver"
|
||||
} else if command == "agents-no-daemon" {
|
||||
args.extend(["agents".into(), "--no-daemon".into()]);
|
||||
steps.push_back(("Notasksyet", b"n"));
|
||||
steps.push_back(("GPT-5.6-Terra", b"/daemon\r"));
|
||||
"Notconnectedtothelocalbackgroundserver"
|
||||
} else if command == "agents" {
|
||||
args.push("agents".into());
|
||||
steps.push_back(("Notasksyet", b"n"));
|
||||
steps.push_back(("GPT-5.6-Terra", b"/daemon\r"));
|
||||
steps.push_back(("Restartbackgroundserver", b"\x1b[F\r"));
|
||||
"Restartbackgroundserver?"
|
||||
} else if command == "agents-untrusted" {
|
||||
args.push("agents".into());
|
||||
steps.push_back(("Notasksyet", b"n"));
|
||||
"entercontinue·escback"
|
||||
} else if command == "discovered" {
|
||||
args.extend(["--disable".into(), "daemon_auto_start".into()]);
|
||||
// Empty drafts need not survive a daemon restart. Renaming materializes the
|
||||
// thread; wait for the confirmed footer name, not the echoed command.
|
||||
steps.push_back(("GPT-5.6-Terra", b"/rename daemon-restart-test\r"));
|
||||
steps.push_back(("·daemon-restart-test", b"/daemon\r"));
|
||||
steps.push_back(("Restartbackgroundserver", b"2"));
|
||||
steps.push_back(("Restartbackgroundserver?", b"2\r"));
|
||||
// Offline editing preserves text but suppresses Enter. Observe the command
|
||||
// popup in a complete connected frame before submitting the retained draft.
|
||||
steps.push_back(("GPT-5.6-Terra", b"/status"));
|
||||
steps.push_back(("/statusshowcurrentsessionconfigurationandtokenusage", b"\r"));
|
||||
"Server:Localbackgroundserver"
|
||||
} else if elevated_launch || command == "restrictive-job" && elevated {
|
||||
if let Some(action) = command.strip_prefix("elevated-") {
|
||||
args.push(action.into());
|
||||
steps.push_back(("Nosessionsyet", b"\x1b"));
|
||||
}
|
||||
steps.push_back(("GPT-5.6-Terra", b"\x14"));
|
||||
"Runningasadministrator:sharedbackgroundserverdisabled."
|
||||
} else if command == "restrictive-job" {
|
||||
steps.push_back(("GPT-5.6-Terra", b"\x14"));
|
||||
"Runningwithoutthesharedbackgroundserver:thisWindowslauncher"
|
||||
} else if mismatch {
|
||||
args.extend(if disabling && !persisted {
|
||||
["--disable".into(), "auth_elicitation".into()]
|
||||
} else {
|
||||
["--disable".into(), "api_key_model_discovery".into()]
|
||||
});
|
||||
let input: &[u8] = match command {
|
||||
"mismatch-cancel" => b"\x03",
|
||||
"mismatch-embedded" => b"1",
|
||||
"mismatch-restart" | "mismatch-disable" | "mismatch-disable-persisted" => b"2\r",
|
||||
_ => unreachable!(),
|
||||
};
|
||||
steps.push_back(("Backgroundserverhasincompatiblefeaturesettings", input));
|
||||
if command == "mismatch-cancel" {
|
||||
"--no-daemon"
|
||||
} else {
|
||||
steps.push_back(("GPT-5.6-Terra", b"/status\r"));
|
||||
if restart { "Server:Localbackgroundserver" } else { "Model:" }
|
||||
}
|
||||
} else if command == "bedrock-running" {
|
||||
env.remove("AWS_BEARER_TOKEN_BEDROCK");
|
||||
steps.push_back(("UseanAPIkeyoranotherprovider", b"3"));
|
||||
steps.push_back(("UseAmazonBedrock", b"2"));
|
||||
"Continuewithdetectedcredentials"
|
||||
} else if bedrock_onboarding {
|
||||
// With GCP disabled, only Bedrock makes the sign-in menu advertise another provider.
|
||||
"UseanAPIkeyoranotherprovider"
|
||||
} else {
|
||||
args.extend([command.into(), "--strict-config".into()]);
|
||||
if command == "resume" {
|
||||
let thread_id = "00000000-0000-0000-0000-000000000001";
|
||||
let sessions = home.path().join("sessions/2025/01/05");
|
||||
fs::create_dir_all(&sessions)?;
|
||||
let metadata = serde_json::json!({
|
||||
"timestamp": "2025-01-05T12:00:00Z",
|
||||
"type": "session_meta",
|
||||
"payload": {
|
||||
"session_id": thread_id, "id": thread_id,
|
||||
"timestamp": "2025-01-05T12:00:00Z", "cwd": workspace_path,
|
||||
"originator": "codex", "cli_version": "0.0.0",
|
||||
"source": "cli", "model_provider": "openai"
|
||||
}
|
||||
});
|
||||
let message = serde_json::json!({
|
||||
"timestamp": "2025-01-05T12:00:00Z",
|
||||
"type": "event_msg",
|
||||
"payload": {"type": "user_message", "message": "Saved resume session", "kind": "plain"}
|
||||
});
|
||||
fs::write(
|
||||
sessions.join(format!("rollout-2025-01-05T12-00-00-{thread_id}.jsonl")),
|
||||
format!("{metadata}\n{message}\n"),
|
||||
)?;
|
||||
steps.push_back(("Savedresumesession", b"\r"));
|
||||
} else {
|
||||
steps.push_back(("Nosessionsyet", b"\x1b"));
|
||||
}
|
||||
steps.push_back(("GPT-5.6-Terra", b"\x14"));
|
||||
if elevated {
|
||||
"Runningasadministrator:sharedbackgroundserverdisabled."
|
||||
} else {
|
||||
"Runningwithoutthesharedbackgroundserver:--strict-config"
|
||||
}
|
||||
};
|
||||
let program = if cfg!(windows) && command == "restrictive-job" {
|
||||
env.insert("CODEX_TEST_RESTRICTIVE_DAEMON_START".into(), "1".into());
|
||||
args = vec![
|
||||
"--exact".into(),
|
||||
"restrictive_launcher_uses_embedded_if_daemon_cannot_start".into(),
|
||||
"--nocapture".into(),
|
||||
];
|
||||
std::env::current_exe()?
|
||||
} else {
|
||||
codex.clone()
|
||||
};
|
||||
let spawned = codex_utils_pty::spawn_pty_process(
|
||||
&program.to_string_lossy(),
|
||||
&args,
|
||||
&workspace_path,
|
||||
&env,
|
||||
/*arg0*/ &None,
|
||||
codex_utils_pty::TerminalSize {
|
||||
rows: 40,
|
||||
cols: 120,
|
||||
},
|
||||
codex_utils_pty::ChildFds::Inherited(&[]),
|
||||
)
|
||||
.await?;
|
||||
let exit = spawned.exit_rx;
|
||||
let session = spawned.session;
|
||||
let writer = session.writer_sender();
|
||||
let mut stdout = spawned.stdout_rx;
|
||||
let mut output = String::new();
|
||||
let mut initial_agents_screen = String::new();
|
||||
let mut screen = vt100::Parser::new(
|
||||
/*rows*/ 40, /*cols*/ 120, /*scrollback_len*/ 0,
|
||||
);
|
||||
let mut queries: Vec<(&str, &[u8])> = vec![
|
||||
("\x1b[6n", b"\x1b[1;1R"),
|
||||
("\x1b[?u", b"\x1b[?0u\x1b[?1;2c"),
|
||||
("\x1b[c", b"\x1b[?1;2c"),
|
||||
("\x1b]10;?", b"\x1b]10;rgb:ffff/ffff/ffff\x1b\\"),
|
||||
("\x1b]11;?", b"\x1b]11;rgb:0000/0000/0000\x1b\\"),
|
||||
];
|
||||
// A fresh disable request includes both cold daemon startup and its confirmed restart.
|
||||
let timeout = Duration::from_secs(if disabling { 90 } else { 45 });
|
||||
let result = tokio::time::timeout(timeout, async {
|
||||
loop {
|
||||
let bytes = tokio::select! {
|
||||
bytes = stdout.recv() => bytes,
|
||||
// The first onboarding draw precedes its typeahead drain. Retry the
|
||||
// main menu shortcut until the submenu appears (it has no option 3).
|
||||
() = tokio::time::sleep(Duration::from_millis(/*millis*/ 250)),
|
||||
if steps.front().is_some_and(|(ready, _)| *ready == "UseAmazonBedrock") => {
|
||||
writer.send(b"3".to_vec()).await?;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let Some(bytes) = bytes else { break };
|
||||
output.push_str(&String::from_utf8_lossy(&bytes));
|
||||
screen.process(&bytes);
|
||||
for (query, reply) in &mut queries {
|
||||
if !query.is_empty() && output.contains(*query) {
|
||||
writer.send(reply.to_vec()).await?;
|
||||
*query = "";
|
||||
}
|
||||
}
|
||||
// PTY reads can split a redraw after the reconnect notice is erased but
|
||||
// before it is repainted. Only inspect completed synchronized updates.
|
||||
if command == "discovered"
|
||||
&& output
|
||||
.rfind("\x1b[?2026l")
|
||||
.is_none_or(|end| output[end..].contains("\x1b[?2026h"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let text: String = screen
|
||||
.screen()
|
||||
.contents()
|
||||
.chars()
|
||||
.filter(|c| !c.is_whitespace())
|
||||
.collect();
|
||||
if let Some((ready, input)) = steps.front()
|
||||
&& text.contains(ready)
|
||||
{
|
||||
if command == "agents-untrusted" && *ready == "Notasksyet" {
|
||||
if !text.contains("enteropennnew") {
|
||||
continue;
|
||||
}
|
||||
initial_agents_screen = screen.screen().contents();
|
||||
}
|
||||
if command == "discovered" {
|
||||
if *ready == "Restartbackgroundserver?" {
|
||||
existing_daemon = Some(fs::read(&pid_file)?);
|
||||
} else if *ready == "GPT-5.6-Terra" {
|
||||
// The header renders before thread/start completes. Wait for the
|
||||
// live status line to confirm there is a session to reconnect.
|
||||
if !screen.screen().contents().split_whitespace().any(|part| {
|
||||
codex_protocol::ThreadId::from_string(part).is_ok()
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// A replacement PID can appear before the TUI observes the disconnect.
|
||||
// Wait for reconnect to clear/rebuild the transcript, so the old
|
||||
// composer's command popup cannot make the status probe look ready.
|
||||
if *input == b"/status" && !output.contains("\x1b[3J") {
|
||||
continue;
|
||||
}
|
||||
// The old header can linger while the daemon stops. Check both
|
||||
// the draft and its Enter against the replacement process and UI.
|
||||
if (*input == b"/status" || *input == b"\r")
|
||||
&& (!fs::read(&pid_file).is_ok_and(|pid| Some(pid) != existing_daemon)
|
||||
|| text.contains("Reconnecting"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if disabling && *ready == "Backgroundserverhasincompatiblefeaturesettings" {
|
||||
existing_daemon = Some(fs::read(&pid_file)?);
|
||||
let settings: serde_json::Value = serde_json::from_slice(&fs::read(home.path().join("app-server-daemon/settings.json"))?)?;
|
||||
if persisted {
|
||||
ensure!(settings["featureOverrides"]["api_key_model_discovery"] == true);
|
||||
} else {
|
||||
ensure!(settings["featureOverrides"]["auth_elicitation"].is_null());
|
||||
}
|
||||
}
|
||||
writer.send(input.to_vec()).await?;
|
||||
steps.pop_front();
|
||||
output.clear();
|
||||
} else if steps.is_empty() && text.contains(expected) {
|
||||
if command == "agents-untrusted" {
|
||||
let transition = format!(
|
||||
"{initial_agents_screen}\n\n--- Start a task ---\n\n{}",
|
||||
screen.screen().contents()
|
||||
)
|
||||
.replace(&*workspace_path.to_string_lossy(), "[WORKSPACE]")
|
||||
.replace(&*home.path().to_string_lossy(), "[CODEX_HOME]")
|
||||
.replace(" tab/⇧tab filter", "tab/shift+tab filter");
|
||||
let transition = transition.lines().map(str::trim_end).collect::<Vec<_>>().join("\n");
|
||||
let snapshot = codex_utils_cargo_bin::find_resource!(
|
||||
"tests/snapshots/daemon_startup__agents_overview_before_folder_consent.snap"
|
||||
)?;
|
||||
insta::with_settings!({snapshot_path => snapshot.parent().context("snapshot has no parent")?}, {
|
||||
insta::assert_snapshot!("agents_overview_before_folder_consent", transition);
|
||||
});
|
||||
}
|
||||
if mismatch {
|
||||
let previous_pid = existing_daemon.as_ref().context("missing original daemon PID")?;
|
||||
ensure!((fs::read(&pid_file)? != *previous_pid) == restart);
|
||||
if command == "mismatch-cancel" {
|
||||
ensure!(text.contains("Cannotusethesharedbackgroundserver:Thissessionrequiresapi_key_model_discoverytobedisabled."));
|
||||
} else {
|
||||
ensure!(text.contains("Server:Localbackgroundserver") == restart);
|
||||
if restart {
|
||||
let settings: serde_json::Value = serde_json::from_slice(
|
||||
&fs::read(home.path().join("app-server-daemon/settings.json"))?
|
||||
)?;
|
||||
let flag = if disabling && !persisted {
|
||||
"auth_elicitation"
|
||||
} else {
|
||||
"api_key_model_discovery"
|
||||
};
|
||||
assert_eq!(settings["featureOverrides"], serde_json::json!({(flag): false}));
|
||||
}
|
||||
}
|
||||
} else if command == "start" {
|
||||
ensure!(text.contains("Server:Localbackgroundserver"));
|
||||
ensure!(home.path().join("app-server-daemon/daemon.pid").exists());
|
||||
} else if command == "discovered" {
|
||||
let previous_pid = existing_daemon.as_ref().context("missing original daemon PID")?;
|
||||
ensure!(fs::read(&pid_file)? != *previous_pid, "daemon PID did not change");
|
||||
} else if let Some(existing_daemon) = &existing_daemon {
|
||||
ensure!(fs::read(&pid_file)? == *existing_daemon);
|
||||
} else if elevated_launch {
|
||||
ensure!(!home.path().join("app-server-daemon").exists());
|
||||
ensure!(!home.path().join("packages/app-server-daemon").exists());
|
||||
} else if bedrock_onboarding {
|
||||
ensure!(pid_file.exists() != elevated);
|
||||
} else if command == "restrictive-job" {
|
||||
ensure!(!pid_file.exists());
|
||||
if !elevated {
|
||||
let contents = screen.screen().contents();
|
||||
let warning = contents.lines()
|
||||
.find(|line| line.contains("Running without the shared background server:"))
|
||||
.context("missing rendered fallback warning")?;
|
||||
insta::assert_snapshot!("restrictive_launcher_warning", warning.trim());
|
||||
}
|
||||
}
|
||||
return Ok::<_, anyhow::Error>(());
|
||||
}
|
||||
}
|
||||
anyhow::bail!(
|
||||
"TUI exited before {expected}: {}",
|
||||
screen.screen().contents()
|
||||
)
|
||||
})
|
||||
.await;
|
||||
if command == "mismatch-cancel" && matches!(result, Ok(Ok(()))) {
|
||||
let status = tokio::time::timeout(Duration::from_secs(/*secs*/ 5), exit).await??;
|
||||
ensure!(status != 0, "incompatible daemon launch must fail");
|
||||
}
|
||||
Ok::<_, anyhow::Error>((
|
||||
session,
|
||||
result.with_context(|| format!("{command} timed out waiting for {}: {}", steps.front().map_or(expected, |(ready, _)| *ready), screen.screen().contents())),
|
||||
))
|
||||
}
|
||||
.await;
|
||||
// Elevated fresh Bedrock onboarding already verified that no daemon started.
|
||||
if elevated
|
||||
&& command == "bedrock"
|
||||
&& let Ok((session, Ok(Ok(())))) = &result
|
||||
{
|
||||
session.terminate();
|
||||
return Ok(());
|
||||
}
|
||||
// Stop the detached daemon, including on timeout or failed assertions.
|
||||
let stopped = Command::new(&codex)
|
||||
.env_clear()
|
||||
.envs(&env)
|
||||
.args(["app-server", "daemon", "stop"])
|
||||
.output()?;
|
||||
let (session, result) = result?;
|
||||
session.terminate();
|
||||
result??;
|
||||
ensure!(
|
||||
stopped.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&stopped.stderr)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
77
codex-rs/cli/tests/daemon_telemetry.rs
Normal file
77
codex-rs/cli/tests/daemon_telemetry.rs
Normal file
@@ -0,0 +1,77 @@
|
||||
//! Foreground updates honor explicit metrics exporters and never claim unconfirmed installation.
|
||||
|
||||
use anyhow::Context as _;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
|
||||
#[tokio::test]
|
||||
async fn foreground_update_honors_metrics_exporter_and_reports_unconfirmed() -> anyhow::Result<()> {
|
||||
for (analytics_config, analytics_default_enabled, metrics_enabled) in [
|
||||
("", false, true),
|
||||
("", true, true),
|
||||
("analytics.enabled = true\n", false, true),
|
||||
("analytics.enabled = false\n", true, true),
|
||||
("analytics.enabled = true\n", true, false),
|
||||
] {
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(wiremock::matchers::path("/metrics"))
|
||||
.respond_with(ResponseTemplate::new(200))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let home = tempfile::tempdir()?;
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!(
|
||||
"cli_auth_credentials_store = \"file\"\n{analytics_config}[otel]\nmetrics_exporter = {{ otlp-http = {{ endpoint = \"{}/metrics\", protocol = \"json\" }} }}\n",
|
||||
server.uri(),
|
||||
),
|
||||
)?;
|
||||
// No managed installation exists, so the command cannot confirm an applied update.
|
||||
let mut command = tokio::process::Command::new(&codex);
|
||||
command
|
||||
.current_dir(home.path())
|
||||
.env("CODEX_HOME", home.path())
|
||||
.env_remove(codex_app_server_daemon::telemetry::HANDOFF_ENV)
|
||||
.arg("app-server");
|
||||
if analytics_default_enabled {
|
||||
command.arg("--analytics-default-enabled");
|
||||
}
|
||||
if !metrics_enabled {
|
||||
command.args(["-c", "otel.metrics_exporter=\"none\""]);
|
||||
}
|
||||
let output = command
|
||||
.args(["daemon", "update", "--from-cli", "--yes"])
|
||||
.output()
|
||||
.await?;
|
||||
assert!(!output.status.success());
|
||||
let requests = server
|
||||
.received_requests()
|
||||
.await
|
||||
.context("metric requests")?;
|
||||
assert_eq!(requests.len(), usize::from(metrics_enabled));
|
||||
if !metrics_enabled {
|
||||
continue;
|
||||
}
|
||||
let body: Value = serde_json::from_slice(&requests[0].body)?;
|
||||
let metric = body["resourceMetrics"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flat_map(|resource| resource["scopeMetrics"].as_array().into_iter().flatten())
|
||||
.flat_map(|scope| scope["metrics"].as_array().into_iter().flatten())
|
||||
.find(|metric| metric["name"] == "codex.daemon.update")
|
||||
.context("daemon update metric")?;
|
||||
assert!(
|
||||
metric["sum"]["dataPoints"][0]["attributes"]
|
||||
.as_array()
|
||||
.context("metric attributes")?
|
||||
.iter()
|
||||
.any(|tag| tag["key"] == "outcome" && tag["value"]["stringValue"] == "unconfirmed")
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
185
codex-rs/cli/tests/debug_clear_memories.rs
Normal file
185
codex-rs/cli/tests/debug_clear_memories.rs
Normal file
@@ -0,0 +1,185 @@
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::Result;
|
||||
use codex_state::StateRuntime;
|
||||
use codex_utils_absolute_path::test_support::PathExt;
|
||||
use predicates::str::contains;
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
|
||||
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
cmd.env("CODEX_HOME", codex_home);
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn debug_clear_memories_resets_state_and_removes_memory_dir() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let sqlite = codex_state::SqliteConfig::new_for_testing(codex_home.path().abs());
|
||||
let runtime = StateRuntime::init(sqlite.clone(), "test-provider".to_string()).await?;
|
||||
runtime.close().await;
|
||||
|
||||
let thread_id = "00000000-0000-0000-0000-000000000123";
|
||||
let db_path = sqlite.state_db_path();
|
||||
let pool = sqlite.open_read_write_pool(&db_path).await?;
|
||||
let memories_db_path = sqlite.memories_db_path();
|
||||
let memories_pool = sqlite.open_read_write_pool(&memories_db_path).await?;
|
||||
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO threads (
|
||||
id,
|
||||
rollout_path,
|
||||
created_at,
|
||||
updated_at,
|
||||
source,
|
||||
agent_nickname,
|
||||
agent_role,
|
||||
model_provider,
|
||||
cwd,
|
||||
cli_version,
|
||||
title,
|
||||
sandbox_policy,
|
||||
approval_mode,
|
||||
tokens_used,
|
||||
first_user_message,
|
||||
archived,
|
||||
archived_at,
|
||||
git_sha,
|
||||
git_branch,
|
||||
git_origin_url,
|
||||
memory_mode
|
||||
) VALUES (?, ?, 1, 1, 'cli', NULL, NULL, 'test-provider', ?, '', '', 'read-only', 'on-request', 0, '', 0, NULL, NULL, NULL, NULL, 'enabled')
|
||||
"#,
|
||||
)
|
||||
.bind(thread_id)
|
||||
.bind(codex_home.path().join("session.jsonl").display().to_string())
|
||||
.bind(codex_home.path().display().to_string())
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO stage1_outputs (
|
||||
thread_id,
|
||||
source_updated_at,
|
||||
raw_memory,
|
||||
rollout_summary,
|
||||
generated_at,
|
||||
rollout_slug,
|
||||
usage_count,
|
||||
last_usage,
|
||||
selected_for_phase2,
|
||||
selected_for_phase2_source_updated_at
|
||||
) VALUES (?, 1, 'raw', 'summary', 1, NULL, 0, NULL, 0, NULL)
|
||||
"#,
|
||||
)
|
||||
.bind(thread_id)
|
||||
.execute(&memories_pool)
|
||||
.await?;
|
||||
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO jobs (
|
||||
kind,
|
||||
job_key,
|
||||
status,
|
||||
worker_id,
|
||||
ownership_token,
|
||||
started_at,
|
||||
finished_at,
|
||||
lease_until,
|
||||
retry_at,
|
||||
retry_remaining,
|
||||
last_error,
|
||||
input_watermark,
|
||||
last_success_watermark
|
||||
) VALUES
|
||||
('memory_stage1', ?, 'completed', NULL, NULL, NULL, NULL, NULL, NULL, 3, NULL, NULL, 1),
|
||||
('memory_consolidate_global', 'global', 'completed', NULL, NULL, NULL, NULL, NULL, NULL, 3, NULL, NULL, 1)
|
||||
"#,
|
||||
)
|
||||
.bind(thread_id)
|
||||
.execute(&memories_pool)
|
||||
.await?;
|
||||
|
||||
let memory_root = codex_home.path().join("memories");
|
||||
std::fs::create_dir_all(&memory_root)?;
|
||||
std::fs::write(memory_root.join("memory_summary.md"), "stale memory")?;
|
||||
pool.close().await;
|
||||
memories_pool.close().await;
|
||||
|
||||
let mut cmd = codex_command(codex_home.path())?;
|
||||
cmd.args(["debug", "clear-memories"])
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(contains("Cleared memory state"));
|
||||
|
||||
let pool = sqlite.open_read_write_pool(&memories_db_path).await?;
|
||||
let stage1_outputs_count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM stage1_outputs")
|
||||
.fetch_one(&pool)
|
||||
.await?;
|
||||
assert_eq!(stage1_outputs_count, 0);
|
||||
|
||||
let memory_jobs_count: i64 = sqlx::query_scalar(
|
||||
"SELECT COUNT(*) FROM jobs WHERE kind = 'memory_stage1' OR kind = 'memory_consolidate_global'",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await?;
|
||||
assert_eq!(memory_jobs_count, 0);
|
||||
assert!(memory_root.exists());
|
||||
assert_eq!(std::fs::read_dir(memory_root)?.count(), 0);
|
||||
pool.close().await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn debug_clear_memories_resets_memories_db_without_state_db() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let sqlite = codex_state::SqliteConfig::new_for_testing(codex_home.path().abs());
|
||||
let runtime = StateRuntime::init(sqlite.clone(), "test-provider".to_string()).await?;
|
||||
runtime.close().await;
|
||||
|
||||
let db_path = sqlite.state_db_path();
|
||||
let memories_db_path = sqlite.memories_db_path();
|
||||
let memories_pool = sqlite.open_read_write_pool(&memories_db_path).await?;
|
||||
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO stage1_outputs (
|
||||
thread_id,
|
||||
source_updated_at,
|
||||
raw_memory,
|
||||
rollout_summary,
|
||||
generated_at,
|
||||
rollout_slug,
|
||||
usage_count,
|
||||
last_usage,
|
||||
selected_for_phase2,
|
||||
selected_for_phase2_source_updated_at
|
||||
) VALUES ('00000000-0000-0000-0000-000000000123', 1, 'raw', 'summary', 1, NULL, 0, NULL, 0, NULL)
|
||||
"#,
|
||||
)
|
||||
.execute(&memories_pool)
|
||||
.await?;
|
||||
|
||||
memories_pool.close().await;
|
||||
std::fs::remove_file(&db_path)?;
|
||||
|
||||
let mut cmd = codex_command(codex_home.path())?;
|
||||
cmd.args(["debug", "clear-memories"])
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(contains("Cleared memory state"));
|
||||
|
||||
let pool = sqlite.open_read_write_pool(&memories_db_path).await?;
|
||||
let stage1_outputs_count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM stage1_outputs")
|
||||
.fetch_one(&pool)
|
||||
.await?;
|
||||
assert_eq!(stage1_outputs_count, 0);
|
||||
pool.close().await;
|
||||
assert!(!db_path.exists());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
40
codex-rs/cli/tests/debug_models.rs
Normal file
40
codex-rs/cli/tests/debug_models.rs
Normal file
@@ -0,0 +1,40 @@
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::Result;
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
|
||||
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
cmd.env("CODEX_HOME", codex_home);
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_models_bundled_prints_json() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let mut cmd = codex_command(codex_home.path())?;
|
||||
let output = cmd.args(["debug", "models", "--bundled"]).output()?;
|
||||
|
||||
assert!(output.status.success());
|
||||
let stdout = String::from_utf8(output.stdout)?;
|
||||
let value: serde_json::Value = serde_json::from_str(&stdout)?;
|
||||
assert!(value["models"].is_array());
|
||||
assert!(!value["models"].as_array().unwrap_or(&Vec::new()).is_empty());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_models_default_prints_json_without_auth() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let mut cmd = codex_command(codex_home.path())?;
|
||||
let output = cmd.args(["debug", "models"]).output()?;
|
||||
|
||||
assert!(output.status.success());
|
||||
let stdout = String::from_utf8(output.stdout)?;
|
||||
let value: serde_json::Value = serde_json::from_str(&stdout)?;
|
||||
assert!(value["models"].is_array());
|
||||
assert!(!value["models"].as_array().unwrap_or(&Vec::new()).is_empty());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
17
codex-rs/cli/tests/delete.rs
Normal file
17
codex-rs/cli/tests/delete.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
use predicates::prelude::*;
|
||||
|
||||
#[test]
|
||||
fn missing_session_fails_before_delete_confirmation() -> anyhow::Result<()> {
|
||||
let codex_home = tempfile::tempdir()?;
|
||||
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
cmd.env("CODEX_HOME", codex_home.path())
|
||||
.args(["delete", "123e4567-e89b-12d3-a456-426614174000"]);
|
||||
|
||||
cmd.assert()
|
||||
.failure()
|
||||
.stderr(predicate::str::contains(
|
||||
"No active or archived session found matching",
|
||||
))
|
||||
.stderr(predicate::str::contains("cannot confirm").not());
|
||||
Ok(())
|
||||
}
|
||||
463
codex-rs/cli/tests/doctor_enterprise_network.rs
Normal file
463
codex-rs/cli/tests/doctor_enterprise_network.rs
Normal file
@@ -0,0 +1,463 @@
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
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;
|
||||
use regex_lite::Regex;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
async fn local_provider() -> Result<(MockServer, TempDir)> {
|
||||
let server = MockServer::start().await;
|
||||
for (request_method, request_path, status) in
|
||||
[("HEAD", "/v1/responses", 200), ("GET", "/v1/models", 401)]
|
||||
{
|
||||
Mock::given(method(request_method))
|
||||
.and(path(request_path))
|
||||
.respond_with(ResponseTemplate::new(status).insert_header("x-request-id", "fixture-id"))
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
let home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!(
|
||||
"cli_auth_credentials_store = \"ephemeral\"\ncheck_for_update_on_startup = false\nmodel_provider = \"local\"\n[model_providers.local]\nname = \"local\"\nbase_url = \"{}/v1\"\nwire_api = \"responses\"\n",
|
||||
server.uri()
|
||||
),
|
||||
)?;
|
||||
Ok((server, home))
|
||||
}
|
||||
|
||||
fn local_command(home: &TempDir) -> Result<Command> {
|
||||
let mut command = Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
command
|
||||
.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")
|
||||
.stdin(Stdio::null());
|
||||
for name in [
|
||||
"HTTP_PROXY",
|
||||
"HTTPS_PROXY",
|
||||
"ALL_PROXY",
|
||||
"http_proxy",
|
||||
"https_proxy",
|
||||
"all_proxy",
|
||||
"CODEX_ACCESS_TOKEN",
|
||||
"CODEX_API_KEY",
|
||||
"OPENAI_API_KEY",
|
||||
"CODEX_CA_CERTIFICATE",
|
||||
"SSL_CERT_FILE",
|
||||
"OPENAI_WORKLOAD_IDENTITY_CONTEXT",
|
||||
"OPENAI_IDENTITY_TOKEN_FILE",
|
||||
"OPENAI_FEDERATION_RULE_ID",
|
||||
] {
|
||||
command.env_remove(name);
|
||||
}
|
||||
Ok(command)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn network_only_selects_checks_without_database_or_mcp_scans() -> Result<()> {
|
||||
let (server, home) = local_provider().await?;
|
||||
Mock::given(path("/unrelated-mcp"))
|
||||
.respond_with(ResponseTemplate::new(200))
|
||||
.expect(0)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let sqlite =
|
||||
SqliteConfig::new_for_testing(AbsolutePathBuf::try_from(home.path().to_path_buf())?);
|
||||
let database = sqlite.logs_db_path();
|
||||
std::fs::write(&database, "not a SQLite database")?;
|
||||
let mcp_url = format!("{}/unrelated-mcp", server.uri());
|
||||
let output = local_command(&home)?
|
||||
.args(["doctor", "--network-only", "--json", "--all", "--feedback"])
|
||||
.arg("-c")
|
||||
.arg(format!("mcp_servers.unrelated.url={mcp_url:?}"))
|
||||
.output()?;
|
||||
let report: Value = serde_json::from_slice(&output.stdout)?;
|
||||
assert!(output.status.success(), "{report:#}");
|
||||
let checks = report["checks"].as_object().unwrap();
|
||||
assert_eq!(
|
||||
checks.keys().map(String::as_str).collect::<Vec<_>>(),
|
||||
vec![
|
||||
"config.load",
|
||||
"network.env",
|
||||
"network.provider_reachability",
|
||||
"network.websocket_reachability",
|
||||
]
|
||||
);
|
||||
assert_eq!(std::fs::read_to_string(database)?, "not a SQLite database");
|
||||
server.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn network_only_reports_recoverable_config_warnings_and_effective_config() -> Result<()> {
|
||||
let (_server, home) = local_provider().await?;
|
||||
let baseline_output = local_command(&home)?
|
||||
.args(["doctor", "--network-only", "--json"])
|
||||
.output()?;
|
||||
let baseline_report: Value = serde_json::from_slice(&baseline_output.stdout)?;
|
||||
assert!(baseline_output.status.success(), "{baseline_report:#}");
|
||||
let baseline_warning_count =
|
||||
baseline_report["checks"]["config.load"]["details"]["startup warnings"]
|
||||
.as_str()
|
||||
.unwrap_or("0")
|
||||
.parse::<usize>()?;
|
||||
let config_path = home.path().join("config.toml");
|
||||
let config = std::fs::read_to_string(&config_path)?;
|
||||
std::fs::write(
|
||||
config_path,
|
||||
format!("{config}\n[otel.span_attributes]\n\"\" = \"missing-key\"\n"),
|
||||
)?;
|
||||
let output = local_command(&home)?
|
||||
.args(["doctor", "--network-only", "--json"])
|
||||
.output()?;
|
||||
let report: Value = serde_json::from_slice(&output.stdout)?;
|
||||
assert!(output.status.success(), "{report:#}");
|
||||
let config_check = &report["checks"]["config.load"];
|
||||
let warning_count = config_check["details"]["startup warnings"]
|
||||
.as_str()
|
||||
.context("missing startup-warning count")?
|
||||
.parse::<usize>()?;
|
||||
let warnings = &config_check["details"]["startup warning"];
|
||||
let startup_warning = std::iter::once(warnings)
|
||||
.chain(warnings.as_array().into_iter().flatten())
|
||||
.filter_map(Value::as_str)
|
||||
.find(|warning| warning.starts_with("Ignoring invalid `otel.span_attributes` config"))
|
||||
.context("missing recoverable OTEL config warning")?;
|
||||
let check_statuses = report["checks"]
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|(id, check)| (id.clone(), check["status"].clone()))
|
||||
.collect::<serde_json::Map<_, _>>();
|
||||
assert_eq!(
|
||||
json!({
|
||||
"overallStatus": report["overallStatus"],
|
||||
"checkStatuses": check_statuses,
|
||||
"config": {
|
||||
"summary": config_check["summary"],
|
||||
"scope": config_check["details"]["configuration scope"],
|
||||
"provider": config_check["details"]["model provider"],
|
||||
"startupWarnings": warning_count,
|
||||
"startupWarning": startup_warning,
|
||||
},
|
||||
}),
|
||||
json!({
|
||||
"overallStatus": "warning",
|
||||
"checkStatuses": {
|
||||
"config.load": "warning",
|
||||
"network.env": "ok",
|
||||
"network.provider_reachability": "ok",
|
||||
"network.websocket_reachability": "ok",
|
||||
},
|
||||
"config": {
|
||||
"summary": "config loaded",
|
||||
"scope": "invocation config, including cloud-managed policy",
|
||||
"provider": "local",
|
||||
"startupWarnings": baseline_warning_count + 1,
|
||||
"startupWarning": "Ignoring invalid `otel.span_attributes` config: configured span attribute key must not be empty",
|
||||
},
|
||||
})
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn network_only_config_failure_does_not_guess_probe_targets() -> Result<()> {
|
||||
let proxy = MockServer::start().await;
|
||||
let home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
"model_provider = sk-config-credential-fixture\n",
|
||||
)?;
|
||||
let output = local_command(&home)?
|
||||
.args(["doctor", "--network-only", "--json"])
|
||||
.env("HTTP_PROXY", proxy.uri())
|
||||
.env("HTTPS_PROXY", proxy.uri())
|
||||
.output()?;
|
||||
assert_eq!(output.status.code(), Some(1));
|
||||
assert!(!String::from_utf8_lossy(&output.stdout).contains("sk-config-credential-fixture"));
|
||||
let report: Value = serde_json::from_slice(&output.stdout)?;
|
||||
assert_eq!(report["checks"].as_object().unwrap().len(), 1);
|
||||
assert_eq!(report["checks"]["config.load"]["status"], "fail");
|
||||
assert_eq!(
|
||||
report["checks"]["config.load"]["details"]["network diagnostics"],
|
||||
"effective network configuration is unavailable"
|
||||
);
|
||||
assert!(proxy.received_requests().await.unwrap().is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn network_only_human_output() -> Result<()> {
|
||||
let (_server, home) = local_provider().await?;
|
||||
let output = local_command(&home)?
|
||||
.args([
|
||||
"doctor",
|
||||
"--network-only",
|
||||
"--summary",
|
||||
"--ascii",
|
||||
"--no-color",
|
||||
])
|
||||
.output()?;
|
||||
let stdout = String::from_utf8(output.stdout)?;
|
||||
assert!(output.status.success(), "{stdout}");
|
||||
insta::assert_snapshot!("network_only_human_output", stdout);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn network_only_config_failure_human_output() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
"model_provider = sk-config-credential-fixture\n",
|
||||
)?;
|
||||
let output = local_command(&home)?
|
||||
.args(["doctor", "--network-only", "--all", "--ascii", "--no-color"])
|
||||
.output()?;
|
||||
let stdout = String::from_utf8(output.stdout)?;
|
||||
assert_eq!(output.status.code(), Some(1));
|
||||
assert!(!stdout.contains("sk-config-credential-fixture"));
|
||||
// Config loading may canonicalize the directory, rendering may shorten it,
|
||||
// and Windows uses backslashes.
|
||||
// Normalize the rendered config-file row while retaining its label and filename.
|
||||
let file_row = Regex::new(r"(?m)^( file +).+[\\/]config\.toml$")?;
|
||||
assert!(file_row.is_match(&stdout), "{stdout}");
|
||||
let stdout = file_row.replace_all(&stdout, "${1}<CODEX_HOME>/config.toml");
|
||||
insta::assert_snapshot!("network_only_config_failure_human_output", stdout);
|
||||
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;
|
||||
for (request_method, request_path) in [("HEAD", "/v1/responses"), ("GET", "/v1/models")] {
|
||||
Mock::given(method(request_method))
|
||||
.and(path(request_path))
|
||||
.respond_with(ResponseTemplate::new(200))
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
|
||||
let codex_home = TempDir::new()?;
|
||||
let certificate = codex_home.path().join("invalid-ca.pem");
|
||||
std::fs::write(&certificate, "not a certificate")?;
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
format!(
|
||||
"model_provider = \"local\"\n[model_providers.local]\nname = \"local\"\nbase_url = \"{}/v1\"\nwire_api = \"responses\"\n",
|
||||
server.uri()
|
||||
),
|
||||
)?;
|
||||
for sandbox in [None, Some("seatbelt")] {
|
||||
let mut command = Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
command
|
||||
.args(["doctor", "--json"])
|
||||
.env("CODEX_HOME", codex_home.path())
|
||||
.env("CODEX_CA_CERTIFICATE", &certificate)
|
||||
.stdin(Stdio::null());
|
||||
if let Some(sandbox) = sandbox {
|
||||
command
|
||||
.env("CODEX_SANDBOX", sandbox)
|
||||
.env("HTTP_PROXY", "http://127.0.0.1:1")
|
||||
.env("http_proxy", "http://127.0.0.1:1")
|
||||
.env("HTTPS_PROXY", "http://127.0.0.1:1")
|
||||
.env("https_proxy", "http://127.0.0.1:1")
|
||||
.env("NO_PROXY", "")
|
||||
.env("no_proxy", "");
|
||||
} else {
|
||||
command
|
||||
.env("NO_PROXY", "127.0.0.1,localhost")
|
||||
.env("no_proxy", "127.0.0.1,localhost");
|
||||
}
|
||||
let output = command
|
||||
.output()
|
||||
.context("failed to run the doctor with an invalid custom CA")?;
|
||||
let report: Value = serde_json::from_slice(&output.stdout)?;
|
||||
|
||||
assert!(
|
||||
report["checks"]["network.provider_reachability"]["details"]["local API inference URL"]
|
||||
.as_str()
|
||||
.is_some_and(|detail| detail.ends_with("reachable (HTTP 200)"))
|
||||
);
|
||||
}
|
||||
server.verify().await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn doctor_reports_macos_system_proxy_configuration_and_policy() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let report = doctor_report(codex_home.path())?;
|
||||
let details = &report["checks"]["network.env"]["details"];
|
||||
|
||||
assert_eq!(details["respect system proxy"], json!("disabled"));
|
||||
assert!(matches!(
|
||||
details["system proxy"].as_str(),
|
||||
Some("automatic (PAC)" | "manual" | "direct" | "unavailable")
|
||||
));
|
||||
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
"[features]\nrespect_system_proxy = true\n",
|
||||
)?;
|
||||
let report = doctor_report(codex_home.path())?;
|
||||
assert_eq!(
|
||||
report["checks"]["network.env"]["details"]["respect system proxy"],
|
||||
json!("enabled")
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn doctor_report(codex_home: &Path) -> Result<Value> {
|
||||
let output = Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
|
||||
.args(["doctor", "--json"])
|
||||
.env("CODEX_HOME", codex_home)
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
.context("failed to run the doctor")?;
|
||||
|
||||
serde_json::from_slice(&output.stdout).context("doctor did not emit a valid json report")
|
||||
}
|
||||
689
codex-rs/cli/tests/doctor_path_safety.rs
Normal file
689
codex-rs/cli/tests/doctor_path_safety.rs
Normal file
@@ -0,0 +1,689 @@
|
||||
//! Black-box coverage for safe diagnostic execution and config error reporting.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
#[cfg(unix)]
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use app_test_support::TestAppServer;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_config::loader::project_trust_key;
|
||||
use codex_state::SqliteConfig;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_cargo_bin::copy_executable;
|
||||
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::TcpListener;
|
||||
use tokio::time::timeout;
|
||||
|
||||
struct Fixture {
|
||||
root: TempDir,
|
||||
program: PathBuf,
|
||||
workspace: PathBuf,
|
||||
home: PathBuf,
|
||||
marker: PathBuf,
|
||||
path: OsString,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Result<Self> {
|
||||
let root = TempDir::new()?;
|
||||
let home = root.path().join("home");
|
||||
std::fs::create_dir(&home)?;
|
||||
// Cargo-built paths deliberately ignore npm provenance. Launch outside
|
||||
// target/ so this fixture also exercises the packaged-install checks.
|
||||
let program = root
|
||||
.path()
|
||||
.join(format!("codex{}", std::env::consts::EXE_SUFFIX));
|
||||
let source = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
// Hard-link setup and teardown invalidate other tests' Rosetta translations.
|
||||
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
|
||||
{
|
||||
copy_executable(&source, &program)?;
|
||||
// Translate the fixture before the timed diagnostic command.
|
||||
anyhow::ensure!(
|
||||
std::process::Command::new(&program)
|
||||
.env("CODEX_HOME", &home)
|
||||
.arg("--version")
|
||||
.output()?
|
||||
.status
|
||||
.success(),
|
||||
"failed to prepare diagnostic test executable"
|
||||
);
|
||||
}
|
||||
#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]
|
||||
if std::fs::hard_link(&source, &program).is_err() {
|
||||
copy_executable(&source, &program)?;
|
||||
}
|
||||
let workspace = root.path().join("workspace");
|
||||
let bin = workspace.join("node_modules/.bin");
|
||||
let marker = root.path().join("helper-ran");
|
||||
std::fs::create_dir_all(&bin)?;
|
||||
std::fs::create_dir_all(workspace.join(".git"))?;
|
||||
std::fs::write(
|
||||
home.join("config.toml"),
|
||||
r#"
|
||||
cli_auth_credentials_store = "file"
|
||||
check_for_update_on_startup = false
|
||||
model_provider = "local"
|
||||
[analytics]
|
||||
enabled = false
|
||||
[model_providers.local]
|
||||
name = "local test"
|
||||
base_url = "http://127.0.0.1:9/v1"
|
||||
wire_api = "responses"
|
||||
"#,
|
||||
)?;
|
||||
for name in [
|
||||
"zellij", "tmux", "which", "where", "npm", "rg", "git", "curl", "cmd.exe",
|
||||
] {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let executable = bin.join(name);
|
||||
codex_utils_cargo_bin::write_executable(
|
||||
&executable,
|
||||
"#!/bin/sh\nprintf 'helper ran\\n' >> \"$CODEX_TEST_HELPER_MARKER\"\nexit 0\n",
|
||||
)?;
|
||||
}
|
||||
#[cfg(windows)]
|
||||
std::fs::write(
|
||||
bin.join(format!("{name}.cmd")),
|
||||
"@echo helper ran>>\"%CODEX_TEST_HELPER_MARKER%\"\r\n@exit /b 0\r\n",
|
||||
)?;
|
||||
}
|
||||
// Windows selects rg.exe explicitly, so rg.cmd cannot satisfy discovery.
|
||||
// An invalid image still counts as found: doctor must not execute it.
|
||||
#[cfg(windows)]
|
||||
std::fs::write(bin.join("rg.exe"), "not an executable image")?;
|
||||
let path = std::env::join_paths(std::iter::once(bin).chain(std::env::split_paths(
|
||||
&std::env::var_os("PATH").unwrap_or_default(),
|
||||
)))?;
|
||||
Ok(Self {
|
||||
root,
|
||||
program,
|
||||
workspace,
|
||||
home,
|
||||
marker,
|
||||
path,
|
||||
})
|
||||
}
|
||||
|
||||
fn command(&self) -> Result<assert_cmd::Command> {
|
||||
let mut command = assert_cmd::Command::new(&self.program);
|
||||
command
|
||||
.current_dir(&self.workspace)
|
||||
.env("CODEX_HOME", &self.home)
|
||||
.env("HOME", self.root.path())
|
||||
.env("PATH", &self.path)
|
||||
.env("CODEX_TEST_HELPER_MARKER", &self.marker)
|
||||
.env("CODEX_MANAGED_BY_NPM", "1")
|
||||
.env(
|
||||
"CODEX_MANAGED_PACKAGE_ROOT",
|
||||
self.workspace.join("node_modules/@openai/codex"),
|
||||
)
|
||||
.env(
|
||||
"CODEX_APP_SERVER_MANAGED_CONFIG_PATH",
|
||||
self.home.join("managed_config.toml"),
|
||||
)
|
||||
.env("HTTPS_PROXY", "http://127.0.0.1:9")
|
||||
.env("HTTP_PROXY", "http://127.0.0.1:9")
|
||||
.env("ALL_PROXY", "http://127.0.0.1:9")
|
||||
.env("https_proxy", "http://127.0.0.1:9")
|
||||
.env("http_proxy", "http://127.0.0.1:9")
|
||||
.env("all_proxy", "http://127.0.0.1:9")
|
||||
.env("NO_PROXY", "127.0.0.1,localhost")
|
||||
.env("no_proxy", "127.0.0.1,localhost")
|
||||
.env_remove("TMUX")
|
||||
.env_remove("TMUX_PANE")
|
||||
.env_remove("ZELLIJ_VERSION")
|
||||
.env_remove("ZELLIJ_SESSION_NAME")
|
||||
.env_remove("TERM_PROGRAM")
|
||||
.env("TERM", "dumb")
|
||||
.env("ZELLIJ", "0")
|
||||
.timeout(Duration::from_secs(/*secs*/ 45));
|
||||
Ok(command)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(
|
||||
windows,
|
||||
ignore = "Windows doctor fixture does not discover the synthetic Git executable"
|
||||
)]
|
||||
fn startup_and_doctor_do_not_execute_path_helpers() -> Result<()> {
|
||||
let fixture = Fixture::new()?;
|
||||
// Non-TTY dumb-terminal startup exits immediately after terminal detection.
|
||||
fixture.command()?.assert().failure();
|
||||
assert!(!fixture.marker.exists(), "startup executed a PATH helper");
|
||||
|
||||
for args in [
|
||||
vec!["doctor", "--json"],
|
||||
vec!["doctor", "--json", "--feedback"],
|
||||
] {
|
||||
let mut command = fixture.command()?;
|
||||
command
|
||||
.args(args)
|
||||
.env("TMUX", "test-tmux")
|
||||
.env("TERM_PROGRAM", "tmux");
|
||||
let output = command.output()?;
|
||||
let report: Value = serde_json::from_slice(&output.stdout)?;
|
||||
assert_eq!(
|
||||
report["checks"]["installation"]["details"]["managed by npm"],
|
||||
"true"
|
||||
);
|
||||
assert_eq!(report["checks"]["runtime.search"]["status"], "ok");
|
||||
assert_eq!(
|
||||
report["checks"]["runtime.search"]["details"]["search command path"],
|
||||
fixture
|
||||
.workspace
|
||||
.join("node_modules/.bin")
|
||||
.join(format!("rg{}", std::env::consts::EXE_SUFFIX))
|
||||
.display()
|
||||
.to_string()
|
||||
);
|
||||
assert_eq!(
|
||||
report["checks"]["git.environment"]["summary"],
|
||||
"git executable found; execution not verified"
|
||||
);
|
||||
assert!(!fixture.marker.exists(), "doctor executed a PATH helper");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_interactive_dumb_terminal_preserves_other_doctor_failures() -> Result<()> {
|
||||
let fixture = Fixture::new()?;
|
||||
let output = fixture
|
||||
.command()?
|
||||
.args(["doctor", "--json"])
|
||||
// Explicit identity takes precedence over inherited terminal-specific variables.
|
||||
.env("TERM_PROGRAM", "dumb")
|
||||
.env_remove("TERMINFO")
|
||||
.env_remove("TERMINFO_DIRS")
|
||||
.output()?;
|
||||
// The fixture's provider is unreachable, regardless of terminal capabilities.
|
||||
assert_eq!(output.status.code(), Some(1));
|
||||
let report: Value = serde_json::from_slice(&output.stdout)?;
|
||||
assert_eq!(report["checks"]["terminal.env"]["status"], "warning");
|
||||
assert_eq!(report["overallStatus"], "fail");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doctor_reports_failed_database_paths() -> Result<()> {
|
||||
let fixture = Fixture::new()?;
|
||||
let sqlite_home = fixture.root.path().join("sqlite");
|
||||
std::fs::create_dir(&sqlite_home)?;
|
||||
let sqlite = SqliteConfig::new_for_testing(AbsolutePathBuf::try_from(sqlite_home.clone())?);
|
||||
let config_file = fixture.home.join("config.toml");
|
||||
let config = std::fs::read_to_string(&config_file)?;
|
||||
let sqlite_home = toml::Value::String(sqlite_home.display().to_string());
|
||||
std::fs::write(
|
||||
&config_file,
|
||||
format!("sqlite_home = {sqlite_home}\nlog_dir = {sqlite_home}\n{config}"),
|
||||
)?;
|
||||
|
||||
for (snapshot_name, failed_paths) in [
|
||||
("doctor_failed_log_database", vec![sqlite.logs_db_path()]),
|
||||
(
|
||||
"doctor_failed_multiple_databases",
|
||||
vec![sqlite.logs_db_path(), sqlite.goals_db_path()],
|
||||
),
|
||||
] {
|
||||
for path in &failed_paths {
|
||||
std::fs::write(path, "not a SQLite database")?;
|
||||
}
|
||||
let paths = failed_paths
|
||||
.iter()
|
||||
.map(|path| path.display().to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let noun = if failed_paths.len() == 1 {
|
||||
"database"
|
||||
} else {
|
||||
"databases"
|
||||
};
|
||||
let expected_cause = format!("{paths} {noun} failed integrity check");
|
||||
for args in [
|
||||
vec!["doctor", "--json"],
|
||||
vec!["doctor", "--json", "--feedback"],
|
||||
] {
|
||||
let output = fixture.command()?.args(args).output()?;
|
||||
assert_eq!(output.status.code(), Some(1));
|
||||
let report: Value = serde_json::from_slice(&output.stdout)?;
|
||||
assert_eq!(report["checks"]["state.paths"]["status"], "fail");
|
||||
assert_eq!(
|
||||
report["checks"]["state.paths"]["summary"],
|
||||
"state database integrity check failed"
|
||||
);
|
||||
assert_eq!(
|
||||
report["checks"]["state.paths"]["issues"][0]["cause"],
|
||||
expected_cause
|
||||
);
|
||||
}
|
||||
|
||||
for summary_only in [false, true] {
|
||||
let mut command = fixture.command()?;
|
||||
command.args(["doctor", "--ascii", "--no-color"]);
|
||||
if summary_only {
|
||||
command.arg("--summary");
|
||||
}
|
||||
let output = command.output()?;
|
||||
assert_eq!(output.status.code(), Some(1));
|
||||
let stdout = String::from_utf8(output.stdout)?;
|
||||
let state_row = stdout
|
||||
.lines()
|
||||
.filter(|line| {
|
||||
line.starts_with(" [XX] state ")
|
||||
|| (!summary_only
|
||||
&& line.starts_with(" -> Move the damaged SQLite database aside"))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
.replace(&fixture.root.path().display().to_string(), "FIXTURE")
|
||||
.replace('\\', "/");
|
||||
if summary_only {
|
||||
assert_eq!(
|
||||
state_row,
|
||||
format!(
|
||||
" [XX] state {}",
|
||||
expected_cause
|
||||
.replace(&fixture.root.path().display().to_string(), "FIXTURE")
|
||||
)
|
||||
.replace('\\', "/")
|
||||
);
|
||||
} else {
|
||||
insta::assert_snapshot!(snapshot_name, state_row);
|
||||
}
|
||||
}
|
||||
for path in &failed_paths {
|
||||
assert_eq!(std::fs::read_to_string(path)?, "not a SQLite database");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doctor_redacts_failed_database_paths_in_json() -> Result<()> {
|
||||
let fixture = Fixture::new()?;
|
||||
let sqlite_home = fixture.root.path().join("doctor-secret-sqlite");
|
||||
std::fs::create_dir(&sqlite_home)?;
|
||||
let sqlite = SqliteConfig::new_for_testing(AbsolutePathBuf::try_from(sqlite_home.clone())?);
|
||||
let config_file = fixture.home.join("config.toml");
|
||||
let config = std::fs::read_to_string(&config_file)?;
|
||||
let sqlite_home = toml::Value::String(sqlite_home.display().to_string());
|
||||
std::fs::write(
|
||||
&config_file,
|
||||
format!("sqlite_home = {sqlite_home}\nlog_dir = {sqlite_home}\n{config}"),
|
||||
)?;
|
||||
std::fs::write(sqlite.logs_db_path(), "not a SQLite database")?;
|
||||
|
||||
let output = fixture
|
||||
.command()?
|
||||
.args(["doctor", "--json", "--feedback"])
|
||||
.output()?;
|
||||
assert_eq!(output.status.code(), Some(1));
|
||||
let stdout = String::from_utf8(output.stdout)?;
|
||||
assert!(!stdout.contains("doctor-secret-sqlite"));
|
||||
let report: Value = serde_json::from_str(&stdout)?;
|
||||
assert_eq!(
|
||||
report["checks"]["state.paths"]["summary"],
|
||||
"state database integrity check failed"
|
||||
);
|
||||
assert_eq!(
|
||||
report["checks"]["state.paths"]["issues"][0]["cause"],
|
||||
"<redacted>"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doctor_reports_only_safe_config_error_metadata() -> Result<()> {
|
||||
let fixture = Fixture::new()?;
|
||||
let user_config_file = fixture.home.join("config.toml");
|
||||
let original = std::fs::read_to_string(&user_config_file)?;
|
||||
// macOS temp directories can use a symlinked path; trust the canonical workspace.
|
||||
let project_key = toml::Value::String(project_trust_key(&fixture.workspace));
|
||||
let original = format!("{original}\n[projects.{project_key}]\ntrust_level = \"trusted\"\n");
|
||||
let project_config_dir = fixture.workspace.join(".codex");
|
||||
std::fs::create_dir(&project_config_dir)?;
|
||||
for (snapshot_name, config_file, config) in [
|
||||
(
|
||||
"doctor_config_error_location",
|
||||
user_config_file.clone(),
|
||||
"custom_header = \"doctor-test-credential\" trailing\n".to_string(),
|
||||
),
|
||||
(
|
||||
"doctor_config_invalid_data",
|
||||
project_config_dir.join("config.toml"),
|
||||
"custom_header = \"doctor-test-credential\" trailing\n".to_string(),
|
||||
),
|
||||
(
|
||||
"doctor_config_not_found",
|
||||
user_config_file.clone(),
|
||||
original.replace(
|
||||
"model_provider = \"local\"",
|
||||
"model_provider = \"doctor-test-credential\"",
|
||||
),
|
||||
),
|
||||
(
|
||||
"doctor_config_invalid_data",
|
||||
user_config_file.clone(),
|
||||
original.replace(
|
||||
"wire_api = \"responses\"",
|
||||
"wire_api = \"responses\"\nhttp_headers = \"sk-proj-ABC123example\"",
|
||||
),
|
||||
),
|
||||
] {
|
||||
std::fs::write(&user_config_file, &original)?;
|
||||
std::fs::write(&config_file, config)?;
|
||||
for args in [
|
||||
vec!["doctor", "--json"],
|
||||
vec!["doctor", "--json", "--feedback"],
|
||||
] {
|
||||
let output = fixture.command()?.args(args).output()?;
|
||||
assert_eq!(output.status.code(), Some(1));
|
||||
let report: Value = serde_json::from_slice(&output.stdout)?;
|
||||
let mut check = report["checks"]["config.load"].clone();
|
||||
check
|
||||
.as_object_mut()
|
||||
.expect("config check")
|
||||
.remove("durationMs");
|
||||
if let Some(file) = check["details"]["file"].as_str() {
|
||||
check["details"]["file"] = Value::String(
|
||||
file.replace(
|
||||
&fixture.root.path().canonicalize()?.display().to_string(),
|
||||
"FIXTURE",
|
||||
)
|
||||
.replace(&fixture.root.path().display().to_string(), "FIXTURE")
|
||||
.replace('\\', "/"),
|
||||
);
|
||||
}
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(!stdout.contains("doctor-test-credential"));
|
||||
assert!(!stdout.contains("sk-proj-ABC123example"));
|
||||
// Keep snapshots stable across serde_json feature sets in Cargo and Bazel.
|
||||
check.sort_all_objects();
|
||||
insta::assert_snapshot!(snapshot_name, serde_json::to_string_pretty(&check)?);
|
||||
}
|
||||
std::fs::remove_file(config_file)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doctor_reports_configured_tui_mode() -> Result<()> {
|
||||
let fixture = Fixture::new()?;
|
||||
for (setting, expected) in [("true", "fullscreen"), ("false", "scrollback")] {
|
||||
let output = fixture
|
||||
.command()?
|
||||
.args(["-c", &format!("tui.fullscreen_transcript={setting}")])
|
||||
.args(["doctor", "--json"])
|
||||
.output()?;
|
||||
let report: Value = serde_json::from_slice(&output.stdout)?;
|
||||
assert_eq!(
|
||||
report["checks"]["config.load"]["details"]["configured TUI mode"],
|
||||
expected
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doctor_reports_configured_filesystem_paths() -> Result<()> {
|
||||
let fixture = Fixture::new()?;
|
||||
let config_file = fixture.home.join("config.toml");
|
||||
let original = std::fs::read_to_string(&config_file)?;
|
||||
let existing = fixture.workspace.join("probe-existing");
|
||||
let missing = fixture.workspace.join("probe-missing");
|
||||
std::fs::create_dir(&existing)?;
|
||||
let existing_key = toml::Value::String(existing.display().to_string());
|
||||
let missing_key = toml::Value::String(missing.display().to_string());
|
||||
std::fs::write(
|
||||
&config_file,
|
||||
format!(
|
||||
r#"default_permissions = "diagnostic"
|
||||
{original}
|
||||
[permissions.diagnostic]
|
||||
extends = ":read-only"
|
||||
[permissions.diagnostic.filesystem]
|
||||
{existing_key} = "read"
|
||||
{missing_key} = "write"
|
||||
"#
|
||||
),
|
||||
)?;
|
||||
let output = fixture.command()?.args(["doctor", "--json"]).output()?;
|
||||
let report: Value = serde_json::from_slice(&output.stdout)?;
|
||||
#[cfg(windows)]
|
||||
assert_eq!(report["checks"]["sandbox.filesystem_paths"]["status"], "ok");
|
||||
let mut details = report["checks"]["sandbox.filesystem_paths"]["details"].clone();
|
||||
// Snapshot outcomes and provenance independently of helper startup speed.
|
||||
details
|
||||
.as_object_mut()
|
||||
.expect("path details")
|
||||
.retain(|key, _| !key.ends_with(" latency"));
|
||||
let canonical_root = fixture.root.path().canonicalize()?;
|
||||
for value in details.as_object_mut().expect("path details").values_mut() {
|
||||
let detail = value
|
||||
.as_str()
|
||||
.expect("scalar path detail")
|
||||
.replace(&canonical_root.display().to_string(), "FIXTURE")
|
||||
.replace(&fixture.root.path().display().to_string(), "FIXTURE")
|
||||
.replace('\\', "/");
|
||||
*value = Value::String(detail);
|
||||
}
|
||||
let snapshot_name = if cfg!(windows) {
|
||||
"doctor_configured_filesystem_paths_windows"
|
||||
} else {
|
||||
"doctor_configured_filesystem_paths"
|
||||
};
|
||||
insta::assert_snapshot!(snapshot_name, serde_json::to_string_pretty(&details)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filesystem_probe_does_not_load_configuration() -> Result<()> {
|
||||
let fixture = Fixture::new()?;
|
||||
std::fs::write(fixture.home.join("config.toml"), "invalid TOML = [")?;
|
||||
for (path, expected) in [
|
||||
(&fixture.workspace, 0),
|
||||
(&fixture.workspace.join("missing"), 2),
|
||||
] {
|
||||
let output = fixture
|
||||
.command()?
|
||||
.args(["doctor", "--probe-filesystem-path"])
|
||||
.arg(path)
|
||||
.output()?;
|
||||
assert_eq!(
|
||||
output.status.code(),
|
||||
Some(if cfg!(windows) { 5 } else { expected })
|
||||
);
|
||||
assert!(output.stdout.is_empty());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn interactive_tmux_startup_does_not_execute_workspace_helpers() -> Result<()> {
|
||||
let fixture = Fixture::new()?;
|
||||
std::fs::create_dir(fixture.workspace.join(".codex"))?;
|
||||
let command = fixture.command()?;
|
||||
let mut env: std::collections::HashMap<String, String> = std::env::vars().collect();
|
||||
for (key, value) in command.get_envs() {
|
||||
let key = key.to_string_lossy().into_owned();
|
||||
if let Some(value) = value {
|
||||
env.insert(key, value.to_string_lossy().into_owned());
|
||||
} else {
|
||||
env.remove(&key);
|
||||
}
|
||||
}
|
||||
env.insert("TERM".to_string(), "xterm-256color".to_string());
|
||||
env.insert("TERM_PROGRAM".to_string(), "tmux".to_string());
|
||||
env.insert("TMUX".to_string(), "test-tmux".to_string());
|
||||
env.insert(
|
||||
"CODEX_TUI_DISABLE_KEYBOARD_ENHANCEMENT".to_string(),
|
||||
"0".to_string(),
|
||||
);
|
||||
env.insert(
|
||||
"GHOSTTY_RESOURCES_DIR".to_string(),
|
||||
"/test/ghostty".to_string(),
|
||||
);
|
||||
let spawned = codex_utils_pty::spawn_pty_process(
|
||||
fixture.program.to_str().unwrap(),
|
||||
&["--no-daemon".to_string()],
|
||||
&fixture.workspace,
|
||||
&env,
|
||||
/*arg0*/ &None,
|
||||
codex_utils_pty::TerminalSize {
|
||||
rows: 40,
|
||||
cols: 120,
|
||||
},
|
||||
codex_utils_pty::ChildFds::Inherited(&[]),
|
||||
)
|
||||
.await?;
|
||||
let session = spawned.session;
|
||||
let mut output_rx = spawned.stdout_rx;
|
||||
let writer = session.writer_sender();
|
||||
let mut output = String::new();
|
||||
let ansi = regex_lite::Regex::new(r"\x1b\[[0-?]*[ -/]*[@-~]")?;
|
||||
let ready = timeout(Duration::from_secs(/*secs*/ 45), async {
|
||||
while let Some(bytes) = output_rx.recv().await {
|
||||
let chunk = String::from_utf8_lossy(&bytes);
|
||||
output.push_str(&chunk);
|
||||
if chunk.contains("\x1b[6n") {
|
||||
writer.send(b"\x1b[1;1R".to_vec()).await?;
|
||||
}
|
||||
if chunk.contains("\x1b[c") {
|
||||
writer.send(b"\x1b[?1;2c".to_vec()).await?;
|
||||
}
|
||||
// Ratatui can position over spaces instead of writing them.
|
||||
let text: String = ansi
|
||||
.replace_all(&output, "")
|
||||
.chars()
|
||||
.filter(|character| !character.is_whitespace())
|
||||
.collect();
|
||||
if text.contains("Trustthisfolder?") {
|
||||
return Ok::<_, anyhow::Error>(());
|
||||
}
|
||||
}
|
||||
anyhow::bail!("TUI exited before trust prompt")
|
||||
})
|
||||
.await;
|
||||
ready.map_err(|_| {
|
||||
anyhow::anyhow!(
|
||||
"trust prompt timed out: {}",
|
||||
output.chars().take(/*n*/ 4000).collect::<String>()
|
||||
)
|
||||
})??;
|
||||
// The first Ctrl+C leaves the untrusted workspace for the command center.
|
||||
// Keep sending Ctrl+C so the TUI exits even if the first draw discarded input.
|
||||
let mut quit_retry = tokio::time::interval(Duration::from_millis(/*millis*/ 250));
|
||||
let mut exit_rx = spawned.exit_rx;
|
||||
timeout(Duration::from_secs(/*secs*/ 10), async {
|
||||
loop {
|
||||
tokio::select! {
|
||||
result = &mut exit_rx => return result,
|
||||
_ = quit_retry.tick() => {
|
||||
let _ = writer.send(b"\x03".to_vec()).await;
|
||||
}
|
||||
Some(_) = output_rx.recv() => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"TUI did not exit after declining directory trust: {}",
|
||||
output.chars().take(/*n*/ 4000).collect::<String>()
|
||||
)
|
||||
})??;
|
||||
assert!(
|
||||
output.contains("\x1b[>5u"),
|
||||
"expected safe Ghostty/tmux keyboard flags: {output}"
|
||||
);
|
||||
assert!(
|
||||
!fixture.marker.exists(),
|
||||
"interactive startup executed a workspace helper"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_with_logs_does_not_execute_path_helpers() -> Result<()> {
|
||||
let fixture = Fixture::new()?;
|
||||
let proxy = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let proxy_uri = format!("http://{}", proxy.local_addr()?);
|
||||
// Reject all outbound traffic locally, including the final feedback upload.
|
||||
let proxy_task = tokio::spawn(async move {
|
||||
while let Ok((stream, _)) = proxy.accept().await {
|
||||
let mut stream = BufReader::new(stream);
|
||||
let mut request = String::new();
|
||||
if stream.read_line(&mut request).await.is_ok() {
|
||||
let _ = stream.get_mut().write_all(b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").await;
|
||||
}
|
||||
}
|
||||
});
|
||||
let path = fixture.path.to_string_lossy();
|
||||
let marker = fixture.marker.to_string_lossy();
|
||||
let home = fixture.root.path().to_string_lossy();
|
||||
let package_root = fixture.workspace.join("node_modules/@openai/codex");
|
||||
let package_root = package_root.to_string_lossy();
|
||||
let mut app_server = TestAppServer::builder()
|
||||
.with_program(&fixture.program)
|
||||
.with_codex_home(&fixture.home)
|
||||
// The CLI does not accept the standalone app-server's test-only flag.
|
||||
// Disable plugins through real config; their safety test joins a full sync.
|
||||
.with_plugin_startup_tasks()
|
||||
.with_args(&["-c", "features.plugins=false", "app-server"])
|
||||
.with_env_overrides(&[
|
||||
("PATH", Some(path.as_ref())),
|
||||
("HOME", Some(home.as_ref())),
|
||||
("CODEX_TEST_HELPER_MARKER", Some(marker.as_ref())),
|
||||
("CODEX_MANAGED_BY_NPM", Some("1")),
|
||||
("CODEX_MANAGED_PACKAGE_ROOT", Some(package_root.as_ref())),
|
||||
("ZELLIJ", Some("0")),
|
||||
("ZELLIJ_VERSION", None),
|
||||
("TMUX", None),
|
||||
("TMUX_PANE", None),
|
||||
("HTTP_PROXY", Some(&proxy_uri)),
|
||||
("HTTPS_PROXY", Some(&proxy_uri)),
|
||||
("ALL_PROXY", Some(&proxy_uri)),
|
||||
("http_proxy", Some(&proxy_uri)),
|
||||
("https_proxy", Some(&proxy_uri)),
|
||||
("all_proxy", Some(&proxy_uri)),
|
||||
("NO_PROXY", Some("127.0.0.1,localhost")),
|
||||
("no_proxy", Some("127.0.0.1,localhost")),
|
||||
])
|
||||
.build_initialized_with_timeout(Duration::from_secs(/*secs*/ 30))
|
||||
.await?;
|
||||
let request_id = app_server
|
||||
.send_raw_request(
|
||||
"feedback/upload",
|
||||
Some(json!({
|
||||
"classification": "bug", "includeLogs": true
|
||||
})),
|
||||
)
|
||||
.await?;
|
||||
let error = timeout(
|
||||
Duration::from_secs(/*secs*/ 45),
|
||||
app_server.read_stream_until_error_message(RequestId::Integer(request_id)),
|
||||
)
|
||||
.await??;
|
||||
assert!(error.error.message.contains("failed to upload feedback"));
|
||||
assert!(!fixture.marker.exists(), "feedback executed a PATH helper");
|
||||
timeout(
|
||||
Duration::from_secs(/*secs*/ 10),
|
||||
app_server.shutdown_gracefully(),
|
||||
)
|
||||
.await??;
|
||||
proxy_task.abort();
|
||||
Ok(())
|
||||
}
|
||||
1358
codex-rs/cli/tests/exec_server.rs
Normal file
1358
codex-rs/cli/tests/exec_server.rs
Normal file
File diff suppressed because it is too large
Load Diff
178
codex-rs/cli/tests/exec_server/auth_refresh_tests.rs
Normal file
178
codex-rs/cli/tests/exec_server/auth_refresh_tests.rs
Normal file
@@ -0,0 +1,178 @@
|
||||
//! 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(®istry)
|
||||
.await;
|
||||
Mock::given(path("/cloud/environment/env/register"))
|
||||
.and(header("authorization", "Bearer old-token"))
|
||||
.respond_with(ResponseTemplate::new(401))
|
||||
.expect(1)
|
||||
.mount(®istry)
|
||||
.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(®istry)
|
||||
.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(®istry)
|
||||
.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",
|
||||
®istry.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(())
|
||||
}
|
||||
155
codex-rs/cli/tests/exec_server/pid_namespace_tests.rs
Normal file
155
codex-rs/cli/tests/exec_server/pid_namespace_tests.rs
Normal file
@@ -0,0 +1,155 @@
|
||||
//! End-to-end checks that only executor startup can opt into PID inheritance.
|
||||
|
||||
use super::*;
|
||||
use codex_exec_server::FileSystemSandboxContext;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::permissions::FileSystemAccessMode;
|
||||
use codex_protocol::permissions::FileSystemPath;
|
||||
use codex_protocol::permissions::FileSystemSandboxEntry;
|
||||
use codex_protocol::permissions::FileSystemSandboxPolicy;
|
||||
use codex_protocol::permissions::FileSystemSpecialPath;
|
||||
use codex_protocol::permissions::NetworkSandboxPolicy;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn pid_inheritance_is_startup_only_for_process_and_filesystem_helpers() -> Result<()> {
|
||||
let Some(bwrap) = codex_sandboxing::find_system_bwrap_in_path(
|
||||
&PermissionProfile::read_only().file_system_sandbox_policy(),
|
||||
&std::env::current_dir()?,
|
||||
) else {
|
||||
eprintln!("skipping PID namespace test: no system bubblewrap");
|
||||
return Ok(());
|
||||
};
|
||||
let available = tokio::process::Command::new(&bwrap)
|
||||
.args(["--unshare-user", "--ro-bind", "/", "/", "--", "/bin/true"])
|
||||
.output()
|
||||
.await?;
|
||||
if !available.status.success() {
|
||||
eprintln!(
|
||||
"skipping PID namespace test: {}",
|
||||
String::from_utf8_lossy(&available.stderr)
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
tokio::time::timeout(Duration::from_secs(30), async {
|
||||
let fixture = TempDir::new()?;
|
||||
let wrapper = fixture.path().join("bwrap");
|
||||
std::os::unix::fs::symlink(bwrap, fixture.path().join("real-bwrap"))?;
|
||||
codex_utils_cargo_bin::write_executable(&wrapper, r#"#!/bin/sh
|
||||
for arg in "$@"; do
|
||||
[ "$arg" = "--" ] && break
|
||||
if [ "$arg" = "--proc" ]; then
|
||||
echo "bwrap: Can't mount proc on /newroot/proc: Operation not permitted" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
exec "${0%/*}/real-bwrap" "$@"
|
||||
"#)?;
|
||||
let path = format!("{}:{}", fixture.path().display(), std::env::var("PATH")?);
|
||||
// System bubblewrap discovery intentionally excludes executables under the command cwd.
|
||||
let workspace = TempDir::new()?;
|
||||
let file = workspace.path().join("readable");
|
||||
std::fs::write(&file, "ok")?;
|
||||
let file_uri = url::Url::from_file_path(&file).unwrap();
|
||||
let cwd = url::Url::from_directory_path(workspace.path()).unwrap();
|
||||
let minimal_policy = FileSystemSandboxPolicy::restricted(vec![
|
||||
FileSystemSandboxEntry::new(
|
||||
FileSystemPath::Special { value: FileSystemSpecialPath::Minimal },
|
||||
FileSystemAccessMode::Read,
|
||||
),
|
||||
FileSystemSandboxEntry::new(
|
||||
AbsolutePathBuf::try_from(workspace.path())?.into(), FileSystemAccessMode::Read,
|
||||
),
|
||||
FileSystemSandboxEntry::new(
|
||||
AbsolutePathBuf::from_absolute_path("/proc/version")?.into(), FileSystemAccessMode::Deny,
|
||||
),
|
||||
]);
|
||||
let minimal_profile = PermissionProfile::from_runtime_permissions(
|
||||
&minimal_policy, NetworkSandboxPolicy::Restricted,
|
||||
);
|
||||
for (inherit, profile) in [
|
||||
(false, PermissionProfile::read_only()),
|
||||
(true, PermissionProfile::read_only()),
|
||||
(true, minimal_profile),
|
||||
] {
|
||||
let minimal = profile.file_system_sandbox_policy().include_platform_defaults();
|
||||
let sandbox = FileSystemSandboxContext::from_permission_profile(
|
||||
profile, cwd.as_str().parse()?,
|
||||
);
|
||||
let codex_home = TempDir::new()?;
|
||||
// Neither a config key nor executor/request environment variables may opt in.
|
||||
std::fs::write(codex_home.path().join("config.toml"),
|
||||
"linux_sandbox_pid_namespace = 'inherit'\n")?;
|
||||
let mut command = tokio::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
command.args(["exec-server", "--listen", "stdio"])
|
||||
.env("CODEX_HOME", codex_home.path())
|
||||
.env("PATH", &path)
|
||||
.env("CODEX_LINUX_SANDBOX_PID_NAMESPACE", "inherit")
|
||||
.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
if inherit {
|
||||
command.arg("--linux-sandbox-pid-namespace=inherit");
|
||||
}
|
||||
let mut child = command.spawn()?;
|
||||
let mut stdin = child.stdin.take().context("executor stdin")?;
|
||||
let mut stdout = BufReader::new(child.stdout.take().context("executor stdout")?);
|
||||
send_json_line(&mut stdin, &serde_json::json!({
|
||||
"id": 1, "method": "initialize",
|
||||
"params": {"clientName": "pid-namespace-test", "resumeSessionId": null}
|
||||
})).await?;
|
||||
wait_for_response(&mut stdout, /*expected_id*/ 1).await?;
|
||||
send_json_line(&mut stdin, &serde_json::json!({"method": "initialized", "params": {}})).await?;
|
||||
send_json_line(&mut stdin, &serde_json::json!({
|
||||
"id": 2, "method": "process/start", "params": {
|
||||
"processId": "pid-test", "cwd": cwd, "sandbox": sandbox,
|
||||
"argv": ["/bin/bash", "-lc", r#"
|
||||
set -e
|
||||
IFS=' ' read -r pid rest < /proc/self/stat
|
||||
test "$$" = "$pid"
|
||||
test "$(cat <(printf shell-ok))" = shell-ok
|
||||
if [ "$MINIMAL" = true ]; then
|
||||
! cat /proc/version
|
||||
fi
|
||||
"#],
|
||||
"env": {"PATH": path, "MINIMAL": minimal.to_string(), "CODEX_LINUX_SANDBOX_PID_NAMESPACE": "inherit"},
|
||||
"tty": false, "pipeStdin": false, "arg0": null
|
||||
}
|
||||
})).await?;
|
||||
// Notifications may precede the process/start response, so consume both.
|
||||
let mut started = false;
|
||||
let mut exit_code = None;
|
||||
while !started || exit_code.is_none() {
|
||||
let mut line = String::new();
|
||||
anyhow::ensure!(stdout.read_line(&mut line).await? > 0, "executor closed");
|
||||
let message: serde_json::Value = serde_json::from_str(&line)?;
|
||||
if message["id"] == 2 {
|
||||
anyhow::ensure!(message.get("error").is_none(), "start failed: {message}");
|
||||
started = true;
|
||||
}
|
||||
if message["method"] == "process/exited" {
|
||||
exit_code = message["params"]["exitCode"].as_i64();
|
||||
}
|
||||
}
|
||||
assert_eq!(exit_code, Some(if inherit { 0 } else { 1 }));
|
||||
send_json_line(&mut stdin, &serde_json::json!({
|
||||
"id": 3, "method": "fs/readFile", "params": {"path": file_uri, "sandbox": sandbox}
|
||||
})).await?;
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
anyhow::ensure!(stdout.read_line(&mut line).await? > 0, "executor closed");
|
||||
let message: serde_json::Value = serde_json::from_str(&line)?;
|
||||
if message["id"] != 3 { continue; }
|
||||
assert_eq!(message["result"], serde_json::json!({"dataBase64": "b2s="}));
|
||||
break;
|
||||
}
|
||||
drop(stdin);
|
||||
// Drain notifications while the executor shuts down.
|
||||
let mut remaining = String::new();
|
||||
stdout.read_to_string(&mut remaining).await?;
|
||||
let output = child.wait_with_output().await?;
|
||||
anyhow::ensure!(output.status.success(), "executor failed: {}", String::from_utf8_lossy(&output.stderr));
|
||||
}
|
||||
Ok(())
|
||||
}).await?
|
||||
}
|
||||
366
codex-rs/cli/tests/exec_server_websocket_auth.rs
Normal file
366
codex-rs/cli/tests/exec_server_websocket_auth.rs
Normal file
@@ -0,0 +1,366 @@
|
||||
//! Exercises listener authentication through the standalone executor CLI and real WebSockets.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
use std::time::SystemTime;
|
||||
use std::time::UNIX_EPOCH;
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::process::Command;
|
||||
use tokio_tungstenite::connect_async;
|
||||
use tokio_tungstenite::tungstenite::Error as WebSocketError;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||
|
||||
enum AuthMode {
|
||||
TokenHash,
|
||||
TokenFile,
|
||||
SignedBearer,
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn exec_server_websocket_auth_gates_rpc_connections() -> Result<()> {
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 60), async {
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
for mode in [
|
||||
AuthMode::TokenHash,
|
||||
AuthMode::TokenFile,
|
||||
AuthMode::SignedBearer,
|
||||
] {
|
||||
let home = TempDir::new()?;
|
||||
let secret = "0123456789abcdef0123456789abcdef";
|
||||
let secret_file = home.path().join("secret");
|
||||
std::fs::write(&secret_file, secret)?;
|
||||
let mut command = Command::new(&codex);
|
||||
command
|
||||
.args(["exec-server", "--listen", "ws://127.0.0.1:0", "--ws-auth"])
|
||||
.env("CODEX_HOME", home.path())
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.kill_on_drop(true);
|
||||
let token = match mode {
|
||||
AuthMode::TokenHash => {
|
||||
command.args([
|
||||
"capability-token",
|
||||
"--ws-token-sha256",
|
||||
&format!("{:x}", Sha256::digest(secret.as_bytes())),
|
||||
]);
|
||||
secret.to_string()
|
||||
}
|
||||
AuthMode::TokenFile => {
|
||||
command
|
||||
.args(["capability-token", "--ws-token-file"])
|
||||
.arg(&secret_file);
|
||||
secret.to_string()
|
||||
}
|
||||
AuthMode::SignedBearer => {
|
||||
command
|
||||
.args(["signed-bearer-token", "--ws-shared-secret-file"])
|
||||
.arg(&secret_file)
|
||||
.args([
|
||||
"--ws-issuer",
|
||||
"test-issuer",
|
||||
"--ws-audience",
|
||||
"test-executor",
|
||||
]);
|
||||
let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
|
||||
jsonwebtoken::encode(
|
||||
&jsonwebtoken::Header::new(jsonwebtoken::Algorithm::HS256),
|
||||
&json!({"exp": now + 300, "iss": "test-issuer", "aud": "test-executor"}),
|
||||
&jsonwebtoken::EncodingKey::from_secret(secret.as_bytes()),
|
||||
)?
|
||||
}
|
||||
};
|
||||
let mut child = command.spawn()?;
|
||||
let mut lines = BufReader::new(child.stdout.take().context("stdout")?).lines();
|
||||
let url = loop {
|
||||
let line = lines
|
||||
.next_line()
|
||||
.await?
|
||||
.context("listener exited before startup")?;
|
||||
if line.starts_with("ws://") {
|
||||
break line;
|
||||
}
|
||||
};
|
||||
|
||||
// A missing or incorrect credential must fail before any RPC session opens.
|
||||
let digest_as_bearer = format!("Bearer {:x}", Sha256::digest(secret.as_bytes()));
|
||||
for authorization in [
|
||||
None,
|
||||
Some("Bearer incorrect"),
|
||||
Some("Basic incorrect"),
|
||||
Some(digest_as_bearer.as_str()),
|
||||
] {
|
||||
let mut request = url.as_str().into_client_request()?;
|
||||
if let Some(authorization) = authorization {
|
||||
request
|
||||
.headers_mut()
|
||||
.insert("authorization", authorization.parse()?);
|
||||
}
|
||||
let error = connect_async(request)
|
||||
.await
|
||||
.expect_err("reject unauthorized upgrade");
|
||||
let WebSocketError::Http(response) = error else {
|
||||
anyhow::bail!("expected HTTP rejection, got {error}");
|
||||
};
|
||||
assert_eq!(response.status(), http::StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
// Authentication applies to every connection, including reconnects.
|
||||
for _ in 0..2 {
|
||||
let mut request = url.as_str().into_client_request()?;
|
||||
request
|
||||
.headers_mut()
|
||||
.insert("authorization", format!("Bearer {token}").parse()?);
|
||||
let (mut websocket, _) = connect_async(request).await?;
|
||||
websocket
|
||||
.send(Message::Text(
|
||||
json!({
|
||||
"id": 1,
|
||||
"method": "initialize",
|
||||
"params": {"clientName": "auth-test"}
|
||||
})
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.await?;
|
||||
let response = websocket.next().await.context("initialize response")??;
|
||||
let response: serde_json::Value = serde_json::from_str(response.to_text()?)?;
|
||||
assert_eq!(response["id"], json!(1));
|
||||
assert!(response.get("error").is_none(), "{response}");
|
||||
assert!(response["result"]["sessionId"].is_string(), "{response}");
|
||||
websocket.close(/*msg*/ None).await?;
|
||||
}
|
||||
child.kill().await?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_server_websocket_auth_rejects_inapplicable_transports() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
for (transport, expected) in [
|
||||
(vec!["--listen", "stdio"], "not stdio"),
|
||||
(vec!["--listen", "stdio://"], "not stdio"),
|
||||
(
|
||||
vec![
|
||||
"--remote",
|
||||
"https://registry.example",
|
||||
"--environment-id",
|
||||
"test",
|
||||
],
|
||||
"cannot be used with --remote",
|
||||
),
|
||||
(
|
||||
vec![
|
||||
"forward",
|
||||
"--connect",
|
||||
"ws://127.0.0.1:1234",
|
||||
"--remote",
|
||||
"https://registry.example",
|
||||
"--environment-id",
|
||||
"test",
|
||||
],
|
||||
"cannot be used with --remote",
|
||||
),
|
||||
] {
|
||||
assert_cmd::Command::new(&codex)
|
||||
.env("CODEX_HOME", home.path())
|
||||
.args([
|
||||
"exec-server",
|
||||
"--ws-auth",
|
||||
"capability-token",
|
||||
"--ws-token-sha256",
|
||||
&"ab".repeat(32),
|
||||
])
|
||||
.args(transport)
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(predicates::str::contains(expected));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_server_websocket_auth_rejects_invalid_configuration() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
for (args, expected) in [
|
||||
(vec!["--ws-token-sha256", "invalid"], "require `--ws-auth"),
|
||||
(
|
||||
vec![
|
||||
"--ws-auth",
|
||||
"capability-token",
|
||||
"--ws-token-sha256",
|
||||
"invalid",
|
||||
],
|
||||
"64-character hex",
|
||||
),
|
||||
(vec!["--ws-auth", "capability-token"], "is required"),
|
||||
] {
|
||||
assert_cmd::Command::new(&codex)
|
||||
.env("CODEX_HOME", home.path())
|
||||
.args(["exec-server"])
|
||||
.args(args)
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(predicates::str::contains(expected));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn app_server_executor_auth_supports_tokens_and_legacy_configuration() -> Result<()> {
|
||||
use app_test_support::TestAppServer;
|
||||
use app_test_support::to_response;
|
||||
use codex_app_server_protocol::EnvironmentInfoResponse;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum Source {
|
||||
Rpc,
|
||||
Toml,
|
||||
}
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 90), async {
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
for token in [None, Some("executor-capability-for-app-server")] {
|
||||
let executor_home = TempDir::new()?;
|
||||
let mut command = Command::new(&codex);
|
||||
command.args(["exec-server", "--listen", "ws://127.0.0.1:0"]);
|
||||
if let Some(token) = token {
|
||||
command.args([
|
||||
"--ws-auth",
|
||||
"capability-token",
|
||||
"--ws-token-sha256",
|
||||
&format!("{:x}", Sha256::digest(token.as_bytes())),
|
||||
]);
|
||||
}
|
||||
let mut executor = command
|
||||
.env("CODEX_HOME", executor_home.path())
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.kill_on_drop(true)
|
||||
.spawn()?;
|
||||
let mut lines =
|
||||
BufReader::new(executor.stdout.take().context("executor stdout")?).lines();
|
||||
let url = loop {
|
||||
let line = lines.next_line().await?.context("executor exited")?;
|
||||
if line.starts_with("ws://") {
|
||||
break line;
|
||||
}
|
||||
};
|
||||
|
||||
for source in [Source::Rpc, Source::Toml] {
|
||||
let home = TempDir::new()?;
|
||||
let builder = TestAppServer::builder()
|
||||
.with_program(&codex)
|
||||
.with_plugin_startup_tasks()
|
||||
.with_args(&["-c", "features.plugins=false", "app-server"])
|
||||
.with_codex_home(home.path())
|
||||
.without_auto_env()
|
||||
.with_env_overrides(&[
|
||||
("CODEX_EXEC_SERVER_URL", None),
|
||||
("CODEX_EXEC_SERVER_NOISE_REGISTRY_URL", None),
|
||||
]);
|
||||
match source {
|
||||
Source::Toml => {
|
||||
let mut config =
|
||||
format!("[[environments]]\nid = \"remote\"\nurl = {url:?}\n");
|
||||
if let Some(token) = token {
|
||||
config.push_str(&format!("auth_bearer_token = {token:?}\n"));
|
||||
}
|
||||
std::fs::write(home.path().join("environments.toml"), config)?;
|
||||
}
|
||||
Source::Rpc => {}
|
||||
}
|
||||
let mut app = builder.build().await?;
|
||||
app.initialize().await?;
|
||||
if source == Source::Rpc {
|
||||
for credential in ["private-token\r\nInjected: true", "private-token\n"] {
|
||||
let id = app
|
||||
.send_raw_request(
|
||||
"environment/add",
|
||||
Some(json!({
|
||||
"environmentId": "invalid", "execServerUrl": url,
|
||||
"authBearerToken": credential,
|
||||
})),
|
||||
)
|
||||
.await?;
|
||||
let error = app
|
||||
.read_stream_until_error_message(RequestId::Integer(id))
|
||||
.await?;
|
||||
assert!(!format!("{error:?}").contains("private-token"));
|
||||
}
|
||||
// Omitted and null tokens preserve old-client requests. They succeed
|
||||
// with an unauthenticated executor and fail when authentication is enabled.
|
||||
let credentials = match token {
|
||||
Some(token) => vec![
|
||||
None,
|
||||
Some(serde_json::Value::Null),
|
||||
Some(json!("wrong-token")),
|
||||
Some(json!(token)),
|
||||
],
|
||||
None => vec![None, Some(serde_json::Value::Null)],
|
||||
};
|
||||
for credential in credentials {
|
||||
let mut params = json!({
|
||||
"environmentId": "remote", "execServerUrl": url,
|
||||
});
|
||||
if let Some(credential) = &credential {
|
||||
params["authBearerToken"] = credential.clone();
|
||||
}
|
||||
let id = app
|
||||
.send_raw_request("environment/add", Some(params))
|
||||
.await?;
|
||||
app.read_stream_until_response_message(RequestId::Integer(id))
|
||||
.await?;
|
||||
let id = app
|
||||
.send_raw_request(
|
||||
"environment/info",
|
||||
Some(json!({"environmentId": "remote"})),
|
||||
)
|
||||
.await?;
|
||||
if token.is_some()
|
||||
&& credential.as_ref().and_then(serde_json::Value::as_str) != token
|
||||
{
|
||||
app.read_stream_until_error_message(RequestId::Integer(id))
|
||||
.await?;
|
||||
} else {
|
||||
app.read_stream_until_response_message(RequestId::Integer(id))
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
let id = app
|
||||
.send_raw_request("environment/info", Some(json!({"environmentId": "remote"})))
|
||||
.await?;
|
||||
let response = app
|
||||
.read_stream_until_response_message(RequestId::Integer(id))
|
||||
.await?;
|
||||
let info: EnvironmentInfoResponse = to_response(response)?;
|
||||
assert!(
|
||||
!info.shell.name.is_empty(),
|
||||
"{source:?} should reach the executor"
|
||||
);
|
||||
}
|
||||
executor.kill().await?;
|
||||
}
|
||||
Ok::<_, anyhow::Error>(())
|
||||
})
|
||||
.await?
|
||||
}
|
||||
119
codex-rs/cli/tests/execpolicy.rs
Normal file
119
codex-rs/cli/tests/execpolicy.rs
Normal file
@@ -0,0 +1,119 @@
|
||||
use std::fs;
|
||||
|
||||
use assert_cmd::Command;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn execpolicy_check_matches_expected_json() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let policy_path = codex_home.path().join("rules").join("policy.rules");
|
||||
fs::create_dir_all(
|
||||
policy_path
|
||||
.parent()
|
||||
.expect("policy path should have a parent"),
|
||||
)?;
|
||||
fs::write(
|
||||
&policy_path,
|
||||
r#"
|
||||
prefix_rule(
|
||||
pattern = ["git", "push"],
|
||||
decision = "forbidden",
|
||||
)
|
||||
"#,
|
||||
)?;
|
||||
|
||||
let output = Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
|
||||
.env("CODEX_HOME", codex_home.path())
|
||||
.args([
|
||||
"execpolicy",
|
||||
"check",
|
||||
"--rules",
|
||||
policy_path
|
||||
.to_str()
|
||||
.expect("policy path should be valid UTF-8"),
|
||||
"git",
|
||||
"push",
|
||||
"origin",
|
||||
"main",
|
||||
])
|
||||
.output()?;
|
||||
|
||||
assert!(output.status.success());
|
||||
let result: serde_json::Value = serde_json::from_slice(&output.stdout)?;
|
||||
assert_eq!(
|
||||
result,
|
||||
json!({
|
||||
"decision": "forbidden",
|
||||
"matchedRules": [
|
||||
{
|
||||
"prefixRuleMatch": {
|
||||
"matchedPrefix": ["git", "push"],
|
||||
"decision": "forbidden"
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn execpolicy_check_includes_justification_when_present() -> Result<(), Box<dyn std::error::Error>>
|
||||
{
|
||||
let codex_home = TempDir::new()?;
|
||||
let policy_path = codex_home.path().join("rules").join("policy.rules");
|
||||
fs::create_dir_all(
|
||||
policy_path
|
||||
.parent()
|
||||
.expect("policy path should have a parent"),
|
||||
)?;
|
||||
fs::write(
|
||||
&policy_path,
|
||||
r#"
|
||||
prefix_rule(
|
||||
pattern = ["git", "push"],
|
||||
decision = "forbidden",
|
||||
justification = "pushing is blocked in this repo",
|
||||
)
|
||||
"#,
|
||||
)?;
|
||||
|
||||
let output = Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
|
||||
.env("CODEX_HOME", codex_home.path())
|
||||
.args([
|
||||
"execpolicy",
|
||||
"check",
|
||||
"--rules",
|
||||
policy_path
|
||||
.to_str()
|
||||
.expect("policy path should be valid UTF-8"),
|
||||
"git",
|
||||
"push",
|
||||
"origin",
|
||||
"main",
|
||||
])
|
||||
.output()?;
|
||||
|
||||
assert!(output.status.success());
|
||||
let result: serde_json::Value = serde_json::from_slice(&output.stdout)?;
|
||||
assert_eq!(
|
||||
result,
|
||||
json!({
|
||||
"decision": "forbidden",
|
||||
"matchedRules": [
|
||||
{
|
||||
"prefixRuleMatch": {
|
||||
"matchedPrefix": ["git", "push"],
|
||||
"decision": "forbidden",
|
||||
"justification": "pushing is blocked in this repo"
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
430
codex-rs/cli/tests/features.rs
Normal file
430
codex-rs/cli/tests/features.rs
Normal file
@@ -0,0 +1,430 @@
|
||||
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")?);
|
||||
cmd.env("CODEX_HOME", codex_home);
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_config_rejects_unknown_config_override() -> Result<()> {
|
||||
for (config_override, ignored_path) in [
|
||||
("foo=bar", "foo"),
|
||||
("tui.bogus_key_xyz=1", "tui.bogus_key_xyz"),
|
||||
] {
|
||||
let codex_home = TempDir::new()?;
|
||||
let mut cmd = codex_command(codex_home.path())?;
|
||||
cmd.args(["--strict-config", "-c", config_override, "exec", "hello"])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains(format!(
|
||||
"unknown configuration field `{ignored_path}`"
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_list_reports_invalid_keybinding_reason() -> Result<()> {
|
||||
for bindings in ["'backslash'", "['backslash']"] {
|
||||
let codex_home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
format!("[tui.keymap.editor]\ninsert_newline = {bindings}\n"),
|
||||
)?;
|
||||
|
||||
let output = codex_command(codex_home.path())?
|
||||
.current_dir(codex_home.path())
|
||||
.args(["mcp", "list"])
|
||||
.assert()
|
||||
.failure()
|
||||
.get_output()
|
||||
.stderr
|
||||
.clone();
|
||||
let output = String::from_utf8(output)?;
|
||||
insta::allow_duplicates! {
|
||||
insta::assert_snapshot!(output);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interactive_validates_config_before_requiring_terminal() -> Result<()> {
|
||||
let cases: &[(&[&str], &str, &str, &str)] = &[
|
||||
(&[], "config.toml", "model = [", "Error loading config.toml"),
|
||||
(
|
||||
&["--strict-config"],
|
||||
"config.toml",
|
||||
"unknown_key = true",
|
||||
"unknown configuration field",
|
||||
),
|
||||
(
|
||||
&["--strict-config"],
|
||||
"config.toml",
|
||||
"[tui]\nbogus_key_xyz = 1",
|
||||
"unknown configuration field `tui.bogus_key_xyz`",
|
||||
),
|
||||
(
|
||||
&["--strict-config", "-c", "foo=bar"],
|
||||
"config.toml",
|
||||
"",
|
||||
"unknown configuration field",
|
||||
),
|
||||
(
|
||||
&["--profile", "work"],
|
||||
"work.config.toml",
|
||||
"model = [",
|
||||
"work.config.toml",
|
||||
),
|
||||
(
|
||||
&["-c", "model_provider=\"missing\""],
|
||||
"config.toml",
|
||||
"",
|
||||
"Model provider `missing` not found",
|
||||
),
|
||||
(&[], "config.toml", "", "stdin is not a terminal"),
|
||||
];
|
||||
|
||||
for &(args, config_file, contents, expected_error) in cases {
|
||||
let codex_home = TempDir::new()?;
|
||||
std::fs::write(codex_home.path().join(config_file), contents)?;
|
||||
|
||||
let mut cmd = codex_command(codex_home.path())?;
|
||||
cmd.env("TERM", "xterm-256color")
|
||||
.current_dir(codex_home.path())
|
||||
.args(args)
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains(expected_error));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interactive_remote_default_preserves_remote_working_directory_before_requiring_terminal()
|
||||
-> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
std::fs::write(codex_home.path().join("config.toml"), "")?;
|
||||
std::fs::write(
|
||||
codex_home.path().join("environments.toml"),
|
||||
r#"default = "remote"
|
||||
include_local = false
|
||||
|
||||
[[environments]]
|
||||
id = "remote"
|
||||
url = "ws://127.0.0.1:4512"
|
||||
"#,
|
||||
)?;
|
||||
let remote_only_cwd = codex_home.path().join("remote-only-working-directory");
|
||||
|
||||
let mut cmd = codex_command(codex_home.path())?;
|
||||
cmd.env("TERM", "xterm-256color")
|
||||
.current_dir(codex_home.path())
|
||||
.arg("--cd")
|
||||
.arg(remote_only_cwd)
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("stdin is not a terminal"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_config_is_not_supported_for_cloud_command() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
let mut cmd = codex_command(codex_home.path())?;
|
||||
cmd.args(["--strict-config", "-c", "foo=bar", "cloud", "list"])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains(
|
||||
"`--strict-config` is not supported for `codex cloud`",
|
||||
));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn features_enable_writes_feature_flag_to_config() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
for feature in ["unified_exec", "shell_tool"] {
|
||||
let mut cmd = codex_command(codex_home.path())?;
|
||||
cmd.args(["features", "enable", feature])
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(contains(format!(
|
||||
"Enabled feature `{feature}` in config.toml."
|
||||
)));
|
||||
|
||||
let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?;
|
||||
assert!(config.contains("[features]"));
|
||||
assert!(config.contains(&format!("{feature} = true")));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn features_disable_writes_feature_flag_to_config() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
let mut cmd = codex_command(codex_home.path())?;
|
||||
cmd.args(["features", "disable", "shell_tool"])
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(contains("Disabled feature `shell_tool` in config.toml."));
|
||||
|
||||
let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?;
|
||||
assert!(config.contains("[features]"));
|
||||
assert!(config.contains("shell_tool = false"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn features_enable_under_development_feature_prints_warning() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
let mut cmd = codex_command(codex_home.path())?;
|
||||
cmd.args(["features", "enable", "runtime_metrics"])
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(contains(
|
||||
"Under-development features enabled: runtime_metrics.",
|
||||
));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn features_list_is_sorted_alphabetically_by_feature_name() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
let mut cmd = codex_command(codex_home.path())?;
|
||||
let output = cmd
|
||||
.args(["features", "list"])
|
||||
.assert()
|
||||
.success()
|
||||
.get_output()
|
||||
.stdout
|
||||
.clone();
|
||||
let stdout = String::from_utf8(output)?;
|
||||
|
||||
let actual_names = stdout
|
||||
.lines()
|
||||
.map(|line| {
|
||||
line.split_once(" ")
|
||||
.map(|(name, _)| name.trim_end().to_string())
|
||||
.expect("feature list output should contain aligned columns")
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut expected_names = actual_names.clone();
|
||||
expected_names.sort();
|
||||
|
||||
assert_eq!(actual_names, expected_names);
|
||||
|
||||
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()?;
|
||||
let output = codex_command(home.path())?
|
||||
.env("TERM", "xterm-256color")
|
||||
.args(["--remote", "ws://127.0.0.1:1", "--add-dir", "remote-extra"])
|
||||
.assert()
|
||||
.failure()
|
||||
.get_output()
|
||||
.stderr
|
||||
.clone();
|
||||
insta::assert_snapshot!(String::from_utf8(output)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_start_rejects_writable_root_overrides_before_connecting() -> Result<()> {
|
||||
for config_override in [
|
||||
"sandbox_workspace_write.writable_roots=[\"./extra\"]",
|
||||
"sandbox_workspace_write={writable_roots=[\"./extra\"],network_access=true}",
|
||||
] {
|
||||
let home = TempDir::new()?;
|
||||
let output = codex_command(home.path())?
|
||||
.env("TERM", "xterm-256color")
|
||||
.args(["--remote", "ws://127.0.0.1:1", "-c", config_override])
|
||||
.assert()
|
||||
.failure()
|
||||
.get_output()
|
||||
.stderr
|
||||
.clone();
|
||||
let output = String::from_utf8(output)?;
|
||||
insta::allow_duplicates! {
|
||||
insta::assert_snapshot!(output, @"Error: sandbox_workspace_write.writable_roots overrides are not supported with --remote. Configure additional workspace roots on the server.");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_start_allows_network_access_overrides_before_requiring_terminal() -> Result<()> {
|
||||
for config_override in [
|
||||
"sandbox_workspace_write.network_access=true",
|
||||
"sandbox_workspace_write={network_access=true}",
|
||||
] {
|
||||
let home = TempDir::new()?;
|
||||
codex_command(home.path())?
|
||||
.env("TERM", "xterm-256color")
|
||||
.args(["--remote", "ws://127.0.0.1:1", "-c", config_override])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("stdin is not a terminal"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_daemon_rejects_queue_and_explicit_remote_targets() -> Result<()> {
|
||||
for args in [
|
||||
"--no-daemon queue --thread example --message hello",
|
||||
"--no-daemon --remote ws://localhost:9999 agents",
|
||||
"--no-daemon --remote ws://localhost:9999",
|
||||
"--no-daemon --remote ws://localhost:9999 archive example",
|
||||
"--no-daemon --remote ws://localhost:9999 unarchive example",
|
||||
"--no-daemon --remote ws://localhost:9999 delete --force 123e4567-e89b-12d3-a456-426614174000",
|
||||
"--no-daemon --remote ws://localhost:9999 queue --thread example --message hello",
|
||||
"--remote ws://localhost:9999 resume --no-daemon --last",
|
||||
"--no-daemon fork --remote ws://localhost:9999 session-name",
|
||||
] {
|
||||
let args = args.split_whitespace().collect::<Vec<_>>();
|
||||
let home = TempDir::new()?;
|
||||
let expected = if args.contains(&"queue") && !args.contains(&"--remote") {
|
||||
"--no-daemon cannot be used with codex queue."
|
||||
} else {
|
||||
"--no-daemon cannot be used with --remote."
|
||||
};
|
||||
codex_command(home.path())?
|
||||
.args(args)
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains(expected));
|
||||
assert!(!home.path().join("app-server-daemon").exists());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
495
codex-rs/cli/tests/login.rs
Normal file
495
codex-rs/cli/tests/login.rs
Normal file
@@ -0,0 +1,495 @@
|
||||
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")?);
|
||||
cmd.env("CODEX_HOME", codex_home);
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
fn write_file_auth_config(codex_home: &Path) -> Result<()> {
|
||||
std::fs::write(
|
||||
codex_home.join("config.toml"),
|
||||
"cli_auth_credentials_store = \"file\"\n",
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_auth_json(codex_home: &Path) -> Result<Value> {
|
||||
let auth_json = std::fs::read_to_string(codex_home.join("auth.json"))?;
|
||||
Ok(serde_json::from_str(&auth_json)?)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_with_api_key_reads_stdin_and_writes_auth_json() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
write_file_auth_config(codex_home.path())?;
|
||||
|
||||
let mut cmd = codex_command(codex_home.path())?;
|
||||
let login = cmd
|
||||
.args([
|
||||
"-c",
|
||||
"forced_login_method=\"api\"",
|
||||
"login",
|
||||
"--with-api-key",
|
||||
])
|
||||
.write_stdin("sk-test\n")
|
||||
.assert()
|
||||
.success();
|
||||
insta::assert_snapshot!(String::from_utf8_lossy(&login.get_output().stderr), @r"
|
||||
Reading API key from stdin...
|
||||
API key saved. Authentication is checked when you send a request.
|
||||
");
|
||||
|
||||
let auth = read_auth_json(codex_home.path())?;
|
||||
assert_eq!(auth["OPENAI_API_KEY"], "sk-test");
|
||||
assert!(auth.get("tokens").is_none());
|
||||
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();
|
||||
insta::assert_snapshot!(String::from_utf8_lossy(&status.get_output().stderr), @r"
|
||||
API key configured - ***
|
||||
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\""])
|
||||
.args(args)
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("ChatGPT login is disabled"));
|
||||
assert_eq!(read_auth_json(codex_home.path())?, auth);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_key_auth_commands_work_when_log_dir_is_unavailable() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let log_dir = codex_home.path().join("unavailable-logs");
|
||||
std::fs::write(&log_dir, "not a directory")?;
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
format!("cli_auth_credentials_store = \"file\"\nlog_dir = {log_dir:?}\n"),
|
||||
)?;
|
||||
|
||||
codex_command(codex_home.path())?
|
||||
.args(["login", "--with-api-key"])
|
||||
.write_stdin("sk-test\n")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(contains("Warning: failed to create login log directory"));
|
||||
assert_eq!(
|
||||
read_auth_json(codex_home.path())?["OPENAI_API_KEY"],
|
||||
"sk-test"
|
||||
);
|
||||
|
||||
codex_command(codex_home.path())?
|
||||
.args(["login", "status"])
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(contains("API key"));
|
||||
|
||||
codex_command(codex_home.path())?
|
||||
.arg("logout")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(contains("Successfully logged out"));
|
||||
assert!(!codex_home.path().join("auth.json").exists());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_status_reports_auth_storage_errors() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
write_file_auth_config(codex_home.path())?;
|
||||
std::fs::write(codex_home.path().join("auth.json"), "{invalid json")?;
|
||||
|
||||
codex_command(codex_home.path())?
|
||||
.args(["login", "status"])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("Error checking login status:"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_status_validates_configured_workload_identity() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
write_file_auth_config(codex_home.path())?;
|
||||
let missing_assertion = codex_home.path().join("missing-identity-token");
|
||||
|
||||
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"));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn logout_clears_only_the_selected_bedrock_provider() -> Result<()> {
|
||||
for (model_provider_id, managed_bedrock_auth, model) in [
|
||||
("amazon-bedrock", true, "openai.gpt-5.6-sol"),
|
||||
("amazon-bedrock-runtime", true, "global.openai.gpt-5.6-sol"),
|
||||
("openai", true, "gpt-5.6-sol"),
|
||||
("amazon-bedrock", false, "gpt-5.6-sol"),
|
||||
("amazon-bedrock-runtime", false, "us.openai.gpt-5.6-sol"),
|
||||
("openai", false, "gpt-5.6-sol"),
|
||||
] {
|
||||
let codex_home = TempDir::new()?;
|
||||
let config_path = codex_home.path().join("config.toml");
|
||||
std::fs::write(
|
||||
&config_path,
|
||||
format!(
|
||||
"cli_auth_credentials_store = \"file\"\n\
|
||||
model_provider = \"{model_provider_id}\"\n\
|
||||
model = \"{model}\"\n\
|
||||
model_reasoning_effort = \"high\"\n\
|
||||
[model_providers.amazon-bedrock]\n\
|
||||
base_url = \"https://mantle.example.com/v1\"\n\
|
||||
[model_providers.amazon-bedrock.aws]\n\
|
||||
profile = \"mantle-profile\"\n\
|
||||
region = \"us-west-2\"\n\
|
||||
auth_refresh = {{ command = \"aws\", args = [\"sso\", \"login\"] }}\n\
|
||||
[model_providers.amazon-bedrock-runtime]\n\
|
||||
base_url = \"https://runtime.example.com/v1\"\n\
|
||||
[model_providers.amazon-bedrock-runtime.aws]\n\
|
||||
profile = \"runtime-profile\"\n\
|
||||
region = \"us-east-1\"\n\
|
||||
auth_refresh = {{ command = \"aws\", args = [\"login\"] }}\n"
|
||||
),
|
||||
)?;
|
||||
if managed_bedrock_auth {
|
||||
login_with_bedrock_access_keys(
|
||||
codex_home.path(),
|
||||
"managed-access-key-id",
|
||||
"managed-secret-access-key",
|
||||
Some("managed-session-token"),
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)?;
|
||||
}
|
||||
let mut expected_config: toml::Value =
|
||||
toml::from_str(&std::fs::read_to_string(&config_path)?)?;
|
||||
if model_provider_id != "openai" {
|
||||
let expected_root = expected_config
|
||||
.as_table_mut()
|
||||
.expect("config should be a table");
|
||||
expected_root.remove("model_provider");
|
||||
expected_root.remove("model");
|
||||
expected_root["model_providers"][model_provider_id]
|
||||
.as_table_mut()
|
||||
.expect("selected Bedrock provider should be a table")
|
||||
.remove("aws");
|
||||
}
|
||||
let expected_message = if managed_bedrock_auth || model_provider_id != "openai" {
|
||||
"Successfully logged out"
|
||||
} else {
|
||||
"Not logged in"
|
||||
};
|
||||
|
||||
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"])
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(contains(expected_message));
|
||||
|
||||
assert!(!codex_home.path().join("auth.json").exists());
|
||||
let actual_config: toml::Value = toml::from_str(&std::fs::read_to_string(&config_path)?)?;
|
||||
assert_eq!(actual_config, expected_config);
|
||||
}
|
||||
|
||||
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(())
|
||||
}
|
||||
253
codex-rs/cli/tests/marketplace_add.rs
Normal file
253
codex-rs/cli/tests/marketplace_add.rs
Normal file
@@ -0,0 +1,253 @@
|
||||
use anyhow::Result;
|
||||
use codex_config::CONFIG_TOML_FILE;
|
||||
use codex_core_plugins::installed_marketplaces::marketplace_install_root;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use predicates::str::contains;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::path::Path;
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
|
||||
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
cmd.env("CODEX_HOME", codex_home);
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
fn write_marketplace_source(source: &Path, marker: &str) -> Result<()> {
|
||||
std::fs::create_dir_all(source.join(".agents/plugins"))?;
|
||||
std::fs::create_dir_all(source.join("plugins/sample/.codex-plugin"))?;
|
||||
std::fs::write(
|
||||
source.join(".agents/plugins/marketplace.json"),
|
||||
r#"{
|
||||
"name": "debug",
|
||||
"plugins": [
|
||||
{
|
||||
"name": "sample",
|
||||
"source": {
|
||||
"source": "local",
|
||||
"path": "./plugins/sample"
|
||||
}
|
||||
}
|
||||
]
|
||||
}"#,
|
||||
)?;
|
||||
std::fs::write(
|
||||
source.join("plugins/sample/.codex-plugin/plugin.json"),
|
||||
r#"{"name":"sample"}"#,
|
||||
)?;
|
||||
std::fs::write(source.join("plugins/sample/marker.txt"), marker)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn marketplace_add_git_source_cleans_staging_after_failures() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let source = TempDir::new()?;
|
||||
write_marketplace_source(source.path(), "git source")?;
|
||||
for args in [
|
||||
vec!["init", "--quiet"],
|
||||
vec!["add", "."],
|
||||
vec![
|
||||
"-c",
|
||||
"user.name=Codex Tests",
|
||||
"-c",
|
||||
"user.email=codex@example.com",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
"commit",
|
||||
"-m",
|
||||
"marketplace",
|
||||
],
|
||||
] {
|
||||
let output = std::process::Command::new("git")
|
||||
.current_dir(source.path())
|
||||
.args(args)
|
||||
.output()?;
|
||||
anyhow::ensure!(
|
||||
output.status.success(),
|
||||
"git fixture failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
// Exercise real Git clones without using the network or changing the process environment.
|
||||
let source_url = "https://example.com/marketplace.git";
|
||||
let rewrite_key = format!("url.{}.insteadOf", source.path().display());
|
||||
let install_root = marketplace_install_root(codex_home.path());
|
||||
let staging_root = install_root.join(".staging");
|
||||
let abandoned = staging_root.join(format!("marketplace-{}-abandoned", std::env::consts::OS));
|
||||
std::fs::create_dir_all(abandoned.join("checkout"))?;
|
||||
std::fs::write(abandoned.join(".lock"), "")?;
|
||||
std::fs::write(abandoned.join("checkout/payload"), "abandoned clone")?;
|
||||
for (args, error) in [
|
||||
(["--ref", "missing-ref"], "git checkout missing-ref failed"),
|
||||
(
|
||||
["--sparse", "plugins/sample"],
|
||||
"marketplace root does not contain a supported manifest",
|
||||
),
|
||||
] {
|
||||
for _ in 0..2 {
|
||||
codex_command(codex_home.path())?
|
||||
.current_dir(codex_home.path())
|
||||
.env("GIT_CONFIG_COUNT", "1")
|
||||
.env("GIT_CONFIG_KEY_0", &rewrite_key)
|
||||
.env("GIT_CONFIG_VALUE_0", source_url)
|
||||
.args(["plugin", "marketplace", "add", source_url])
|
||||
.args(args)
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains(error));
|
||||
|
||||
assert_eq!(std::fs::read_dir(&staging_root)?.count(), 0);
|
||||
assert!(!install_root.join("debug").exists());
|
||||
assert!(!codex_home.path().join(CONFIG_TOML_FILE).exists());
|
||||
}
|
||||
}
|
||||
|
||||
codex_command(codex_home.path())?
|
||||
.current_dir(codex_home.path())
|
||||
.env("GIT_CONFIG_COUNT", "1")
|
||||
.env("GIT_CONFIG_KEY_0", &rewrite_key)
|
||||
.env("GIT_CONFIG_VALUE_0", source_url)
|
||||
.args(["plugin", "marketplace", "add", source_url])
|
||||
.assert()
|
||||
.success();
|
||||
let config = std::fs::read_to_string(codex_home.path().join(CONFIG_TOML_FILE))?;
|
||||
|
||||
// A different ref bypasses the already-added shortcut and conflicts after cloning.
|
||||
codex_command(codex_home.path())?
|
||||
.current_dir(codex_home.path())
|
||||
.env("GIT_CONFIG_COUNT", "1")
|
||||
.env("GIT_CONFIG_KEY_0", &rewrite_key)
|
||||
.env("GIT_CONFIG_VALUE_0", source_url)
|
||||
.args(["plugin", "marketplace", "add", source_url, "--ref", "HEAD"])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("already added from a different source"));
|
||||
|
||||
assert_eq!(std::fs::read_dir(&staging_root)?.count(), 0);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(install_root.join("debug/plugins/sample/marker.txt"))?,
|
||||
"git source"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(codex_home.path().join(CONFIG_TOML_FILE))?,
|
||||
config
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn marketplace_add_local_directory_source() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let source = TempDir::new()?;
|
||||
write_marketplace_source(source.path(), "local ref")?;
|
||||
let source_parent = source.path().parent().unwrap();
|
||||
let source_arg = format!("./{}", source.path().file_name().unwrap().to_string_lossy());
|
||||
|
||||
codex_command(codex_home.path())?
|
||||
.current_dir(source_parent)
|
||||
.args(["plugin", "marketplace", "add", source_arg.as_str()])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let installed_root = marketplace_install_root(codex_home.path()).join("debug");
|
||||
assert!(!installed_root.exists());
|
||||
|
||||
let config = std::fs::read_to_string(codex_home.path().join(CONFIG_TOML_FILE))?;
|
||||
let config: toml::Value = toml::from_str(&config)?;
|
||||
let expected_source = source.path().canonicalize()?.display().to_string();
|
||||
assert_eq!(
|
||||
config["marketplaces"]["debug"]["source_type"].as_str(),
|
||||
Some("local")
|
||||
);
|
||||
assert_eq!(
|
||||
config["marketplaces"]["debug"]["source"].as_str(),
|
||||
Some(expected_source.as_str())
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn marketplace_add_json_prints_add_outcome() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let source = TempDir::new()?;
|
||||
write_marketplace_source(source.path(), "local ref")?;
|
||||
let source_parent = source.path().parent().unwrap();
|
||||
let source_arg = format!("./{}", source.path().file_name().unwrap().to_string_lossy());
|
||||
|
||||
let assert = codex_command(codex_home.path())?
|
||||
.current_dir(source_parent)
|
||||
.args([
|
||||
"plugin",
|
||||
"marketplace",
|
||||
"add",
|
||||
source_arg.as_str(),
|
||||
"--json",
|
||||
])
|
||||
.assert()
|
||||
.success();
|
||||
let stdout = assert.get_output().stdout.as_slice();
|
||||
let actual: serde_json::Value = serde_json::from_slice(stdout)?;
|
||||
let expected_installed_root = AbsolutePathBuf::try_from(source.path().canonicalize()?)?;
|
||||
|
||||
assert_eq!(
|
||||
actual,
|
||||
json!({
|
||||
"marketplaceName": "debug",
|
||||
"installedRoot": expected_installed_root.as_path().display().to_string(),
|
||||
"alreadyAdded": false,
|
||||
})
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn marketplace_add_rejects_local_manifest_file_source() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let source = TempDir::new()?;
|
||||
write_marketplace_source(source.path(), "local ref")?;
|
||||
let manifest_path = source.path().join(".agents/plugins/marketplace.json");
|
||||
|
||||
codex_command(codex_home.path())?
|
||||
.args([
|
||||
"plugin",
|
||||
"marketplace",
|
||||
"add",
|
||||
manifest_path.to_str().unwrap(),
|
||||
])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains(
|
||||
"local marketplace source must be a directory, not a file",
|
||||
));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn marketplace_add_rejects_sparse_for_local_directory_source() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let source = TempDir::new()?;
|
||||
write_marketplace_source(source.path(), "local ref")?;
|
||||
|
||||
codex_command(codex_home.path())?
|
||||
.args([
|
||||
"plugin",
|
||||
"marketplace",
|
||||
"add",
|
||||
"--sparse",
|
||||
".agents",
|
||||
source.path().to_str().unwrap(),
|
||||
])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains(
|
||||
"--sparse is only supported for git marketplace sources",
|
||||
));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
127
codex-rs/cli/tests/marketplace_remove.rs
Normal file
127
codex-rs/cli/tests/marketplace_remove.rs
Normal file
@@ -0,0 +1,127 @@
|
||||
use anyhow::Result;
|
||||
use codex_config::MarketplaceConfigUpdate;
|
||||
use codex_config::record_user_marketplace;
|
||||
use codex_core_plugins::installed_marketplaces::marketplace_install_root;
|
||||
use codex_utils_absolute_path::canonicalize_existing_preserving_symlinks;
|
||||
use predicates::str::contains;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::path::Path;
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
|
||||
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
cmd.env("CODEX_HOME", codex_home);
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
fn configured_marketplace_update() -> MarketplaceConfigUpdate<'static> {
|
||||
MarketplaceConfigUpdate {
|
||||
source_type: "git",
|
||||
source: "https://github.com/owner/repo.git",
|
||||
ref_name: Some("main"),
|
||||
sparse_paths: &[],
|
||||
}
|
||||
}
|
||||
|
||||
fn write_installed_marketplace(codex_home: &Path, marketplace_name: &str) -> Result<()> {
|
||||
let root = marketplace_install_root(codex_home).join(marketplace_name);
|
||||
std::fs::create_dir_all(root.join(".agents/plugins"))?;
|
||||
std::fs::write(root.join(".agents/plugins/marketplace.json"), "{}")?;
|
||||
std::fs::write(root.join("marker.txt"), "installed")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn marketplace_remove_deletes_config_and_installed_root() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
record_user_marketplace(codex_home.path(), "debug", &configured_marketplace_update())?;
|
||||
write_installed_marketplace(codex_home.path(), "debug")?;
|
||||
|
||||
codex_command(codex_home.path())?
|
||||
.args(["plugin", "marketplace", "remove", "debug"])
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(contains("Removed marketplace `debug`."));
|
||||
|
||||
let config_path = codex_home.path().join("config.toml");
|
||||
let config = std::fs::read_to_string(config_path)?;
|
||||
assert!(!config.contains("[marketplaces.debug]"));
|
||||
assert!(
|
||||
!marketplace_install_root(codex_home.path())
|
||||
.join("debug")
|
||||
.exists()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn marketplace_remove_json_prints_remove_outcome() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
record_user_marketplace(codex_home.path(), "debug", &configured_marketplace_update())?;
|
||||
write_installed_marketplace(codex_home.path(), "debug")?;
|
||||
let installed_root = marketplace_install_root(codex_home.path()).join("debug");
|
||||
let normalized_installed_root = canonicalize_existing_preserving_symlinks(&installed_root)?;
|
||||
|
||||
let assert = codex_command(codex_home.path())?
|
||||
.args(["plugin", "marketplace", "remove", "debug", "--json"])
|
||||
.assert()
|
||||
.success();
|
||||
let stdout = assert.get_output().stdout.as_slice();
|
||||
let actual: serde_json::Value = serde_json::from_slice(stdout)?;
|
||||
|
||||
assert_eq!(
|
||||
actual,
|
||||
json!({
|
||||
"marketplaceName": "debug",
|
||||
"installedRoot": normalized_installed_root.display().to_string(),
|
||||
})
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn marketplace_remove_rejects_unknown_marketplace() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
codex_command(codex_home.path())?
|
||||
.args(["plugin", "marketplace", "remove", "debug"])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains(
|
||||
"marketplace `debug` is not configured or installed",
|
||||
));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn marketplace_remove_preserves_marketplace_referenced_by_session_config() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
record_user_marketplace(codex_home.path(), "debug", &configured_marketplace_update())?;
|
||||
write_installed_marketplace(codex_home.path(), "debug")?;
|
||||
let config_path = codex_home.path().join("config.toml");
|
||||
let config = std::fs::read_to_string(&config_path)?;
|
||||
|
||||
codex_command(codex_home.path())?
|
||||
.args([
|
||||
"plugin", "marketplace",
|
||||
"-c", "marketplaces.debug.source_type=\"git\"",
|
||||
"remove", "debug",
|
||||
])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains(
|
||||
"marketplace `debug` is configured in session-flags; remove it from that configuration source instead",
|
||||
));
|
||||
|
||||
assert_eq!(std::fs::read_to_string(config_path)?, config);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(
|
||||
marketplace_install_root(codex_home.path()).join("debug/marker.txt")
|
||||
)?,
|
||||
"installed",
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
118
codex-rs/cli/tests/marketplace_upgrade.rs
Normal file
118
codex-rs/cli/tests/marketplace_upgrade.rs
Normal file
@@ -0,0 +1,118 @@
|
||||
use anyhow::Result;
|
||||
use codex_core_plugins::installed_marketplaces::marketplace_install_root;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use predicates::str::contains;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::path::Path;
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
|
||||
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
cmd.env("CODEX_HOME", codex_home);
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn marketplace_upgrade_runs_under_plugin() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let abandoned = marketplace_install_root(codex_home.path())
|
||||
.join(".staging")
|
||||
.join(format!("marketplace-{}-abandoned", std::env::consts::OS));
|
||||
std::fs::create_dir_all(abandoned.join("checkout"))?;
|
||||
std::fs::write(abandoned.join(".lock"), "")?;
|
||||
std::fs::write(abandoned.join("checkout/payload"), "abandoned clone")?;
|
||||
|
||||
codex_command(codex_home.path())?
|
||||
.args(["plugin", "marketplace", "upgrade"])
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(contains("No configured Git marketplaces to upgrade."));
|
||||
|
||||
assert!(!abandoned.exists());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn marketplace_upgrade_json_prints_upgrade_outcome() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let source = TempDir::new()?;
|
||||
let manifest = r#"{"name":"debug","plugins":[]}"#;
|
||||
std::fs::create_dir_all(source.path().join(".agents/plugins"))?;
|
||||
std::fs::write(
|
||||
source.path().join(".agents/plugins/marketplace.json"),
|
||||
manifest,
|
||||
)?;
|
||||
for args in [
|
||||
vec!["init", "--quiet"],
|
||||
vec!["add", "."],
|
||||
vec![
|
||||
"-c",
|
||||
"user.name=Codex Tests",
|
||||
"-c",
|
||||
"user.email=codex@example.com",
|
||||
"commit",
|
||||
"-m",
|
||||
"marketplace",
|
||||
],
|
||||
] {
|
||||
let output = std::process::Command::new("git")
|
||||
.current_dir(source.path())
|
||||
.args(args)
|
||||
.output()?;
|
||||
anyhow::ensure!(
|
||||
output.status.success(),
|
||||
"git fixture failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
let source_arg = serde_json::to_string(&source.path().to_string_lossy())?;
|
||||
let marketplace_override =
|
||||
format!("marketplaces.debug={{source_type=\"git\",source={source_arg}}}");
|
||||
|
||||
let assert = codex_command(codex_home.path())?
|
||||
.current_dir(codex_home.path())
|
||||
.args(["--config", &marketplace_override])
|
||||
.args(["plugin", "marketplace", "upgrade", "--json"])
|
||||
.assert()
|
||||
.success();
|
||||
let stdout = assert.get_output().stdout.as_slice();
|
||||
let actual: serde_json::Value = serde_json::from_slice(stdout)?;
|
||||
let installed_root = AbsolutePathBuf::try_from(
|
||||
marketplace_install_root(&codex_home.path().canonicalize()?).join("debug"),
|
||||
)?;
|
||||
|
||||
assert_eq!(
|
||||
actual,
|
||||
json!({
|
||||
"selectedMarketplaces": ["debug"],
|
||||
"upgradedRoots": [installed_root],
|
||||
"errors": [],
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(installed_root.join(".agents/plugins/marketplace.json"))?,
|
||||
manifest
|
||||
);
|
||||
assert!(!codex_home.path().join("config.toml").exists());
|
||||
assert_eq!(
|
||||
std::fs::read_dir(marketplace_install_root(codex_home.path()).join(".staging"))?.count(),
|
||||
0
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn marketplace_upgrade_no_longer_runs_at_top_level() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
codex_command(codex_home.path())?
|
||||
.args(["marketplace", "upgrade"])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("unrecognized subcommand 'upgrade'"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
582
codex-rs/cli/tests/mcp_add_remove.rs
Normal file
582
codex-rs/cli/tests/mcp_add_remove.rs
Normal file
@@ -0,0 +1,582 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::Result;
|
||||
use codex_config::types::McpServerTransportConfig;
|
||||
use codex_core::config::edit::ConfigEditsBuilder;
|
||||
use codex_core::config::load_global_mcp_servers;
|
||||
use predicates::str::contains;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
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")?);
|
||||
cmd.env("CODEX_HOME", codex_home);
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn add_and_remove_server_updates_global_config() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
let mut add_cmd = codex_command(codex_home.path())?;
|
||||
add_cmd
|
||||
.args(["mcp", "add", "docs", "--", "echo", "hello"])
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(contains("Added global MCP server 'docs'."));
|
||||
|
||||
let servers = load_global_mcp_servers(codex_home.path()).await?;
|
||||
assert_eq!(servers.len(), 1);
|
||||
let docs = servers.get("docs").expect("server should exist");
|
||||
match &docs.transport {
|
||||
McpServerTransportConfig::Stdio {
|
||||
command,
|
||||
args,
|
||||
env,
|
||||
env_vars,
|
||||
cwd,
|
||||
} => {
|
||||
assert_eq!(command, "echo");
|
||||
assert_eq!(args, &vec!["hello".to_string()]);
|
||||
assert!(env.is_none());
|
||||
assert!(env_vars.is_empty());
|
||||
assert!(cwd.is_none());
|
||||
}
|
||||
other => panic!("unexpected transport: {other:?}"),
|
||||
}
|
||||
assert!(docs.enabled);
|
||||
|
||||
let mut remove_cmd = codex_command(codex_home.path())?;
|
||||
remove_cmd
|
||||
.args(["mcp", "remove", "docs"])
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(contains("Removed global MCP server 'docs'."));
|
||||
|
||||
let servers = load_global_mcp_servers(codex_home.path()).await?;
|
||||
assert!(servers.is_empty());
|
||||
|
||||
let mut remove_again_cmd = codex_command(codex_home.path())?;
|
||||
remove_again_cmd
|
||||
.args(["mcp", "remove", "docs"])
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(contains("No MCP server named 'docs' found."));
|
||||
|
||||
let servers = load_global_mcp_servers(codex_home.path()).await?;
|
||||
assert!(servers.is_empty());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn npm_server_names_round_trip_through_cli() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let name = "npm:@modelcontextprotocol/server-sequential.thinking";
|
||||
|
||||
codex_command(codex_home.path())?
|
||||
.args(["mcp", "add", name, "--", "echo", "hello"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?;
|
||||
assert!(config.contains(&format!("[mcp_servers.\"{name}\"]")));
|
||||
let servers = load_global_mcp_servers(codex_home.path()).await?;
|
||||
assert_eq!(
|
||||
servers.keys().map(String::as_str).collect::<Vec<_>>(),
|
||||
vec![name]
|
||||
);
|
||||
|
||||
let output = codex_command(codex_home.path())?
|
||||
.args(["mcp", "get", name, "--json"])
|
||||
.assert()
|
||||
.success()
|
||||
.get_output()
|
||||
.stdout
|
||||
.clone();
|
||||
let server: serde_json::Value = serde_json::from_slice(&output)?;
|
||||
assert_eq!(server["name"], name);
|
||||
|
||||
let output = codex_command(codex_home.path())?
|
||||
.args(["mcp", "list", "--json"])
|
||||
.assert()
|
||||
.success()
|
||||
.get_output()
|
||||
.stdout
|
||||
.clone();
|
||||
let listed: Vec<serde_json::Value> = serde_json::from_slice(&output)?;
|
||||
assert_eq!(listed.len(), 1);
|
||||
assert_eq!(listed[0]["name"], name);
|
||||
|
||||
codex_command(codex_home.path())?
|
||||
.args(["mcp", "remove", name])
|
||||
.assert()
|
||||
.success();
|
||||
assert!(load_global_mcp_servers(codex_home.path()).await?.is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn add_and_login_discover_oauth_through_configured_http_proxy() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let proxy = MockServer::start().await;
|
||||
let resource_url = "http://cli-mcp.invalid";
|
||||
let challenge = "Bearer resource_metadata=\"http://cli-mcp.invalid/oauth-resource\"";
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/mcp"))
|
||||
.respond_with(ResponseTemplate::new(401).insert_header("WWW-Authenticate", challenge))
|
||||
.mount(&proxy)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/oauth-resource"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"resource": format!("{resource_url}/mcp"),
|
||||
"authorization_servers": [resource_url],
|
||||
})))
|
||||
.mount(&proxy)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/.well-known/oauth-authorization-server"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"authorization_endpoint": format!("{resource_url}/oauth/authorize"),
|
||||
"token_endpoint": format!("{resource_url}/oauth/token"),
|
||||
"registration_endpoint": format!("{resource_url}/oauth/register"),
|
||||
"response_types_supported": ["code"],
|
||||
"code_challenge_methods_supported": ["S256"],
|
||||
})))
|
||||
.mount(&proxy)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/oauth/register"))
|
||||
.respond_with(ResponseTemplate::new(400))
|
||||
.mount(&proxy)
|
||||
.await;
|
||||
|
||||
let mut add = codex_command(codex_home.path())?;
|
||||
add.env("HTTP_PROXY", proxy.uri())
|
||||
.env("http_proxy", proxy.uri())
|
||||
.env_remove("HTTPS_PROXY")
|
||||
.env_remove("https_proxy")
|
||||
.env_remove("ALL_PROXY")
|
||||
.env_remove("all_proxy")
|
||||
.env_remove("NO_PROXY")
|
||||
.env_remove("no_proxy")
|
||||
.args([
|
||||
"-c",
|
||||
"mcp_oauth_credentials_store=\"file\"",
|
||||
"mcp",
|
||||
"add",
|
||||
"oauth",
|
||||
"--url",
|
||||
"http://cli-mcp.invalid/mcp",
|
||||
]);
|
||||
let add_output = tokio::task::spawn_blocking(move || add.output()).await??;
|
||||
assert!(
|
||||
!add_output.status.success(),
|
||||
"mock OAuth registration should terminate the automatic login"
|
||||
);
|
||||
assert!(
|
||||
load_global_mcp_servers(codex_home.path())
|
||||
.await?
|
||||
.contains_key("oauth")
|
||||
);
|
||||
let helper_command = if cfg!(windows) {
|
||||
r#"echo {"X-Gateway":"gateway-token"}"#
|
||||
} else {
|
||||
r#"printf '{"X-Gateway":"gateway-token"}'"#
|
||||
};
|
||||
let config_path = codex_home.path().join("config.toml");
|
||||
let mut config = std::fs::read_to_string(&config_path)?;
|
||||
config.push_str(&format!(
|
||||
"http_headers_helper = {}\n",
|
||||
toml::Value::String(helper_command.to_string())
|
||||
));
|
||||
std::fs::write(config_path, config)?;
|
||||
|
||||
// Local OAuth login does not require the execution-environment registry.
|
||||
std::fs::write(codex_home.path().join("environments.toml"), "invalid = [")?;
|
||||
|
||||
let mut login = codex_command(codex_home.path())?;
|
||||
login
|
||||
.env("HTTP_PROXY", proxy.uri())
|
||||
.env("http_proxy", proxy.uri())
|
||||
.env_remove("HTTPS_PROXY")
|
||||
.env_remove("https_proxy")
|
||||
.env_remove("ALL_PROXY")
|
||||
.env_remove("all_proxy")
|
||||
.env_remove("NO_PROXY")
|
||||
.env_remove("no_proxy")
|
||||
.args([
|
||||
"-c",
|
||||
"mcp_oauth_credentials_store=\"file\"",
|
||||
"mcp",
|
||||
"login",
|
||||
"oauth",
|
||||
]);
|
||||
let login_output = tokio::task::spawn_blocking(move || login.output()).await??;
|
||||
assert!(
|
||||
!login_output.status.success(),
|
||||
"mock OAuth registration should terminate the explicit login"
|
||||
);
|
||||
|
||||
let requests = proxy
|
||||
.received_requests()
|
||||
.await
|
||||
.expect("mock proxy should record OAuth requests");
|
||||
let registrations: Vec<_> = requests
|
||||
.iter()
|
||||
.filter(|request| request.method == "POST" && request.url.path() == "/oauth/register")
|
||||
.collect();
|
||||
assert_eq!(registrations.len(), 2);
|
||||
assert_eq!(
|
||||
registrations
|
||||
.iter()
|
||||
.filter(|request| request.headers.get("x-gateway").is_some())
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn profile_mcp_reports_legacy_profile_migration() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
r#"[profiles.work]
|
||||
model = "gpt-5"
|
||||
"#,
|
||||
)?;
|
||||
|
||||
let mut list_cmd = codex_command(codex_home.path())?;
|
||||
list_cmd
|
||||
.args(["--profile", "work", "mcp", "list"])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("--profile `work` cannot be used"))
|
||||
.stderr(contains("[profiles.work]"))
|
||||
.stderr(contains("work.config.toml"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn add_with_env_preserves_key_order_and_values() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
let mut add_cmd = codex_command(codex_home.path())?;
|
||||
add_cmd
|
||||
.args([
|
||||
"mcp",
|
||||
"add",
|
||||
"envy",
|
||||
"--env",
|
||||
"FOO=bar",
|
||||
"--env",
|
||||
"ALPHA=beta",
|
||||
"--",
|
||||
"python",
|
||||
"server.py",
|
||||
])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let servers = load_global_mcp_servers(codex_home.path()).await?;
|
||||
let envy = servers.get("envy").expect("server should exist");
|
||||
let env = match &envy.transport {
|
||||
McpServerTransportConfig::Stdio { env: Some(env), .. } => env,
|
||||
other => panic!("unexpected transport: {other:?}"),
|
||||
};
|
||||
|
||||
assert_eq!(env.len(), 2);
|
||||
assert_eq!(env.get("FOO"), Some(&"bar".to_string()));
|
||||
assert_eq!(env.get("ALPHA"), Some(&"beta".to_string()));
|
||||
assert!(envy.enabled);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn add_streamable_http_without_manual_token() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
let mut add_cmd = codex_command(codex_home.path())?;
|
||||
add_cmd
|
||||
.args([
|
||||
"mcp",
|
||||
"add",
|
||||
"github",
|
||||
"--url",
|
||||
"https://example.com/mcp",
|
||||
"--oauth-client-registration",
|
||||
"dcr",
|
||||
])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let servers = load_global_mcp_servers(codex_home.path()).await?;
|
||||
let github = servers.get("github").expect("github server should exist");
|
||||
match &github.transport {
|
||||
McpServerTransportConfig::StreamableHttp {
|
||||
url,
|
||||
bearer_token_env_var,
|
||||
http_headers,
|
||||
env_http_headers,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(url, "https://example.com/mcp");
|
||||
assert!(bearer_token_env_var.is_none());
|
||||
assert!(http_headers.is_none());
|
||||
assert!(env_http_headers.is_none());
|
||||
}
|
||||
other => panic!("unexpected transport: {other:?}"),
|
||||
}
|
||||
assert!(github.enabled);
|
||||
assert_eq!(github.oauth, None);
|
||||
|
||||
assert!(!codex_home.path().join(".credentials.json").exists());
|
||||
assert!(!codex_home.path().join(".env").exists());
|
||||
let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?;
|
||||
assert!(!config.contains("client_registration"));
|
||||
assert!(!config.contains("[mcp_servers.github.oauth]"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn add_rejects_blank_client_credentials_before_saving() -> Result<()> {
|
||||
let mut errors = Vec::new();
|
||||
for (client_id, client_secret) in [("registered-client", " "), (" ", "cli-secret-marker")] {
|
||||
let codex_home = TempDir::new()?;
|
||||
let output = codex_command(codex_home.path())?
|
||||
.args([
|
||||
"mcp",
|
||||
"add",
|
||||
"private",
|
||||
"--url",
|
||||
"http://127.0.0.1:9/mcp",
|
||||
"--oauth-client-id",
|
||||
client_id,
|
||||
"--oauth-client-secret",
|
||||
client_secret,
|
||||
])
|
||||
.assert()
|
||||
.failure()
|
||||
.get_output()
|
||||
.clone();
|
||||
let stderr = String::from_utf8(output.stderr)?;
|
||||
assert!(!stderr.contains("cli-secret-marker"));
|
||||
assert!(!String::from_utf8(output.stdout)?.contains("cli-secret-marker"));
|
||||
assert!(load_global_mcp_servers(codex_home.path()).await?.is_empty());
|
||||
errors.push(stderr.trim().to_string());
|
||||
}
|
||||
insta::assert_snapshot!(errors.join("\n"), @r"
|
||||
Error: --oauth-client-secret must not be empty
|
||||
Error: --oauth-client-secret requires a nonempty --oauth-client-id
|
||||
");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn add_streamable_http_with_custom_env_var() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
let mut add_cmd = codex_command(codex_home.path())?;
|
||||
add_cmd
|
||||
.args([
|
||||
"mcp",
|
||||
"add",
|
||||
"issues",
|
||||
"--url",
|
||||
"https://example.com/issues",
|
||||
"--bearer-token-env-var",
|
||||
"GITHUB_TOKEN",
|
||||
])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let servers = load_global_mcp_servers(codex_home.path()).await?;
|
||||
let issues = servers.get("issues").expect("issues server should exist");
|
||||
match &issues.transport {
|
||||
McpServerTransportConfig::StreamableHttp {
|
||||
url,
|
||||
bearer_token_env_var,
|
||||
http_headers,
|
||||
env_http_headers,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(url, "https://example.com/issues");
|
||||
assert_eq!(bearer_token_env_var.as_deref(), Some("GITHUB_TOKEN"));
|
||||
assert!(http_headers.is_none());
|
||||
assert!(env_http_headers.is_none());
|
||||
}
|
||||
other => panic!("unexpected transport: {other:?}"),
|
||||
}
|
||||
assert!(issues.enabled);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn add_streamable_http_with_oauth_options() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let expected_callback = "http://127.0.0.1/callback/w9gKTtkB7gWy";
|
||||
|
||||
let mut add_cmd = codex_command(codex_home.path())?;
|
||||
add_cmd
|
||||
.args([
|
||||
"-c",
|
||||
"mcp_oauth_callback_port=43123",
|
||||
"mcp",
|
||||
"add",
|
||||
"oauth-server",
|
||||
"--url",
|
||||
"https://example.com/mcp",
|
||||
"--oauth-client-id",
|
||||
"eci-prd-pub-codex-123",
|
||||
"--oauth-resource",
|
||||
"https://resource.example.com",
|
||||
])
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(contains(format!("OAuth callback URL: {expected_callback}")));
|
||||
|
||||
let servers = load_global_mcp_servers(codex_home.path()).await?;
|
||||
let oauth_server = servers
|
||||
.get("oauth-server")
|
||||
.expect("oauth server should exist");
|
||||
assert_eq!(
|
||||
oauth_server.oauth_client_id(),
|
||||
Some("eci-prd-pub-codex-123")
|
||||
);
|
||||
assert_eq!(
|
||||
oauth_server
|
||||
.oauth
|
||||
.as_ref()
|
||||
.and_then(|oauth| oauth.callback_url.as_deref()),
|
||||
Some(expected_callback)
|
||||
);
|
||||
assert_eq!(
|
||||
oauth_server.oauth_resource.as_deref(),
|
||||
Some("https://resource.example.com")
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn add_persists_issuer_bound_callback_before_starting_oauth() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let oauth_server = MockServer::start().await;
|
||||
let issuer = format!("{}/mcp", oauth_server.uri());
|
||||
let metadata = serde_json::json!({
|
||||
"issuer": issuer,
|
||||
"authorization_endpoint": "not-a-valid-authorization-url",
|
||||
"token_endpoint": format!("{}/token", oauth_server.uri()),
|
||||
"authorization_response_iss_parameter_supported": true,
|
||||
});
|
||||
let concurrent_codex_home = codex_home.path().to_path_buf();
|
||||
let concurrent_servers = BTreeMap::from([(
|
||||
"concurrent".to_string(),
|
||||
toml::from_str("command = \"echo\"\nargs = [\"concurrent\"]")?,
|
||||
)]);
|
||||
let concurrent_add = std::sync::Once::new();
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/.well-known/oauth-authorization-server/mcp"))
|
||||
.respond_with(move |_: &wiremock::Request| {
|
||||
concurrent_add.call_once(|| {
|
||||
// Edit during discovery without starting another CLI inside the HTTP timeout.
|
||||
ConfigEditsBuilder::new(&concurrent_codex_home)
|
||||
.replace_mcp_servers(&concurrent_servers)
|
||||
.apply_blocking()
|
||||
.expect("persist concurrent MCP server during discovery");
|
||||
});
|
||||
ResponseTemplate::new(200).set_body_json(metadata.clone())
|
||||
})
|
||||
.mount(&oauth_server)
|
||||
.await;
|
||||
|
||||
let mut add_cmd = codex_command(codex_home.path())?;
|
||||
add_cmd.args([
|
||||
"mcp",
|
||||
"add",
|
||||
"issuer-bound",
|
||||
"--url",
|
||||
&format!("{}/mcp", oauth_server.uri()),
|
||||
"--oauth-client-id",
|
||||
"registered-client",
|
||||
]);
|
||||
let output = tokio::task::spawn_blocking(move || add_cmd.output()).await??;
|
||||
|
||||
assert_cmd::assert::Assert::new(output)
|
||||
.failure()
|
||||
.stdout(contains("OAuth callback URL: http://127.0.0.1/callback"))
|
||||
.stderr(contains("OAuth authorization endpoint must be a valid URL"));
|
||||
let servers = load_global_mcp_servers(codex_home.path()).await?;
|
||||
assert!(servers.contains_key("concurrent"));
|
||||
assert_eq!(
|
||||
servers["issuer-bound"]
|
||||
.oauth
|
||||
.as_ref()
|
||||
.and_then(|oauth| oauth.callback_url.as_deref()),
|
||||
Some("http://127.0.0.1/callback")
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn add_streamable_http_rejects_removed_flag() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
let mut add_cmd = codex_command(codex_home.path())?;
|
||||
add_cmd
|
||||
.args([
|
||||
"mcp",
|
||||
"add",
|
||||
"github",
|
||||
"--url",
|
||||
"https://example.com/mcp",
|
||||
"--with-bearer-token",
|
||||
])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("--with-bearer-token"));
|
||||
|
||||
let servers = load_global_mcp_servers(codex_home.path()).await?;
|
||||
assert!(servers.is_empty());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn add_cant_add_command_and_url() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
let mut add_cmd = codex_command(codex_home.path())?;
|
||||
add_cmd
|
||||
.args([
|
||||
"mcp",
|
||||
"add",
|
||||
"github",
|
||||
"--url",
|
||||
"https://example.com/mcp",
|
||||
"--command",
|
||||
"--",
|
||||
"echo",
|
||||
"hello",
|
||||
])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("unexpected argument '--command' found"));
|
||||
|
||||
let servers = load_global_mcp_servers(codex_home.path()).await?;
|
||||
assert!(servers.is_empty());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
511
codex-rs/cli/tests/mcp_list.rs
Normal file
511
codex-rs/cli/tests/mcp_list.rs
Normal file
@@ -0,0 +1,511 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::net::TcpListener;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Result;
|
||||
use codex_config::types::McpServerTransportConfig;
|
||||
use codex_core::config::edit::ConfigEditsBuilder;
|
||||
use codex_core::config::load_global_mcp_servers;
|
||||
use codex_login::CODEX_API_KEY_ENV_VAR;
|
||||
use predicates::prelude::PredicateBooleanExt;
|
||||
use predicates::str::contains;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value as JsonValue;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
#[cfg(target_os = "macos")]
|
||||
use wiremock::Mock;
|
||||
#[cfg(target_os = "macos")]
|
||||
use wiremock::MockServer;
|
||||
#[cfg(target_os = "macos")]
|
||||
use wiremock::ResponseTemplate;
|
||||
#[cfg(target_os = "macos")]
|
||||
use wiremock::matchers::method;
|
||||
#[cfg(target_os = "macos")]
|
||||
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")?);
|
||||
cmd.env("CODEX_HOME", codex_home);
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
async fn configure_http_oauth_server(codex_home: &Path, url: &str) -> Result<()> {
|
||||
let mut servers = load_global_mcp_servers(codex_home).await?;
|
||||
servers.insert(
|
||||
"oauth".to_string(),
|
||||
toml::from_str(&format!("url = \"{url}\""))?,
|
||||
);
|
||||
ConfigEditsBuilder::new(codex_home)
|
||||
.replace_mcp_servers(&servers)
|
||||
.apply_blocking()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_shows_empty_state() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
let mut cmd = codex_command(codex_home.path())?;
|
||||
let output = cmd.args(["mcp", "list"]).output()?;
|
||||
assert!(output.status.success());
|
||||
let stdout = String::from_utf8(output.stdout)?;
|
||||
assert!(stdout.contains("No MCP servers configured yet."));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_key_auth_exposes_api_curated_plugin_mcp_servers() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
r#"[features]
|
||||
plugins = true
|
||||
remote_plugin = false
|
||||
|
||||
[plugins."api-docs@openai-api-curated"]
|
||||
enabled = true
|
||||
"#,
|
||||
)?;
|
||||
let plugin_root = codex_home
|
||||
.path()
|
||||
.join("plugins/cache/openai-api-curated/api-docs/local");
|
||||
std::fs::create_dir_all(plugin_root.join(".codex-plugin"))?;
|
||||
std::fs::write(
|
||||
plugin_root.join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"api-docs","version":"local"}"#,
|
||||
)?;
|
||||
std::fs::write(
|
||||
plugin_root.join(".mcp.json"),
|
||||
r#"{
|
||||
"mcpServers": {
|
||||
"api-docs": {
|
||||
"type": "stdio",
|
||||
"command": "api-docs-mcp"
|
||||
}
|
||||
}
|
||||
}"#,
|
||||
)?;
|
||||
|
||||
let mut list_cmd = codex_command(codex_home.path())?;
|
||||
list_cmd
|
||||
.env(CODEX_API_KEY_ENV_VAR, "sk-test")
|
||||
.args(["mcp", "list", "--json"])
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(contains(r#""name": "api-docs""#));
|
||||
|
||||
let mut get_cmd = codex_command(codex_home.path())?;
|
||||
get_cmd
|
||||
.env(CODEX_API_KEY_ENV_VAR, "sk-test")
|
||||
.args(["mcp", "get", "api-docs", "--json"])
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(contains(r#""name": "api-docs""#));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_discovers_local_oauth_server_through_environment_proxy() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
configure_http_oauth_server(codex_home.path(), "http://mcp-proxy.invalid/mcp").await?;
|
||||
std::fs::write(codex_home.path().join("environments.toml"), "invalid = [")?;
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0")?;
|
||||
listener.set_nonblocking(true)?;
|
||||
let proxy_url = format!("http://{}", listener.local_addr()?);
|
||||
let proxy = std::thread::spawn(move || -> Result<Vec<String>> {
|
||||
let resource_metadata = json!({
|
||||
"resource": "http://mcp-proxy.invalid/mcp",
|
||||
"authorization_servers": ["http://mcp-proxy.invalid"],
|
||||
})
|
||||
.to_string();
|
||||
let authorization_metadata = json!({
|
||||
"authorization_endpoint": "https://oauth.example/authorize",
|
||||
"token_endpoint": "https://oauth.example/token",
|
||||
})
|
||||
.to_string();
|
||||
let responses = [
|
||||
concat!(
|
||||
"HTTP/1.1 401 Unauthorized\r\n",
|
||||
"www-authenticate: Bearer resource_metadata=\"http://mcp-proxy.invalid/oauth-resource\"\r\n",
|
||||
"content-length: 0\r\n",
|
||||
"connection: close\r\n\r\n"
|
||||
)
|
||||
.to_string(),
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{resource_metadata}",
|
||||
resource_metadata.len()
|
||||
),
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{authorization_metadata}",
|
||||
authorization_metadata.len()
|
||||
),
|
||||
];
|
||||
|
||||
let mut requests = Vec::new();
|
||||
for response in responses {
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
let mut stream = loop {
|
||||
match listener.accept() {
|
||||
Ok((stream, _)) => break stream,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
|
||||
anyhow::ensure!(
|
||||
Instant::now() < deadline,
|
||||
"proxy did not receive OAuth discovery request {}",
|
||||
requests.len() + 1
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
};
|
||||
stream.set_nonblocking(false)?;
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5)))?;
|
||||
let mut request = Vec::new();
|
||||
let mut buffer = [0_u8; 1024];
|
||||
while !request.windows(4).any(|window| window == b"\r\n\r\n") {
|
||||
let bytes_read = stream.read(&mut buffer)?;
|
||||
anyhow::ensure!(bytes_read > 0, "proxy request ended before its headers");
|
||||
request.extend_from_slice(&buffer[..bytes_read]);
|
||||
anyhow::ensure!(
|
||||
request.len() <= 64 * 1024,
|
||||
"proxy request headers are too large"
|
||||
);
|
||||
}
|
||||
let request = String::from_utf8(request)?;
|
||||
requests.push(request.lines().next().unwrap_or_default().to_string());
|
||||
stream.write_all(response.as_bytes())?;
|
||||
}
|
||||
|
||||
Ok(requests)
|
||||
});
|
||||
|
||||
let mut command = codex_command(codex_home.path())?;
|
||||
command
|
||||
.env("HTTP_PROXY", &proxy_url)
|
||||
.env("http_proxy", &proxy_url)
|
||||
.env_remove("HTTPS_PROXY")
|
||||
.env_remove("https_proxy")
|
||||
.env_remove("ALL_PROXY")
|
||||
.env_remove("all_proxy")
|
||||
.env_remove("NO_PROXY")
|
||||
.env_remove("no_proxy")
|
||||
.args([
|
||||
"-c",
|
||||
"mcp_oauth_credentials_store=\"file\"",
|
||||
"mcp",
|
||||
"list",
|
||||
"--json",
|
||||
]);
|
||||
let output = command.output()?;
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"mcp list failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let proxy_requests = proxy
|
||||
.join()
|
||||
.expect("OAuth discovery proxy thread should finish")?;
|
||||
|
||||
assert_eq!(
|
||||
proxy_requests,
|
||||
vec![
|
||||
"GET http://mcp-proxy.invalid/mcp HTTP/1.1",
|
||||
"GET http://mcp-proxy.invalid/oauth-resource HTTP/1.1",
|
||||
"GET http://mcp-proxy.invalid/.well-known/oauth-authorization-server HTTP/1.1",
|
||||
]
|
||||
);
|
||||
let entries: JsonValue = serde_json::from_slice(&output.stdout)?;
|
||||
assert_eq!(entries[0]["name"], "oauth");
|
||||
assert_eq!(
|
||||
entries[0]["auth_status"],
|
||||
"not_logged_in",
|
||||
"OAuth discovery failed after proxy requests {proxy_requests:?}; stderr: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn list_reports_unknown_auth_status_when_oauth_discovery_is_rate_limited() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let server = wiremock::MockServer::start().await;
|
||||
wiremock::Mock::given(wiremock::matchers::method("GET"))
|
||||
.and(wiremock::matchers::path("/mcp"))
|
||||
.respond_with(wiremock::ResponseTemplate::new(429))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
configure_http_oauth_server(codex_home.path(), &format!("{}/mcp", server.uri())).await?;
|
||||
|
||||
codex_command(codex_home.path())?
|
||||
.env("NO_PROXY", "127.0.0.1,localhost")
|
||||
.env("no_proxy", "127.0.0.1,localhost")
|
||||
.args([
|
||||
"-c",
|
||||
"mcp_oauth_credentials_store=\"file\"",
|
||||
"mcp",
|
||||
"list",
|
||||
"--json",
|
||||
])
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(contains(r#""auth_status": "unknown""#));
|
||||
server.verify().await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn list_with_macos_proxy_resolution_does_not_panic() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/.well-known/oauth-authorization-server/mcp"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"authorization_endpoint": "https://oauth.example/authorize",
|
||||
"token_endpoint": "https://oauth.example/token",
|
||||
})))
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
configure_http_oauth_server(codex_home.path(), &format!("{}/mcp", server.uri())).await?;
|
||||
|
||||
for respect_system_proxy in [false, true] {
|
||||
let system_proxy_override = format!("features.respect_system_proxy={respect_system_proxy}");
|
||||
let mut command = codex_command(codex_home.path())?;
|
||||
command
|
||||
.env_remove("HTTP_PROXY")
|
||||
.env_remove("http_proxy")
|
||||
.env_remove("HTTPS_PROXY")
|
||||
.env_remove("https_proxy")
|
||||
.env_remove("ALL_PROXY")
|
||||
.env_remove("all_proxy")
|
||||
.env_remove("NO_PROXY")
|
||||
.env_remove("no_proxy")
|
||||
.args([
|
||||
"-c",
|
||||
&system_proxy_override,
|
||||
"-c",
|
||||
"mcp_oauth_credentials_store=\"file\"",
|
||||
"mcp",
|
||||
"list",
|
||||
"--json",
|
||||
]);
|
||||
let output = command.output()?;
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"macOS proxy resolution should not panic with respect_system_proxy={respect_system_proxy}: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let entries: JsonValue = serde_json::from_slice(&output.stdout)?;
|
||||
assert_eq!(entries[0]["auth_status"], "not_logged_in");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_and_get_render_expected_output() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
let mut add = codex_command(codex_home.path())?;
|
||||
add.args([
|
||||
"mcp",
|
||||
"add",
|
||||
"docs",
|
||||
"--env",
|
||||
"TOKEN=secret",
|
||||
"--",
|
||||
"docs-server",
|
||||
"--port",
|
||||
"4000",
|
||||
])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let mut servers = load_global_mcp_servers(codex_home.path()).await?;
|
||||
let docs_entry = servers
|
||||
.get_mut("docs")
|
||||
.expect("docs server should exist after add");
|
||||
match &mut docs_entry.transport {
|
||||
McpServerTransportConfig::Stdio { env_vars, .. } => {
|
||||
*env_vars = vec!["APP_TOKEN".into(), "WORKSPACE_ID".into()];
|
||||
}
|
||||
other => panic!("unexpected transport: {other:?}"),
|
||||
}
|
||||
ConfigEditsBuilder::new(codex_home.path())
|
||||
.replace_mcp_servers(&servers)
|
||||
.apply_blocking()?;
|
||||
|
||||
let mut list_cmd = codex_command(codex_home.path())?;
|
||||
let list_output = list_cmd.args(["mcp", "list"]).output()?;
|
||||
assert!(list_output.status.success());
|
||||
let stdout = String::from_utf8(list_output.stdout)?;
|
||||
assert!(stdout.contains("Name"));
|
||||
assert!(stdout.contains("docs"));
|
||||
assert!(stdout.contains("docs-server"));
|
||||
assert!(stdout.contains("TOKEN=*****"));
|
||||
assert!(stdout.contains("APP_TOKEN=*****"));
|
||||
assert!(stdout.contains("WORKSPACE_ID=*****"));
|
||||
assert!(stdout.contains("Status"));
|
||||
assert!(stdout.contains("Auth"));
|
||||
assert!(stdout.contains("enabled"));
|
||||
assert!(stdout.contains("Unsupported"));
|
||||
|
||||
let mut list_json_cmd = codex_command(codex_home.path())?;
|
||||
let json_output = list_json_cmd.args(["mcp", "list", "--json"]).output()?;
|
||||
assert!(json_output.status.success());
|
||||
let stdout = String::from_utf8(json_output.stdout)?;
|
||||
let parsed: JsonValue = serde_json::from_str(&stdout)?;
|
||||
assert_eq!(
|
||||
parsed,
|
||||
json!([
|
||||
{
|
||||
"name": "docs",
|
||||
"enabled": true,
|
||||
"disabled_reason": null,
|
||||
"transport": {
|
||||
"type": "stdio",
|
||||
"command": "docs-server",
|
||||
"args": [
|
||||
"--port",
|
||||
"4000"
|
||||
],
|
||||
"env": {
|
||||
"TOKEN": "secret"
|
||||
},
|
||||
"env_vars": [
|
||||
"APP_TOKEN",
|
||||
"WORKSPACE_ID"
|
||||
],
|
||||
"cwd": null
|
||||
},
|
||||
"startup_timeout_sec": null,
|
||||
"tool_timeout_sec": null,
|
||||
"auth_status": "unsupported"
|
||||
}
|
||||
]
|
||||
)
|
||||
);
|
||||
|
||||
let mut get_cmd = codex_command(codex_home.path())?;
|
||||
let get_output = get_cmd.args(["mcp", "get", "docs"]).output()?;
|
||||
assert!(get_output.status.success());
|
||||
let stdout = String::from_utf8(get_output.stdout)?;
|
||||
assert!(stdout.contains("docs"));
|
||||
assert!(stdout.contains("transport: stdio"));
|
||||
assert!(stdout.contains("command: docs-server"));
|
||||
assert!(stdout.contains("args: --port 4000"));
|
||||
assert!(stdout.contains("env: TOKEN=*****"));
|
||||
assert!(stdout.contains("APP_TOKEN=*****"));
|
||||
assert!(stdout.contains("WORKSPACE_ID=*****"));
|
||||
assert!(stdout.contains("enabled: true"));
|
||||
assert!(stdout.contains("remove: codex mcp remove docs"));
|
||||
|
||||
let mut get_json_cmd = codex_command(codex_home.path())?;
|
||||
get_json_cmd
|
||||
.args(["mcp", "get", "docs", "--json"])
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(contains("\"name\": \"docs\"").and(contains("\"enabled\": true")));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_and_get_redact_http_headers_helper() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let marker = codex_home.path().join("helper-ran");
|
||||
let helper = toml::Value::String(format!("echo invoked > \"{}\"", marker.display()));
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
format!(
|
||||
"[mcp_servers.docs]\n\
|
||||
url = \"https://example.com/mcp\"\n\
|
||||
http_headers_helper = {helper}\n\
|
||||
[mcp_servers.authenticated]\n\
|
||||
url = \"https://example.com/mcp\"\n\
|
||||
http_headers = {{ Authorization = \"Bearer static\" }}\n\
|
||||
http_headers_helper = {helper}\n"
|
||||
),
|
||||
)?;
|
||||
|
||||
let list_output = codex_command(codex_home.path())?
|
||||
.args(["mcp", "list", "--json"])
|
||||
.output()?;
|
||||
assert!(list_output.status.success());
|
||||
let stdout = String::from_utf8(list_output.stdout)?;
|
||||
assert!(stdout.contains("http_headers_helper"));
|
||||
assert!(stdout.contains("<redacted>"));
|
||||
let entries: Vec<JsonValue> = serde_json::from_str(&stdout)?;
|
||||
let auth_statuses = entries
|
||||
.into_iter()
|
||||
.map(|entry| {
|
||||
(
|
||||
entry["name"].as_str().expect("server name").to_string(),
|
||||
entry["auth_status"]
|
||||
.as_str()
|
||||
.expect("auth status")
|
||||
.to_string(),
|
||||
)
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
assert_eq!(
|
||||
auth_statuses,
|
||||
BTreeMap::from([
|
||||
("authenticated".to_string(), "bearer_token".to_string()),
|
||||
("docs".to_string(), "unknown".to_string()),
|
||||
])
|
||||
);
|
||||
assert!(!marker.exists());
|
||||
|
||||
for args in [
|
||||
&["mcp", "get", "docs", "--json"][..],
|
||||
&["mcp", "get", "docs"][..],
|
||||
] {
|
||||
let output = codex_command(codex_home.path())?.args(args).output()?;
|
||||
assert!(output.status.success());
|
||||
let stdout = String::from_utf8(output.stdout)?;
|
||||
assert!(stdout.contains("http_headers_helper"));
|
||||
assert!(stdout.contains("<redacted>"));
|
||||
assert!(!stdout.contains("helper-ran"));
|
||||
assert!(!marker.exists());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_disabled_server_shows_single_line() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
let mut add = codex_command(codex_home.path())?;
|
||||
add.args(["mcp", "add", "docs", "--", "docs-server"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let mut servers = load_global_mcp_servers(codex_home.path()).await?;
|
||||
let docs = servers
|
||||
.get_mut("docs")
|
||||
.expect("docs server should exist after add");
|
||||
docs.enabled = false;
|
||||
ConfigEditsBuilder::new(codex_home.path())
|
||||
.replace_mcp_servers(&servers)
|
||||
.apply_blocking()?;
|
||||
|
||||
let mut get_cmd = codex_command(codex_home.path())?;
|
||||
let get_output = get_cmd.args(["mcp", "get", "docs"]).output()?;
|
||||
assert!(get_output.status.success());
|
||||
let stdout = String::from_utf8(get_output.stdout)?;
|
||||
assert_eq!(stdout.trim_end(), "docs (disabled)");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
632
codex-rs/cli/tests/mcp_login.rs
Normal file
632
codex-rs/cli/tests/mcp_login.rs
Normal file
@@ -0,0 +1,632 @@
|
||||
//! Exercises terminal OAuth pasteback and its shared callback validation through the CLI.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::process::Output;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use codex_core::config::load_global_mcp_servers;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::process::Child;
|
||||
use tokio::process::ChildStdout;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
use url::Url;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
const TEST_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
struct Fixture {
|
||||
server: MockServer,
|
||||
home: TempDir,
|
||||
issuer: String,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
async fn new(client_secret: Option<&'static str>) -> Result<Self> {
|
||||
Self::with_scopes(client_secret, &["mcp.read"]).await
|
||||
}
|
||||
|
||||
async fn with_scopes(client_secret: Option<&'static str>, scopes: &[&str]) -> Result<Self> {
|
||||
let server = MockServer::start().await;
|
||||
let home = TempDir::new()?;
|
||||
let issuer = format!("{}/mcp", server.uri());
|
||||
let saved_client_secret = client_secret
|
||||
.map(|secret| format!("client_secret = \"{secret}\"\n"))
|
||||
.unwrap_or_default();
|
||||
let saved_scopes = if scopes.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("scopes = {scopes:?}\n")
|
||||
};
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!(
|
||||
"mcp_oauth_credentials_store = \"file\"\n\
|
||||
[mcp_servers.manual]\nurl = \"{issuer}\"\n{saved_scopes}\
|
||||
[mcp_servers.manual.oauth]\nclient_id = \"registered-client\"\n\
|
||||
{saved_client_secret}"
|
||||
),
|
||||
)?;
|
||||
let fixture = Self {
|
||||
server,
|
||||
home,
|
||||
issuer,
|
||||
};
|
||||
fixture.mount_oauth(client_secret).await;
|
||||
Ok(fixture)
|
||||
}
|
||||
|
||||
async fn mount_oauth(&self, client_secret: Option<&'static str>) {
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/.well-known/oauth-authorization-server/mcp"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"issuer": self.issuer,
|
||||
"authorization_endpoint": format!("{}/authorize", self.server.uri()),
|
||||
"token_endpoint": format!("{}/token", self.server.uri()),
|
||||
"response_types_supported": ["code"],
|
||||
"code_challenge_methods_supported": ["S256"],
|
||||
"scopes_supported": ["mcp.read"],
|
||||
"authorization_response_iss_parameter_supported": true,
|
||||
"token_endpoint_auth_methods_supported": [if client_secret.is_some() {
|
||||
"client_secret_post"
|
||||
} else {
|
||||
"none"
|
||||
}],
|
||||
})))
|
||||
.mount(&self.server)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/token"))
|
||||
.and(move |request: &wiremock::Request| {
|
||||
let body: BTreeMap<_, _> = url::form_urlencoded::parse(&request.body)
|
||||
.into_owned()
|
||||
.collect();
|
||||
body.get("client_secret").map(String::as_str) == client_secret
|
||||
})
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"access_token": "mock-access-token",
|
||||
"token_type": "Bearer",
|
||||
"refresh_token": "mock-refresh-token",
|
||||
"scope": "mcp.read",
|
||||
})))
|
||||
.mount(&self.server)
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn mount_resource_metadata(&self, scopes: &[&str], challenge_scope: Option<&str>) {
|
||||
let mut challenge = format!(
|
||||
"Bearer resource_metadata=\"{}/resource-metadata\"",
|
||||
self.server.uri()
|
||||
);
|
||||
if let Some(scope) = challenge_scope {
|
||||
challenge.push_str(&format!(", scope=\"{scope}\""));
|
||||
}
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/mcp"))
|
||||
.respond_with(ResponseTemplate::new(401).insert_header("www-authenticate", challenge))
|
||||
.mount(&self.server)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/resource-metadata"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"resource": self.issuer,
|
||||
"authorization_servers": [self.issuer],
|
||||
"scopes_supported": scopes,
|
||||
})))
|
||||
.mount(&self.server)
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn start(&self) -> Result<Login> {
|
||||
let mut child = Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
|
||||
.kill_on_drop(true)
|
||||
.current_dir(self.home.path())
|
||||
.env("CODEX_HOME", self.home.path())
|
||||
.env("NO_PROXY", "127.0.0.1,localhost")
|
||||
.env("no_proxy", "127.0.0.1,localhost")
|
||||
.args(["mcp", "login", "manual", "--no-browser"])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()?;
|
||||
let mut stdout = BufReader::new(child.stdout.take().context("missing stdout")?);
|
||||
let mut transcript = String::new();
|
||||
let authorization_url = match read_authorization_url(&mut stdout, &mut transcript).await {
|
||||
Ok(authorization_url) => authorization_url,
|
||||
Err(error) => {
|
||||
let mut stderr = String::new();
|
||||
if let Some(stderr_pipe) = child.stderr.take() {
|
||||
let _ = timeout(
|
||||
Duration::from_secs(1),
|
||||
stderr_pipe.take(/*limit*/ 4096).read_to_string(&mut stderr),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
return Err(error.context(format!("MCP login stderr: {stderr}")));
|
||||
}
|
||||
};
|
||||
Ok(Login {
|
||||
child,
|
||||
stdout,
|
||||
transcript,
|
||||
authorization_url,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_authorization_url(
|
||||
stdout: &mut BufReader<ChildStdout>,
|
||||
transcript: &mut String,
|
||||
) -> Result<Url> {
|
||||
timeout(TEST_TIMEOUT, async {
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
if stdout.read_line(&mut line).await? == 0 {
|
||||
bail!("login exited before printing its authorization URL: {transcript}");
|
||||
}
|
||||
transcript.push_str(&line);
|
||||
if line.starts_with("http://") {
|
||||
return Ok(Url::parse(line.trim())?);
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.context("authorization URL timeout")?
|
||||
}
|
||||
|
||||
struct Login {
|
||||
child: Child,
|
||||
stdout: BufReader<ChildStdout>,
|
||||
transcript: String,
|
||||
authorization_url: Url,
|
||||
}
|
||||
|
||||
impl Login {
|
||||
fn callback(&self, issuer: &str) -> Result<Url> {
|
||||
let params: BTreeMap<_, _> = self.authorization_url.query_pairs().into_owned().collect();
|
||||
let mut callback = Url::parse(¶ms["redirect_uri"])?;
|
||||
callback
|
||||
.query_pairs_mut()
|
||||
.append_pair("code", "mock-code")
|
||||
.append_pair("state", ¶ms["state"])
|
||||
.append_pair("iss", issuer);
|
||||
Ok(callback)
|
||||
}
|
||||
|
||||
async fn finish(mut self) -> Result<Output> {
|
||||
let (mut output, _) = timeout(TEST_TIMEOUT, async {
|
||||
tokio::try_join!(
|
||||
self.child.wait_with_output(),
|
||||
self.stdout.read_to_string(&mut self.transcript),
|
||||
)
|
||||
})
|
||||
.await
|
||||
.context("login completion timeout")??;
|
||||
output.stdout = self.transcript.into_bytes();
|
||||
Ok(output)
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_browser_exchanges_pasted_callback_and_saves_credentials() -> Result<()> {
|
||||
let fixture = Fixture::new(/*client_secret*/ None).await?;
|
||||
assert_no_browser_exchanges_pasted_callback_and_saves_credentials(
|
||||
fixture, /*client_secret*/ None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_browser_prefers_challenge_scopes_for_preregistered_client() -> Result<()> {
|
||||
let fixture = Fixture::with_scopes(/*client_secret*/ None, &[]).await?;
|
||||
fixture
|
||||
.mount_resource_metadata(&["mcp.read", "mcp.write"], Some("mcp.read"))
|
||||
.await;
|
||||
// The authorization server advertises neither scopes nor dynamic registration.
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/.well-known/oauth-authorization-server/mcp"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"issuer": fixture.issuer,
|
||||
"authorization_endpoint": format!("{}/authorize", fixture.server.uri()),
|
||||
"token_endpoint": format!("{}/token", fixture.server.uri()),
|
||||
"response_types_supported": ["code"],
|
||||
"code_challenge_methods_supported": ["S256"],
|
||||
})))
|
||||
.with_priority(/*priority*/ 1)
|
||||
.mount(&fixture.server)
|
||||
.await;
|
||||
|
||||
assert_no_browser_exchanges_pasted_callback_and_saves_credentials(
|
||||
fixture, /*client_secret*/ None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_browser_exchanges_pasted_callback_with_client_secret() -> Result<()> {
|
||||
let fixture = Fixture::new(Some("headless-client-secret")).await?;
|
||||
assert_no_browser_exchanges_pasted_callback_and_saves_credentials(
|
||||
fixture,
|
||||
Some("headless-client-secret"),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn add_persists_client_secret_for_subsequent_login_without_disclosure() -> Result<()> {
|
||||
const CLIENT_SECRET: &str = "cli-client-secret";
|
||||
let fixture = Fixture::new(Some(CLIENT_SECRET)).await?;
|
||||
std::fs::write(
|
||||
fixture.home.path().join("config.toml"),
|
||||
"mcp_oauth_credentials_store = \"file\"\n",
|
||||
)?;
|
||||
// Stop automatic login before browser launch, then retry with valid metadata.
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/.well-known/oauth-authorization-server/mcp"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"issuer": fixture.issuer,
|
||||
"authorization_endpoint": "not-a-valid-authorization-url",
|
||||
"token_endpoint": format!("{}/token", fixture.server.uri()),
|
||||
"authorization_response_iss_parameter_supported": true,
|
||||
})))
|
||||
.with_priority(/*priority*/ 1)
|
||||
.mount(&fixture.server)
|
||||
.await;
|
||||
let output = timeout(
|
||||
TEST_TIMEOUT,
|
||||
Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
|
||||
.kill_on_drop(true)
|
||||
.current_dir(fixture.home.path())
|
||||
.env("CODEX_HOME", fixture.home.path())
|
||||
.env("NO_PROXY", "127.0.0.1,localhost")
|
||||
.env("no_proxy", "127.0.0.1,localhost")
|
||||
.args([
|
||||
"mcp",
|
||||
"add",
|
||||
"manual",
|
||||
"--url",
|
||||
&fixture.issuer,
|
||||
"--oauth-client-id",
|
||||
"registered-client",
|
||||
"--oauth-client-secret",
|
||||
CLIENT_SECRET,
|
||||
])
|
||||
.output(),
|
||||
)
|
||||
.await??;
|
||||
assert!(!output.status.success());
|
||||
let stdout = String::from_utf8(output.stdout)?;
|
||||
let stderr = String::from_utf8(output.stderr)?;
|
||||
assert!(stdout.contains("Detected OAuth support. Starting OAuth flow"));
|
||||
assert!(!stdout.contains(CLIENT_SECRET));
|
||||
assert!(!stderr.contains(CLIENT_SECRET));
|
||||
let servers = load_global_mcp_servers(fixture.home.path()).await?;
|
||||
assert_eq!(servers["manual"].oauth_client_secret(), Some(CLIENT_SECRET));
|
||||
// Reset removes the priority override without relying on wiremock's scoped indices.
|
||||
fixture.server.reset().await;
|
||||
fixture.mount_oauth(Some(CLIENT_SECRET)).await;
|
||||
fixture
|
||||
.mount_resource_metadata(&["mcp.read"], /*challenge_scope*/ None)
|
||||
.await;
|
||||
|
||||
assert_no_browser_exchanges_pasted_callback_and_saves_credentials(fixture, Some(CLIENT_SECRET))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn assert_no_browser_exchanges_pasted_callback_and_saves_credentials(
|
||||
fixture: Fixture,
|
||||
client_secret: Option<&'static str>,
|
||||
) -> Result<()> {
|
||||
let mut login = fixture.start().await?;
|
||||
let authorization_url = login.authorization_url.to_string();
|
||||
let params: BTreeMap<_, _> = login.authorization_url.query_pairs().into_owned().collect();
|
||||
assert_eq!(params.get("scope").map(String::as_str), Some("mcp.read"));
|
||||
let callback = login.callback(&fixture.issuer)?;
|
||||
login
|
||||
.child
|
||||
.stdin
|
||||
.as_mut()
|
||||
.context("missing stdin")?
|
||||
.write_all(format!("{callback}\n").as_bytes())
|
||||
.await?;
|
||||
let output = login.finish().await?;
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let stdout = String::from_utf8(output.stdout)?;
|
||||
let stderr = String::from_utf8(output.stderr)?;
|
||||
if let Some(client_secret) = client_secret {
|
||||
assert!(!stdout.contains(client_secret));
|
||||
assert!(!stderr.contains(client_secret));
|
||||
}
|
||||
insta::allow_duplicates! {
|
||||
insta::assert_snapshot!(stdout.replace(&authorization_url, "[AUTHORIZATION_URL]"), @r"
|
||||
Authorize the MCP server by opening this URL in your browser:
|
||||
[AUTHORIZATION_URL]
|
||||
|
||||
After signing in, copy the full URL from your browser's address bar.
|
||||
If the callback page cannot load, paste that URL here anyway.
|
||||
Successfully logged in to MCP server 'manual'.
|
||||
");
|
||||
}
|
||||
assert!(stderr.contains("Callback URL (input hidden): "));
|
||||
let requests = fixture
|
||||
.server
|
||||
.received_requests()
|
||||
.await
|
||||
.context("missing requests")?;
|
||||
let tokens: Vec<_> = requests
|
||||
.iter()
|
||||
.filter(|r| r.url.path() == "/token")
|
||||
.collect();
|
||||
assert_eq!(tokens.len(), 1);
|
||||
let mut exchange: BTreeMap<_, _> = url::form_urlencoded::parse(&tokens[0].body)
|
||||
.into_owned()
|
||||
.collect();
|
||||
let verifier = exchange
|
||||
.remove("code_verifier")
|
||||
.context("missing PKCE verifier")?;
|
||||
assert!((43..=128).contains(&verifier.len()));
|
||||
assert_eq!(params["code_challenge_method"], "S256");
|
||||
assert!(!params["code_challenge"].is_empty());
|
||||
let mut expected_exchange = BTreeMap::from([
|
||||
("client_id".to_string(), "registered-client".to_string()),
|
||||
("code".to_string(), "mock-code".to_string()),
|
||||
("grant_type".to_string(), "authorization_code".to_string()),
|
||||
("redirect_uri".to_string(), params["redirect_uri"].clone()),
|
||||
("resource".to_string(), fixture.issuer.clone()),
|
||||
]);
|
||||
if let Some(client_secret) = client_secret {
|
||||
expected_exchange.insert("client_secret".to_string(), client_secret.to_string());
|
||||
}
|
||||
assert_eq!(exchange, expected_exchange);
|
||||
let credentials: BTreeMap<String, Value> = serde_json::from_slice(&std::fs::read(
|
||||
fixture.home.path().join(".credentials.json"),
|
||||
)?)?;
|
||||
assert_eq!(
|
||||
credentials.into_values().collect::<Vec<_>>(),
|
||||
vec![json!({
|
||||
"server_name": "manual", "server_url": fixture.issuer, "issuer": fixture.issuer,
|
||||
"client_id": "registered-client", "access_token": "mock-access-token",
|
||||
"refresh_token": "mock-refresh-token", "expires_at": null, "scopes": ["mcp.read"],
|
||||
})]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_browser_rejects_invalid_callbacks_without_exchanging_tokens() -> Result<()> {
|
||||
for (field, value) in [
|
||||
("state", Some("wrong-state")),
|
||||
("iss", None),
|
||||
("iss", Some("https://secret-issuer-marker.example")),
|
||||
("eof", None),
|
||||
] {
|
||||
let fixture = Fixture::new(/*client_secret*/ None).await?;
|
||||
let mut login = fixture.start().await?;
|
||||
let mut callback = login.callback(&fixture.issuer)?;
|
||||
let mut pairs: BTreeMap<_, _> = callback.query_pairs().into_owned().collect();
|
||||
pairs.remove(field);
|
||||
if let Some(value) = value {
|
||||
pairs.insert(field.to_string(), value.to_string());
|
||||
}
|
||||
callback.set_query(None);
|
||||
callback.query_pairs_mut().extend_pairs(pairs);
|
||||
if field == "eof" {
|
||||
drop(login.child.stdin.take());
|
||||
} else {
|
||||
login
|
||||
.child
|
||||
.stdin
|
||||
.as_mut()
|
||||
.context("missing stdin")?
|
||||
.write_all(format!("{callback}\n").as_bytes())
|
||||
.await?;
|
||||
}
|
||||
let output = login.finish().await?;
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"accepted invalid {field}: {value:?}"
|
||||
);
|
||||
let stderr = String::from_utf8(output.stderr)?;
|
||||
for secret in ["mock-code", "secret-issuer-marker"] {
|
||||
assert!(
|
||||
!stderr.contains(secret),
|
||||
"callback error leaked {secret}: {stderr}"
|
||||
);
|
||||
}
|
||||
assert!(!fixture.home.path().join(".credentials.json").exists());
|
||||
assert!(
|
||||
fixture
|
||||
.server
|
||||
.received_requests()
|
||||
.await
|
||||
.context("missing requests")?
|
||||
.iter()
|
||||
.all(|request| request.url.path() != "/token")
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_browser_accepts_http_callback_while_terminal_input_remains_open() -> Result<()> {
|
||||
let fixture = Fixture::new(/*client_secret*/ None).await?;
|
||||
let mut login = fixture.start().await?;
|
||||
let callback = login.callback(&fixture.issuer)?;
|
||||
let stdin = login.child.stdin.take().context("missing stdin")?;
|
||||
let mut stream = TcpStream::connect((
|
||||
"127.0.0.1",
|
||||
callback.port().context("missing callback port")?,
|
||||
))
|
||||
.await?;
|
||||
stream
|
||||
.write_all(
|
||||
format!(
|
||||
"GET {}?{} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
|
||||
callback.path(),
|
||||
callback.query().context("missing callback query")?
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.await?;
|
||||
let output = login.finish().await?;
|
||||
drop(stdin);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert!(fixture.home.path().join(".credentials.json").exists());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_browser_retries_rejected_discovered_scopes_with_pasteback() -> Result<()> {
|
||||
let fixture = Fixture::with_scopes(/*client_secret*/ None, &[]).await?;
|
||||
fixture
|
||||
.mount_resource_metadata(&["mcp.read"], /*challenge_scope*/ None)
|
||||
.await;
|
||||
let mut login = fixture.start().await?;
|
||||
assert!(
|
||||
login
|
||||
.authorization_url
|
||||
.query_pairs()
|
||||
.any(|(key, value)| key == "scope" && value == "mcp.read")
|
||||
);
|
||||
let mut callback = login.callback(&fixture.issuer)?;
|
||||
let mut params: BTreeMap<_, _> = callback.query_pairs().into_owned().collect();
|
||||
params.remove("code");
|
||||
params.insert("error".to_string(), "invalid_scope".to_string());
|
||||
callback.set_query(None);
|
||||
callback.query_pairs_mut().extend_pairs(params);
|
||||
login
|
||||
.child
|
||||
.stdin
|
||||
.as_mut()
|
||||
.context("missing stdin")?
|
||||
.write_all(format!("{callback}\n").as_bytes())
|
||||
.await?;
|
||||
login.authorization_url =
|
||||
read_authorization_url(&mut login.stdout, &mut login.transcript).await?;
|
||||
assert!(
|
||||
!login
|
||||
.authorization_url
|
||||
.query_pairs()
|
||||
.any(|(key, _)| key == "scope")
|
||||
);
|
||||
let callback = login.callback(&fixture.issuer)?;
|
||||
login
|
||||
.child
|
||||
.stdin
|
||||
.as_mut()
|
||||
.context("missing stdin")?
|
||||
.write_all(format!("{callback}\n").as_bytes())
|
||||
.await?;
|
||||
let output = login.finish().await?;
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert!(String::from_utf8(output.stdout)?.contains("Retrying without scopes"));
|
||||
let requests = fixture
|
||||
.server
|
||||
.received_requests()
|
||||
.await
|
||||
.context("missing requests")?;
|
||||
assert_eq!(
|
||||
requests
|
||||
.iter()
|
||||
.filter(|request| request.url.path() == "/token")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn no_browser_sigint_cancels_token_exchange_after_pasted_or_http_callback() -> Result<()> {
|
||||
for callback_delivery in ["paste", "http"] {
|
||||
let fixture = Fixture::new(/*client_secret*/ None).await?;
|
||||
let request_started = std::sync::Arc::new(tokio::sync::Notify::new());
|
||||
let notify = std::sync::Arc::clone(&request_started);
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/token"))
|
||||
.respond_with(move |_: &wiremock::Request| {
|
||||
notify.notify_one();
|
||||
ResponseTemplate::new(200)
|
||||
.set_delay(Duration::from_secs(/*secs*/ 30))
|
||||
.set_body_json(
|
||||
json!({"access_token": "mock-access-token", "token_type": "Bearer"}),
|
||||
)
|
||||
})
|
||||
.with_priority(/*priority*/ 1)
|
||||
.expect(1)
|
||||
.mount(&fixture.server)
|
||||
.await;
|
||||
let mut login = fixture.start().await?;
|
||||
let callback = login.callback(&fixture.issuer)?;
|
||||
// Keep the input pipe open after an HTTP callback, including while waiting for exit.
|
||||
let mut stdin = login.child.stdin.take().context("missing stdin")?;
|
||||
let mut http_callback = None;
|
||||
if callback_delivery == "http" {
|
||||
let mut stream = TcpStream::connect((
|
||||
"127.0.0.1",
|
||||
callback.port().context("missing callback port")?,
|
||||
))
|
||||
.await?;
|
||||
stream
|
||||
.write_all(
|
||||
format!(
|
||||
"GET {}?{} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
|
||||
callback.path(),
|
||||
callback.query().context("missing callback query")?,
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.await?;
|
||||
http_callback = Some(stream);
|
||||
} else {
|
||||
stdin.write_all(format!("{callback}\n").as_bytes()).await?;
|
||||
}
|
||||
timeout(TEST_TIMEOUT, request_started.notified())
|
||||
.await
|
||||
.context("token exchange never started")?;
|
||||
let child_pid = i32::try_from(login.child.id().context("login exited before SIGINT")?)?;
|
||||
// SAFETY: this positive PID belongs to the live child process owned by this test.
|
||||
assert_eq!(unsafe { libc::kill(child_pid, libc::SIGINT) }, 0);
|
||||
let output = timeout(Duration::from_secs(/*secs*/ 5), login.finish())
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!("SIGINT did not cancel {callback_delivery} callback token exchange")
|
||||
})??;
|
||||
drop((stdin, http_callback));
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"SIGINT login unexpectedly succeeded"
|
||||
);
|
||||
assert!(String::from_utf8(output.stderr)?.contains("OAuth login cancelled"));
|
||||
assert!(!fixture.home.path().join(".credentials.json").exists());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
132
codex-rs/cli/tests/migrate_nfs_db.rs
Normal file
132
codex-rs/cli/tests/migrate_nfs_db.rs
Normal file
@@ -0,0 +1,132 @@
|
||||
//! Exercise migration consent, permissions, and accurate partial/no-op reporting.
|
||||
|
||||
#![cfg(unix)]
|
||||
|
||||
use anyhow::Result;
|
||||
use codex_state::SqliteConfig;
|
||||
use predicates::prelude::PredicateBooleanExt;
|
||||
use predicates::str::contains;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
#[tokio::test]
|
||||
async fn migration_requires_consent_and_preserves_shared_database_mode() -> Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let sqlite = SqliteConfig::new_for_testing(home.path().to_path_buf().try_into()?);
|
||||
let mut empty = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
let empty = empty
|
||||
.env("CODEX_HOME", home.path())
|
||||
.env(codex_state::SQLITE_HOME_ENV, home.path())
|
||||
.arg("migrate-nfs-db")
|
||||
.write_stdin("y\n")
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(
|
||||
contains("No databases found").and(contains("Migration completed successfully").not()),
|
||||
);
|
||||
insta::assert_snapshot!(
|
||||
String::from_utf8_lossy(&empty.get_output().stdout)
|
||||
.replace(home.path().to_str().unwrap(), "[HOME]"),
|
||||
@"No databases found."
|
||||
);
|
||||
let path = sqlite.state_db_path();
|
||||
let pool = sqlite.open_read_write_pool(&path).await?;
|
||||
sqlx::raw_sql("CREATE TABLE entries (id INTEGER); INSERT INTO entries VALUES (42)")
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
pool.close().await;
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(/*mode*/ 0o600))?;
|
||||
let mut command = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
let declined = command
|
||||
.env("CODEX_HOME", home.path())
|
||||
.env(codex_state::SQLITE_HOME_ENV, home.path())
|
||||
.arg("migrate-nfs-db")
|
||||
.write_stdin("n\n")
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("permissions other than 0600").not())
|
||||
.stderr(contains("Continue? [y/N]"));
|
||||
let stderr = String::from_utf8_lossy(&declined.get_output().stderr);
|
||||
let disclosure = stderr
|
||||
.find("the original owner, group, and extended ACLs are not copied")
|
||||
.unwrap();
|
||||
let consent = stderr.find("Continue? [y/N]").unwrap();
|
||||
assert!(
|
||||
disclosure < consent,
|
||||
"ACL loss must be disclosed before consent, including for 0600 files"
|
||||
);
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(/*mode*/ 0o644))?;
|
||||
let before = std::fs::read(&path)?;
|
||||
|
||||
let mut command = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
command
|
||||
.env("CODEX_HOME", home.path())
|
||||
.env(codex_state::SQLITE_HOME_ENV, home.path())
|
||||
.arg("migrate-nfs-db")
|
||||
.write_stdin("n\n")
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("permissions other than 0600"))
|
||||
.stderr(contains("No databases were changed"));
|
||||
assert_eq!(std::fs::read(&path)?, before);
|
||||
|
||||
// A later corrupt database must be reported without undoing a completed conversion.
|
||||
std::fs::write(sqlite.logs_db_path(), b"corrupt SQLite database")?;
|
||||
let mut partial = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
let partial = partial
|
||||
.env("CODEX_HOME", home.path())
|
||||
.env(codex_state::SQLITE_HOME_ENV, home.path())
|
||||
.arg("migrate-nfs-db")
|
||||
.write_stdin("y\n")
|
||||
.assert()
|
||||
.failure()
|
||||
.stdout(
|
||||
contains("Migrated database").and(contains("Migration completed successfully").not()),
|
||||
)
|
||||
.stderr(contains("migration failed for"));
|
||||
let stderr = String::from_utf8_lossy(&partial.get_output().stderr);
|
||||
insta::assert_snapshot!(
|
||||
stderr
|
||||
.lines()
|
||||
.find(|line| line.starts_with("Error: migration failed"))
|
||||
.unwrap()
|
||||
.replace(home.path().to_str().unwrap(), "[HOME]"),
|
||||
@"Error: migration failed for [HOME]/logs_2.sqlite. Keep all Codex instances stopped. Correct the error and rerun codex migrate-nfs-db"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(sqlite.logs_db_path())?,
|
||||
b"corrupt SQLite database"
|
||||
);
|
||||
std::fs::remove_file(sqlite.logs_db_path())?;
|
||||
|
||||
let mut command = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
command
|
||||
.env("CODEX_HOME", home.path())
|
||||
.env(codex_state::SQLITE_HOME_ENV, home.path())
|
||||
.arg("migrate-nfs-db")
|
||||
.write_stdin("y\n")
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(
|
||||
contains("Already in DELETE mode").and(contains("Migration completed successfully")),
|
||||
);
|
||||
let pool = sqlite
|
||||
.open_read_only_pool(&path, /*busy_timeout*/ None)
|
||||
.await?;
|
||||
let mode: String = sqlx::query_scalar("PRAGMA journal_mode")
|
||||
.fetch_one(&pool)
|
||||
.await?;
|
||||
let rows: Vec<i64> = sqlx::query_scalar("SELECT id FROM entries")
|
||||
.fetch_all(&pool)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
(
|
||||
mode,
|
||||
rows,
|
||||
std::fs::metadata(&path)?.permissions().mode() & 0o777
|
||||
),
|
||||
("delete".to_string(), vec![42], 0o644)
|
||||
);
|
||||
pool.close().await;
|
||||
Ok(())
|
||||
}
|
||||
1938
codex-rs/cli/tests/plugin_cli.rs
Normal file
1938
codex-rs/cli/tests/plugin_cli.rs
Normal file
File diff suppressed because it is too large
Load Diff
703
codex-rs/cli/tests/queue.rs
Normal file
703
codex-rs/cli/tests/queue.rs
Normal file
@@ -0,0 +1,703 @@
|
||||
use std::path::Path;
|
||||
use std::process::Output;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio_tungstenite::accept_async;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
|
||||
const THREAD_ID: &str = "123e4567-e89b-12d3-a456-426614174000";
|
||||
|
||||
enum QueueResponse {
|
||||
Success,
|
||||
ResumeRejected,
|
||||
MethodNotFound,
|
||||
#[cfg(unix)]
|
||||
UnknownMethodVariant,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn socket_test_home() -> Result<TempDir> {
|
||||
// macOS temporary paths can exceed the Unix socket path limit.
|
||||
#[cfg(target_os = "macos")]
|
||||
let home = tempfile::tempdir_in("/tmp")?;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let home = TempDir::new()?;
|
||||
Ok(home)
|
||||
}
|
||||
|
||||
async fn respond_to_queue_request<S>(
|
||||
stream: S,
|
||||
codex_home: &Path,
|
||||
response: QueueResponse,
|
||||
) -> Result<Value>
|
||||
where
|
||||
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
|
||||
{
|
||||
let mut websocket = accept_async(stream).await?;
|
||||
let initialize = websocket
|
||||
.next()
|
||||
.await
|
||||
.context("missing initialize request")??;
|
||||
let initialize: Value = serde_json::from_str(initialize.to_text()?)?;
|
||||
assert_eq!(initialize["method"], "initialize");
|
||||
assert_eq!(
|
||||
initialize["params"]["capabilities"]["experimentalApi"],
|
||||
true
|
||||
);
|
||||
let initialized_response = json!({
|
||||
"id": initialize["id"],
|
||||
"result": {
|
||||
"userAgent": "codex_cli_rs/0.0.0-test",
|
||||
"codexHome": codex_home,
|
||||
},
|
||||
});
|
||||
websocket
|
||||
.send(Message::Text(initialized_response.to_string().into()))
|
||||
.await?;
|
||||
|
||||
let initialized = websocket
|
||||
.next()
|
||||
.await
|
||||
.context("missing initialized notification")??;
|
||||
let initialized: Value = serde_json::from_str(initialized.to_text()?)?;
|
||||
assert_eq!(initialized["method"], "initialized");
|
||||
|
||||
let request = websocket.next().await.context("missing queue request")??;
|
||||
let request: Value = serde_json::from_str(request.to_text()?)?;
|
||||
assert_eq!(request["method"], "thread/queue/add");
|
||||
assert_eq!(request["params"]["threadId"], THREAD_ID);
|
||||
|
||||
let result = match response {
|
||||
QueueResponse::Success | QueueResponse::ResumeRejected => json!({
|
||||
"id": request["id"],
|
||||
"result": {
|
||||
"queuedSubmission": {
|
||||
"id": "queued-submission-id",
|
||||
"input": request["params"]["input"],
|
||||
"clientUserMessageId": request["params"]["clientUserMessageId"],
|
||||
},
|
||||
},
|
||||
}),
|
||||
QueueResponse::MethodNotFound => json!({
|
||||
"id": request["id"],
|
||||
"error": { "code": -32601, "message": "Method not found" },
|
||||
}),
|
||||
#[cfg(unix)]
|
||||
QueueResponse::UnknownMethodVariant => json!({
|
||||
"id": request["id"],
|
||||
"error": {
|
||||
"code": -32600,
|
||||
"message": "Invalid request: unknown variant `thread/queue/add`, expected `thread/list`",
|
||||
},
|
||||
}),
|
||||
};
|
||||
websocket
|
||||
.send(Message::Text(result.to_string().into()))
|
||||
.await?;
|
||||
if matches!(response, QueueResponse::ResumeRejected) {
|
||||
for (method, mut reply) in [
|
||||
(
|
||||
"thread/read",
|
||||
json!({"result": {"thread": {"status": {"type": "notLoaded"}, "cwd": r"C:\workspace"}}}),
|
||||
),
|
||||
(
|
||||
"thread/resume",
|
||||
json!({"error": {"code": -32603, "message": "thread already has an active writer"}}),
|
||||
),
|
||||
] {
|
||||
let rpc = websocket.next().await.context("missing resume request")??;
|
||||
let rpc: Value = serde_json::from_str(rpc.to_text()?)?;
|
||||
assert_eq!(rpc["method"], method);
|
||||
assert_eq!(rpc["params"]["threadId"], THREAD_ID);
|
||||
reply["id"] = rpc["id"].clone();
|
||||
websocket
|
||||
.send(Message::Text(reply.to_string().into()))
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn queue_submits_message_to_remote_app_server() -> Result<()> {
|
||||
let (output, request) = run_remote_queue_command(QueueResponse::Success).await?;
|
||||
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert_eq!(request["params"]["threadId"], THREAD_ID);
|
||||
assert_eq!(request["params"]["input"][0]["text"], "do the thing");
|
||||
assert_eq!(
|
||||
String::from_utf8(output.stdout)?,
|
||||
format!("Queued message queued-submission-id for thread {THREAD_ID}.\n")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn queue_succeeds_when_another_server_owns_the_thread() -> Result<()> {
|
||||
let (output, _) = run_remote_queue_command(QueueResponse::ResumeRejected).await?;
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert_eq!(
|
||||
String::from_utf8(output.stdout)?,
|
||||
format!("Queued message queued-submission-id for thread {THREAD_ID}.\n")
|
||||
);
|
||||
assert!(String::from_utf8(output.stderr)?.contains("thread already has an active writer"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn queue_does_not_fallback_from_unsupported_explicit_remote() -> Result<()> {
|
||||
let (output, _) = run_remote_queue_command(QueueResponse::MethodNotFound).await?;
|
||||
|
||||
assert!(!output.status.success());
|
||||
assert!(
|
||||
String::from_utf8(output.stderr)?
|
||||
.contains("remote app server does not support thread/queue/add")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queue_rejects_empty_message() -> Result<()> {
|
||||
let output = std::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
|
||||
.args(["queue", "--thread", THREAD_ID, "--message", ""])
|
||||
.output()?;
|
||||
assert!(!output.status.success());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queue_rejects_unsupported_options() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
for (args, expected) in [
|
||||
("queue --image screenshot.png", "image attachments"),
|
||||
("queue --model other-model", "`--model`"),
|
||||
("--oss queue", "`--oss`"),
|
||||
("queue --local-provider ollama", "`--local-provider`"),
|
||||
(
|
||||
"queue --dangerously-bypass-hook-trust",
|
||||
"`--dangerously-bypass-hook-trust`",
|
||||
),
|
||||
(
|
||||
"-c model=other queue -c analytics.enabled=false",
|
||||
"`model` config override",
|
||||
),
|
||||
("queue -s read-only", "`--sandbox`"),
|
||||
("--approve-for-me queue", "`--approve-for-me`"),
|
||||
("prompt queue", "positional prompt; use `--message`"),
|
||||
("-C . queue --remote unix://", "`--cd` with `--remote`"),
|
||||
("--remote unix:// queue -C .", "`--cd` with `--remote`"),
|
||||
] {
|
||||
let output = std::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
|
||||
.env("CODEX_HOME", codex_home.path())
|
||||
.args(args.split_whitespace())
|
||||
.args(["--thread", THREAD_ID, "--message", "do the thing"])
|
||||
.output()?;
|
||||
assert!(!output.status.success());
|
||||
let stderr = String::from_utf8(output.stderr)?;
|
||||
assert!(
|
||||
stderr.contains("`codex queue`") && stderr.contains(expected),
|
||||
"{args:?}: {stderr}"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_remote_queue_command(response: QueueResponse) -> Result<(Output, Value)> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let endpoint = format!("ws://{}", listener.local_addr()?);
|
||||
let remote_first = matches!(response, QueueResponse::MethodNotFound);
|
||||
let resume = matches!(response, QueueResponse::ResumeRejected);
|
||||
let server_home = codex_home.path().to_path_buf();
|
||||
let server = tokio::spawn(async move {
|
||||
let (stream, _) = listener.accept().await?;
|
||||
respond_to_queue_request(stream, server_home.as_path(), response).await
|
||||
});
|
||||
|
||||
let remote_args = if remote_first {
|
||||
[
|
||||
"--remote",
|
||||
endpoint.as_str(),
|
||||
"--remote-auth-token-env",
|
||||
"CODEX_REMOTE_TOKEN",
|
||||
"queue",
|
||||
]
|
||||
} else {
|
||||
[
|
||||
"queue",
|
||||
"--remote",
|
||||
endpoint.as_str(),
|
||||
"--remote-auth-token-env",
|
||||
"CODEX_REMOTE_TOKEN",
|
||||
]
|
||||
};
|
||||
let output = tokio::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
|
||||
.env("CODEX_HOME", codex_home.path())
|
||||
.env("CODEX_REMOTE_TOKEN", "test-token")
|
||||
.args(remote_args)
|
||||
.args(resume.then_some("--resume"))
|
||||
.args(["--thread", THREAD_ID, "--message", "do the thing"])
|
||||
.output()
|
||||
.await?;
|
||||
Ok((output, server.await??))
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn remote_session_commands_with_workload_identity_use_server_auth() -> Result<()> {
|
||||
use std::time::Duration;
|
||||
|
||||
use app_test_support::MockResponsesConfig;
|
||||
use app_test_support::TestAppServer;
|
||||
use app_test_support::create_final_assistant_message_sse_response;
|
||||
use codex_app_server_client::AppServerEvent;
|
||||
use codex_app_server_client::DEFAULT_IN_PROCESS_CHANNEL_CAPACITY;
|
||||
use codex_app_server_client::RemoteAppServerClient;
|
||||
use codex_app_server_client::RemoteAppServerConnectArgs;
|
||||
use codex_app_server_client::RemoteAppServerEndpoint;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::ThreadListParams;
|
||||
use codex_app_server_protocol::ThreadListResponse;
|
||||
use codex_app_server_protocol::ThreadQueueListParams;
|
||||
use codex_app_server_protocol::ThreadQueueListResponse;
|
||||
use codex_app_server_protocol::ThreadReadParams;
|
||||
use codex_app_server_protocol::ThreadReadResponse;
|
||||
use codex_app_server_protocol::ThreadSetNameParams;
|
||||
use codex_app_server_protocol::ThreadSetNameResponse;
|
||||
use codex_app_server_protocol::ThreadStartParams;
|
||||
use codex_app_server_protocol::ThreadStartResponse;
|
||||
use codex_app_server_protocol::ThreadStatus;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use codex_protocol::shell_environment::OPENAI_FEDERATION_RULE_ID_ENV_VAR;
|
||||
use codex_protocol::shell_environment::OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR;
|
||||
use core_test_support::responses;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
use wiremock::Mock;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
let codex_home = socket_test_home()?;
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
let model = responses::start_mock_server().await;
|
||||
let model_requests = Mock::given(method("POST"))
|
||||
.and(path("/v1/responses"))
|
||||
.respond_with(responses::sse_response(
|
||||
create_final_assistant_message_sse_response("queued message consumed")?,
|
||||
))
|
||||
.expect(2)
|
||||
.mount_as_scoped(&model)
|
||||
.await;
|
||||
MockResponsesConfig::new(&model.uri())
|
||||
.with_root_config("features.plugins = false\nanalytics.enabled = false")
|
||||
.with_provider_config("env_key = \"CODEX_QUEUE_SERVER_API_KEY\"")
|
||||
.write(codex_home.path())?;
|
||||
let _server = TestAppServer::builder()
|
||||
.with_program(&codex)
|
||||
.with_codex_home(codex_home.path())
|
||||
.with_plugin_startup_tasks()
|
||||
.without_managed_config()
|
||||
.with_args(&["app-server", "--listen", "unix://"])
|
||||
.with_env_overrides(&[
|
||||
("OPENAI_API_KEY", None),
|
||||
("CODEX_API_KEY", None),
|
||||
("CODEX_ACCESS_TOKEN", None),
|
||||
(OPENAI_FEDERATION_RULE_ID_ENV_VAR, None),
|
||||
(OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR, None),
|
||||
("CODEX_QUEUE_SERVER_API_KEY", Some("server-only-test-key")),
|
||||
])
|
||||
.build()
|
||||
.await?;
|
||||
let socket_path = codex_app_server::app_server_control_socket_path(codex_home.path())?;
|
||||
timeout(Duration::from_secs(30), async {
|
||||
while !socket_path.as_path().try_exists()? {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
Ok::<_, anyhow::Error>(())
|
||||
})
|
||||
.await??;
|
||||
|
||||
let endpoint = format!("unix://{}", socket_path.as_path().display());
|
||||
let mut app = RemoteAppServerClient::connect(RemoteAppServerConnectArgs {
|
||||
required_human_approval: false,
|
||||
endpoint: RemoteAppServerEndpoint::UnixSocket { socket_path },
|
||||
client_name: "queue-e2e-test".to_string(),
|
||||
client_version: "0.1.0".to_string(),
|
||||
experimental_api: true,
|
||||
mcp_server_openai_form_elicitation: false,
|
||||
opt_out_notification_methods: Vec::new(),
|
||||
channel_capacity: DEFAULT_IN_PROCESS_CHANNEL_CAPACITY,
|
||||
})
|
||||
.await?;
|
||||
let started: ThreadStartResponse = app
|
||||
.request_typed(ClientRequest::ThreadStart {
|
||||
request_id: RequestId::Integer(1),
|
||||
params: ThreadStartParams::default(),
|
||||
})
|
||||
.await?;
|
||||
let thread_id = started.thread.id;
|
||||
let message = "synthetic WIF queue end-to-end message";
|
||||
let output = timeout(
|
||||
Duration::from_secs(30),
|
||||
Command::new(&codex)
|
||||
.env("CODEX_HOME", codex_home.path())
|
||||
.env(OPENAI_FEDERATION_RULE_ID_ENV_VAR, "rule-test")
|
||||
.env(
|
||||
OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR,
|
||||
codex_home.path().join("missing-identity-token"),
|
||||
)
|
||||
.env_remove("CODEX_QUEUE_SERVER_API_KEY")
|
||||
.kill_on_drop(true)
|
||||
.args(["queue", "--resume", "--remote", "unix://"])
|
||||
.args(["--thread", &thread_id, "--message", message])
|
||||
.output(),
|
||||
)
|
||||
.await??;
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let completed = timeout(Duration::from_secs(30), async {
|
||||
while let Some(event) = app.next_event().await {
|
||||
if let AppServerEvent::ServerNotification(notification) = event
|
||||
&& let ServerNotification::TurnCompleted(completed) = *notification
|
||||
{
|
||||
return Ok::<_, anyhow::Error>(completed);
|
||||
}
|
||||
}
|
||||
anyhow::bail!("app server disconnected before the queued turn completed")
|
||||
})
|
||||
.await??;
|
||||
assert_eq!(completed.thread_id, thread_id);
|
||||
assert_eq!(completed.turn.status, TurnStatus::Completed);
|
||||
let queue: ThreadQueueListResponse = app
|
||||
.request_typed(ClientRequest::ThreadQueueList {
|
||||
request_id: RequestId::Integer(2),
|
||||
params: ThreadQueueListParams {
|
||||
thread_id: thread_id.clone(),
|
||||
cursor: None,
|
||||
limit: None,
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
assert!(queue.data.is_empty());
|
||||
|
||||
let requests = model_requests.received_requests().await;
|
||||
let request = requests
|
||||
.first()
|
||||
.context("queued message did not reach the model")?;
|
||||
assert!(
|
||||
request.body_json::<Value>()?["input"]
|
||||
.to_string()
|
||||
.contains(message)
|
||||
);
|
||||
assert_eq!(
|
||||
request.headers["authorization"].to_str()?,
|
||||
"Bearer server-only-test-key"
|
||||
);
|
||||
let metadata: Value = serde_json::from_str(request.headers["x-codex-turn-metadata"].to_str()?)?;
|
||||
assert_eq!(metadata["turn_trigger"], "queue");
|
||||
|
||||
let name = "remote-session-lifecycle";
|
||||
let _: ThreadSetNameResponse = app
|
||||
.request_typed(ClientRequest::ThreadSetName {
|
||||
request_id: RequestId::Integer(3),
|
||||
params: ThreadSetNameParams {
|
||||
thread_id: thread_id.clone(),
|
||||
name: name.to_string(),
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
// A separate caller home makes name resolution rely on the selected server.
|
||||
let caller_home = TempDir::new()?;
|
||||
let remote_command = || {
|
||||
let mut command = Command::new(&codex);
|
||||
command
|
||||
.env("CODEX_HOME", caller_home.path())
|
||||
.current_dir(caller_home.path())
|
||||
.env(OPENAI_FEDERATION_RULE_ID_ENV_VAR, "rule-test")
|
||||
.env(
|
||||
OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR,
|
||||
caller_home.path().join("missing-identity-token"),
|
||||
)
|
||||
.env_remove("CODEX_QUEUE_SERVER_API_KEY")
|
||||
.kill_on_drop(true)
|
||||
.args(["--remote", &endpoint]);
|
||||
command
|
||||
};
|
||||
let output = timeout(
|
||||
Duration::from_secs(30),
|
||||
remote_command().args(["delete", &thread_id]).output(),
|
||||
)
|
||||
.await??;
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8(output.stderr)?.contains("cannot confirm session deletion"));
|
||||
|
||||
let cold_message = "Continue after the thread was unloaded";
|
||||
let cases: &[(&[&str], Option<bool>)] = &[
|
||||
(&["archive", name], Some(true)),
|
||||
(&["unarchive", name], Some(false)),
|
||||
(&["delete", "--force", &thread_id], None),
|
||||
];
|
||||
for &(args, expected_archived) in cases {
|
||||
let output = timeout(
|
||||
Duration::from_secs(30),
|
||||
remote_command().args(args).output(),
|
||||
)
|
||||
.await??;
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{args:?}: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
for archived in [false, true] {
|
||||
let threads: ThreadListResponse = app
|
||||
.request_typed(ClientRequest::ThreadList {
|
||||
request_id: RequestId::Integer(4),
|
||||
params: ThreadListParams {
|
||||
current_account_only: false,
|
||||
excluded_thread_ids: None,
|
||||
attached_to_thread_id: None,
|
||||
cursor: None,
|
||||
limit: None,
|
||||
sort_key: None,
|
||||
sort_direction: None,
|
||||
model_providers: None,
|
||||
source_kinds: None,
|
||||
originators: None,
|
||||
archived: Some(archived),
|
||||
section_id: None,
|
||||
project_id: None,
|
||||
cwd: None,
|
||||
use_state_db_only: false,
|
||||
search_term: None,
|
||||
parent_thread_id: None,
|
||||
ancestor_thread_id: None,
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
let thread = threads.data.iter().find(|thread| thread.id == thread_id);
|
||||
assert_eq!(
|
||||
thread.is_some(),
|
||||
expected_archived == Some(archived),
|
||||
"{args:?}: archived={archived}"
|
||||
);
|
||||
if expected_archived == Some(false)
|
||||
&& let Some(thread) = thread
|
||||
{
|
||||
assert_eq!(thread.status, ThreadStatus::NotLoaded);
|
||||
}
|
||||
}
|
||||
let Some(archived) = expected_archived else {
|
||||
continue;
|
||||
};
|
||||
// Archived threads are reachable by ID; active threads can also be targeted by name.
|
||||
let (target, text) = if archived {
|
||||
(thread_id.as_str(), "still archived")
|
||||
} else {
|
||||
(name, cold_message)
|
||||
};
|
||||
let output = remote_command()
|
||||
.args(["queue", "--resume", "--thread", target, "--message", text])
|
||||
.output()
|
||||
.await?;
|
||||
if archived {
|
||||
assert!(!output.status.success());
|
||||
assert!(
|
||||
String::from_utf8(output.stderr)?
|
||||
.contains(&format!("session {thread_id} is archived"))
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
timeout(
|
||||
Duration::from_secs(30),
|
||||
model_requests.wait_until_satisfied(),
|
||||
)
|
||||
.await?;
|
||||
let requests = model_requests.received_requests().await;
|
||||
assert!(
|
||||
requests[1].body_json::<Value>()?["input"]
|
||||
.to_string()
|
||||
.contains(cold_message)
|
||||
);
|
||||
// The mock receives the request before the resumed turn finishes. Deletion
|
||||
// requires an idle thread, and archiving removed our original subscription.
|
||||
timeout(Duration::from_secs(30), async {
|
||||
loop {
|
||||
let read: ThreadReadResponse = app
|
||||
.request_typed(ClientRequest::ThreadRead {
|
||||
request_id: RequestId::Integer(5),
|
||||
params: ThreadReadParams {
|
||||
thread_id: thread_id.clone(),
|
||||
include_turns: true,
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
if let Some(last) = read.thread.turns.last()
|
||||
&& last.id != completed.turn.id
|
||||
&& last.status == TurnStatus::Completed
|
||||
&& matches!(
|
||||
read.thread.status,
|
||||
ThreadStatus::Idle | ThreadStatus::NotLoaded
|
||||
)
|
||||
{
|
||||
return anyhow::Ok(());
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.context("resumed queued turn did not finish before deletion")??;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_session_commands_validate_config() -> Result<()> {
|
||||
let cases: &[(&[&str], &str, &str)] = &[
|
||||
(
|
||||
&["--strict-config"],
|
||||
"config.toml",
|
||||
"unknown_queue_option = true\n",
|
||||
),
|
||||
(&["--profile", "queue"], "queue.config.toml", "model = 42\n"),
|
||||
(
|
||||
&[],
|
||||
"config.toml",
|
||||
"experimental_thread_store_endpoint = \"https://example.com\"\n",
|
||||
),
|
||||
];
|
||||
let commands: &[&[&str]] = &[
|
||||
&["queue", "--thread", THREAD_ID, "--message", "do the thing"],
|
||||
&["archive", THREAD_ID],
|
||||
&["unarchive", THREAD_ID],
|
||||
&["delete", "--force", THREAD_ID],
|
||||
];
|
||||
for &command in commands {
|
||||
for &(args, config_file, config) in cases {
|
||||
let codex_home = TempDir::new()?;
|
||||
std::fs::write(codex_home.path().join(config_file), config)?;
|
||||
let output = std::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
|
||||
.env("CODEX_HOME", codex_home.path())
|
||||
.current_dir(codex_home.path())
|
||||
.args(args)
|
||||
.args(["--remote", "ws://127.0.0.1:1"])
|
||||
.args(command)
|
||||
.output()?;
|
||||
let stderr = String::from_utf8(output.stderr)?;
|
||||
assert!(!output.status.success());
|
||||
assert!(
|
||||
stderr.contains("failed to load config.toml"),
|
||||
"{command:?}, {config:?}: {stderr}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn queue_rejects_local_daemon_that_does_not_support_queueing() -> Result<()> {
|
||||
let codex_home = socket_test_home()?;
|
||||
let socket_path = codex_app_server::app_server_control_socket_path(codex_home.path())?;
|
||||
std::fs::create_dir_all(
|
||||
socket_path
|
||||
.as_path()
|
||||
.parent()
|
||||
.context("missing socket parent")?,
|
||||
)?;
|
||||
let listener = tokio::net::UnixListener::bind(socket_path.as_path())?;
|
||||
let server_home = codex_home.path().to_path_buf();
|
||||
let server = tokio::spawn(async move {
|
||||
let (probe, _) = listener.accept().await?;
|
||||
drop(probe);
|
||||
let (stream, _) = listener.accept().await?;
|
||||
respond_to_queue_request(
|
||||
stream,
|
||||
server_home.as_path(),
|
||||
QueueResponse::UnknownMethodVariant,
|
||||
)
|
||||
.await
|
||||
});
|
||||
|
||||
let output = tokio::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
|
||||
.env("CODEX_HOME", codex_home.path())
|
||||
.args(["queue", "--thread", THREAD_ID, "--message", "do the thing"])
|
||||
.output()
|
||||
.await?;
|
||||
server.await??;
|
||||
|
||||
assert!(!output.status.success());
|
||||
assert!(
|
||||
String::from_utf8(output.stderr)?
|
||||
.contains("local app-server daemon does not support thread/queue/add")
|
||||
);
|
||||
assert!(!codex_home.path().join("queue_1.sqlite").exists());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn queue_rejects_overrides_that_bypass_local_daemon() -> Result<()> {
|
||||
let codex_home = socket_test_home()?;
|
||||
let socket_path = codex_app_server::app_server_control_socket_path(codex_home.path())?;
|
||||
std::fs::create_dir_all(
|
||||
socket_path
|
||||
.as_path()
|
||||
.parent()
|
||||
.context("missing socket parent")?,
|
||||
)?;
|
||||
let listener = tokio::net::UnixListener::bind(socket_path.as_path())?;
|
||||
let server = tokio::spawn(async move {
|
||||
let (probe, _) = listener.accept().await?;
|
||||
drop(probe);
|
||||
Ok::<_, std::io::Error>(())
|
||||
});
|
||||
|
||||
let output = tokio::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
|
||||
.env("CODEX_HOME", codex_home.path())
|
||||
.args([
|
||||
"queue",
|
||||
"-C",
|
||||
".",
|
||||
"-c",
|
||||
"analytics.enabled=false",
|
||||
"--thread",
|
||||
THREAD_ID,
|
||||
"--message",
|
||||
"do the thing",
|
||||
])
|
||||
.output()
|
||||
.await?;
|
||||
assert!(!output.status.success());
|
||||
assert!(
|
||||
String::from_utf8(output.stderr)?
|
||||
.contains("embedded app server while a local app-server daemon is running")
|
||||
);
|
||||
server.await??;
|
||||
Ok(())
|
||||
}
|
||||
304
codex-rs/cli/tests/rollout_trace.rs
Normal file
304
codex-rs/cli/tests/rollout_trace.rs
Normal file
@@ -0,0 +1,304 @@
|
||||
//! Exercise trace acceptance through the CLI app-server and its offline reducer.
|
||||
|
||||
use anyhow::Result;
|
||||
use app_test_support::MockResponsesConfig;
|
||||
use app_test_support::TestAppServer;
|
||||
use app_test_support::create_mock_responses_server_sequence;
|
||||
use codex_app_server_protocol::AgentMessageDeltaNotification;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::ThreadStartParams;
|
||||
use codex_app_server_protocol::ThreadStartResponse;
|
||||
use codex_app_server_protocol::TurnCompletedNotification;
|
||||
use codex_app_server_protocol::TurnInterruptParams;
|
||||
use codex_app_server_protocol::TurnInterruptResponse;
|
||||
use codex_app_server_protocol::TurnStartParams;
|
||||
use codex_app_server_protocol::TurnStartResponse;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use codex_app_server_protocol::UserInput;
|
||||
use codex_rollout_trace::ConversationRole;
|
||||
use codex_rollout_trace::ExecutionStatus;
|
||||
use codex_rollout_trace::ProducerRef;
|
||||
use codex_rollout_trace::RolloutTrace;
|
||||
use core_test_support::responses;
|
||||
use core_test_support::streaming_sse::StreamingSseChunk;
|
||||
use core_test_support::streaming_sse::start_streaming_sse_server;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
#[tokio::test]
|
||||
async fn enabled_recording_cannot_silently_fail_to_start() -> Result<()> {
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
let home = TempDir::new()?;
|
||||
let server = create_mock_responses_server_sequence(Vec::new()).await;
|
||||
MockResponsesConfig::new(&server.uri()).write(home.path())?;
|
||||
let trace_root = home.path().join("traces");
|
||||
std::fs::write(&trace_root, "file")?;
|
||||
let mut app = TestAppServer::builder()
|
||||
.with_program(&codex)
|
||||
.with_plugin_startup_tasks()
|
||||
.with_args(&["app-server"])
|
||||
.with_codex_home(home.path())
|
||||
.with_env_overrides(&[("CODEX_ROLLOUT_TRACE_ROOT", trace_root.to_str())])
|
||||
.build_initialized()
|
||||
.await?;
|
||||
let request_id = app
|
||||
.send_thread_start_request_with_auto_env(ThreadStartParams::default())
|
||||
.await?;
|
||||
let error = app
|
||||
.read_stream_until_error_message(RequestId::Integer(request_id))
|
||||
.await?;
|
||||
assert!(
|
||||
error
|
||||
.error
|
||||
.message
|
||||
.contains("failed to start rollout recording")
|
||||
);
|
||||
// The same app-server can start a new recording once storage is available.
|
||||
std::fs::remove_file(&trace_root)?;
|
||||
std::fs::create_dir(&trace_root)?;
|
||||
app.start_thread(ThreadStartParams::default()).await?;
|
||||
assert!(app.shutdown_gracefully().await?.success());
|
||||
let mut bundles = std::fs::read_dir(trace_root)?;
|
||||
let bundle = bundles.next().unwrap()?.path();
|
||||
assert!(bundles.next().is_none());
|
||||
assert!(codex_rollout_trace::replay_bundle(bundle)?.recording_complete);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn accepted_output_survives_success_and_stream_failure() -> Result<()> {
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
for (source_id, terminal, status) in [
|
||||
(
|
||||
Some("msg-original"),
|
||||
"response.completed",
|
||||
ExecutionStatus::Completed,
|
||||
),
|
||||
(None, "response.completed", ExecutionStatus::Completed),
|
||||
(
|
||||
Some("msg-original"),
|
||||
"response.failed",
|
||||
ExecutionStatus::Failed,
|
||||
),
|
||||
(None, "response.failed", ExecutionStatus::Failed),
|
||||
] {
|
||||
let home = TempDir::new()?;
|
||||
let traces = TempDir::new()?;
|
||||
let item = json!({
|
||||
"type": "message", "id": source_id, "role": "assistant",
|
||||
"content": [{"type": "output_text", "text": "accepted answer"}]
|
||||
});
|
||||
let mut terminal_response = json!({"id": "resp-1"});
|
||||
if status == ExecutionStatus::Failed {
|
||||
terminal_response["error"] =
|
||||
json!({"code": "server_error", "message": "stream failed"});
|
||||
}
|
||||
let response = [
|
||||
json!({"type": "response.created", "response": {"id": "resp-1"}}),
|
||||
json!({"type": "response.output_item.added", "item": item}),
|
||||
json!({"type": "response.output_item.done", "item": item}),
|
||||
json!({"type": terminal, "response": terminal_response}),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|event| format!("data: {event}\n\n"))
|
||||
.collect();
|
||||
let server = create_mock_responses_server_sequence(vec![response]).await;
|
||||
MockResponsesConfig::new(&server.uri()).write(home.path())?;
|
||||
let mut app = TestAppServer::builder()
|
||||
.with_program(&codex)
|
||||
.with_plugin_startup_tasks()
|
||||
.with_args(&["app-server"])
|
||||
.with_codex_home(home.path())
|
||||
.with_env_overrides(&[("CODEX_ROLLOUT_TRACE_ROOT", traces.path().to_str())])
|
||||
.build_initialized()
|
||||
.await?;
|
||||
let ThreadStartResponse { thread, .. } =
|
||||
app.start_thread(ThreadStartParams::default()).await?;
|
||||
let TurnStartResponse { turn } = app
|
||||
.request(|request_id| ClientRequest::TurnStart {
|
||||
request_id,
|
||||
params: TurnStartParams {
|
||||
thread_id: thread.id.clone(),
|
||||
input: vec![UserInput::Text {
|
||||
text: "answer once".into(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
let completed: TurnCompletedNotification = app.read_notification("turn/completed").await?;
|
||||
assert_eq!(
|
||||
completed.turn.status,
|
||||
if status == ExecutionStatus::Completed {
|
||||
TurnStatus::Completed
|
||||
} else {
|
||||
TurnStatus::Failed
|
||||
}
|
||||
);
|
||||
assert!(app.shutdown_gracefully().await?.success());
|
||||
|
||||
// Exercise the exported artifact, not just an in-process reducer call.
|
||||
// There is no following request to prove acceptance of this final item.
|
||||
let bundle = std::fs::read_dir(traces.path())?.next().unwrap()?.path();
|
||||
let reduced = tokio::process::Command::new(&codex)
|
||||
.env("CODEX_HOME", home.path())
|
||||
.args(["debug", "trace-reduce"])
|
||||
.arg(&bundle)
|
||||
.output()
|
||||
.await?;
|
||||
assert!(
|
||||
reduced.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&reduced.stderr)
|
||||
);
|
||||
let rollout: RolloutTrace =
|
||||
serde_json::from_reader(std::fs::File::open(bundle.join("state.json"))?)?;
|
||||
assert!(rollout.recording_complete);
|
||||
let call = rollout.inference_calls.values().next().unwrap();
|
||||
let output_id = &call.response_item_ids[0];
|
||||
let output = &rollout.conversation_items[output_id];
|
||||
let mut expected = call.request_item_ids.clone();
|
||||
expected.push(output_id.clone());
|
||||
assert_eq!(rollout.threads[&thread.id].conversation_item_ids, expected);
|
||||
assert_eq!(rollout.codex_turns[&turn.id].execution.status, status);
|
||||
assert_eq!(call.execution.status, status);
|
||||
assert_eq!(
|
||||
output.produced_by,
|
||||
vec![ProducerRef::Inference {
|
||||
inference_call_id: call.inference_call_id.clone()
|
||||
}]
|
||||
);
|
||||
assert!(
|
||||
output
|
||||
.responses_item_id
|
||||
.as_ref()
|
||||
.is_some_and(|id| !id.is_empty())
|
||||
);
|
||||
if let Some(source_id) = source_id {
|
||||
assert_eq!(output.responses_item_id.as_deref(), Some(source_id));
|
||||
}
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let request = requests
|
||||
.iter()
|
||||
.find(|request| request.url.path().ends_with("/responses"))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
request.headers["x-codex-inference-call-id"].to_str()?,
|
||||
call.inference_call_id
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn accepted_output_survives_interruption_and_shutdown() -> Result<()> {
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
let home = TempDir::new()?;
|
||||
let traces = TempDir::new()?;
|
||||
let (release_response, response_gate) = oneshot::channel();
|
||||
let (server, _) = start_streaming_sse_server(vec![vec![
|
||||
StreamingSseChunk {
|
||||
gate: None,
|
||||
body: responses::sse(vec![
|
||||
responses::ev_response_created("resp-1"),
|
||||
responses::ev_assistant_message("accepted", "Keep this answer."),
|
||||
responses::ev_message_item_added("unfinished", ""),
|
||||
responses::ev_output_text_delta("Discard this unfinished text"),
|
||||
]),
|
||||
},
|
||||
// Keep the provider stream open so only the client interrupt ends it.
|
||||
StreamingSseChunk {
|
||||
gate: Some(response_gate),
|
||||
body: String::new(),
|
||||
},
|
||||
]])
|
||||
.await;
|
||||
MockResponsesConfig::new(server.uri()).write(home.path())?;
|
||||
let mut app = TestAppServer::builder()
|
||||
.with_program(&codex)
|
||||
.with_plugin_startup_tasks()
|
||||
.with_args(&["app-server"])
|
||||
.with_codex_home(home.path())
|
||||
.with_env_overrides(&[("CODEX_ROLLOUT_TRACE_ROOT", traces.path().to_str())])
|
||||
.build_initialized()
|
||||
.await?;
|
||||
let ThreadStartResponse { thread, .. } = app.start_thread(ThreadStartParams::default()).await?;
|
||||
let TurnStartResponse { turn } = app
|
||||
.request(|request_id| ClientRequest::TurnStart {
|
||||
request_id,
|
||||
params: TurnStartParams {
|
||||
thread_id: thread.id.clone(),
|
||||
input: vec![UserInput::Text {
|
||||
text: "answer once".into(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
|
||||
// Reaching the second item proves the session processed the first one.
|
||||
let delta: AgentMessageDeltaNotification =
|
||||
app.read_notification("item/agentMessage/delta").await?;
|
||||
assert_eq!(delta.item_id, "unfinished");
|
||||
let _: TurnInterruptResponse = app
|
||||
.request(|request_id| ClientRequest::TurnInterrupt {
|
||||
request_id,
|
||||
params: TurnInterruptParams {
|
||||
thread_id: thread.id.clone(),
|
||||
turn_id: turn.id.clone(),
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
let completed: TurnCompletedNotification = app.read_notification("turn/completed").await?;
|
||||
assert_eq!(completed.turn.status, TurnStatus::Interrupted);
|
||||
assert!(app.shutdown_gracefully().await?.success());
|
||||
drop(release_response);
|
||||
server.shutdown().await;
|
||||
|
||||
// Reduce immediately after shutdown: the background stream recorder must
|
||||
// have preserved the accepted output even without response.completed.
|
||||
let bundle = std::fs::read_dir(traces.path())?.next().unwrap()?.path();
|
||||
let reduced = tokio::process::Command::new(&codex)
|
||||
.env("CODEX_HOME", home.path())
|
||||
.args(["debug", "trace-reduce"])
|
||||
.arg(&bundle)
|
||||
.output()
|
||||
.await?;
|
||||
assert!(
|
||||
reduced.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&reduced.stderr)
|
||||
);
|
||||
let rollout: RolloutTrace =
|
||||
serde_json::from_reader(std::fs::File::open(bundle.join("state.json"))?)?;
|
||||
assert!(rollout.recording_complete);
|
||||
assert_eq!(rollout.inference_calls.len(), 1);
|
||||
let call = rollout.inference_calls.values().next().unwrap();
|
||||
assert_eq!(call.execution.status, ExecutionStatus::Cancelled);
|
||||
assert_eq!(
|
||||
rollout.codex_turns[&turn.id].execution.status,
|
||||
ExecutionStatus::Cancelled
|
||||
);
|
||||
assert_eq!(call.response_item_ids.len(), 1);
|
||||
let output_id = &call.response_item_ids[0];
|
||||
let output = &rollout.conversation_items[output_id];
|
||||
assert_eq!(output.responses_item_id.as_deref(), Some("accepted"));
|
||||
assert_eq!(
|
||||
output.produced_by,
|
||||
vec![ProducerRef::Inference {
|
||||
inference_call_id: call.inference_call_id.clone(),
|
||||
}]
|
||||
);
|
||||
let accepted_messages: Vec<_> = rollout.threads[&thread.id]
|
||||
.conversation_item_ids
|
||||
.iter()
|
||||
.filter(|id| rollout.conversation_items[*id].role == ConversationRole::Assistant)
|
||||
.collect();
|
||||
assert_eq!(accepted_messages, vec![output_id]);
|
||||
Ok(())
|
||||
}
|
||||
184
codex-rs/cli/tests/sandbox_cloud_config.rs
Normal file
184
codex-rs/cli/tests/sandbox_cloud_config.rs
Normal file
@@ -0,0 +1,184 @@
|
||||
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))
|
||||
}
|
||||
145
codex-rs/cli/tests/sandbox_network_proxy.rs
Normal file
145
codex-rs/cli/tests/sandbox_network_proxy.rs
Normal file
@@ -0,0 +1,145 @@
|
||||
#![cfg(target_os = "linux")]
|
||||
|
||||
use std::net::TcpListener;
|
||||
|
||||
use anyhow::Result;
|
||||
use tempfile::TempDir;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
const BWRAP_UNAVAILABLE_ERR: &str = "bubblewrap is unavailable";
|
||||
|
||||
#[test]
|
||||
fn sandbox_with_network_proxy_blocks_direct_loopback_access() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let listener = TcpListener::bind("127.0.0.2:0")?;
|
||||
let port = listener.local_addr()?.port();
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
r#"
|
||||
default_permissions = "network-test"
|
||||
|
||||
[features]
|
||||
network_proxy = true
|
||||
use_legacy_landlock = true
|
||||
|
||||
[permissions.network-test]
|
||||
extends = ":workspace"
|
||||
|
||||
[permissions.network-test.network]
|
||||
enabled = true
|
||||
mode = "full"
|
||||
"#,
|
||||
)?;
|
||||
|
||||
let url = format!("http://127.0.0.2:{port}/");
|
||||
let output = std::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
|
||||
.env("CODEX_HOME", codex_home.path())
|
||||
.args([
|
||||
"sandbox",
|
||||
"--permission-profile",
|
||||
"network-test",
|
||||
"--",
|
||||
"curl",
|
||||
"--noproxy",
|
||||
"*",
|
||||
"--silent",
|
||||
"--show-error",
|
||||
"--connect-timeout",
|
||||
"1",
|
||||
"--max-time",
|
||||
"2",
|
||||
url.as_str(),
|
||||
])
|
||||
.output()?;
|
||||
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if stderr.contains(BWRAP_UNAVAILABLE_ERR) {
|
||||
eprintln!("skipping network proxy sandbox test: bubblewrap is unavailable");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
output.status.code(),
|
||||
Some(7),
|
||||
"expected direct loopback access to be blocked; status={:?}; stdout={}; stderr={}",
|
||||
output.status.code(),
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
stderr,
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sandbox_with_network_proxy_allows_explicit_loopback_access() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let listener = TcpListener::bind("127.0.0.2:0")?;
|
||||
let port = listener.local_addr()?.port();
|
||||
let server = MockServer::builder().listener(listener).start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/"))
|
||||
.respond_with(ResponseTemplate::new(204))
|
||||
.mount(&server)
|
||||
.await;
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
r#"
|
||||
default_permissions = "network-test"
|
||||
|
||||
[features]
|
||||
network_proxy = true
|
||||
use_legacy_landlock = true
|
||||
|
||||
[permissions.network-test]
|
||||
extends = ":workspace"
|
||||
|
||||
[permissions.network-test.network]
|
||||
enabled = true
|
||||
mode = "full"
|
||||
allow_local_binding = false
|
||||
|
||||
[permissions.network-test.network.domains]
|
||||
"127.0.0.2" = "allow"
|
||||
"#,
|
||||
)?;
|
||||
|
||||
let url = format!("http://127.0.0.2:{port}/");
|
||||
let output = tokio::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
|
||||
.env("CODEX_HOME", codex_home.path())
|
||||
.args([
|
||||
"sandbox",
|
||||
"--permission-profile",
|
||||
"network-test",
|
||||
"--",
|
||||
"curl",
|
||||
"--fail",
|
||||
"--silent",
|
||||
"--show-error",
|
||||
"--connect-timeout",
|
||||
"2",
|
||||
"--max-time",
|
||||
"4",
|
||||
url.as_str(),
|
||||
])
|
||||
.output()
|
||||
.await?;
|
||||
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if stderr.contains(BWRAP_UNAVAILABLE_ERR) {
|
||||
eprintln!("skipping network proxy sandbox test: bubblewrap is unavailable");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"expected allowlisted loopback access to succeed; status={:?}; stdout={}; stderr={}",
|
||||
output.status.code(),
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
stderr,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
132
codex-rs/cli/tests/sandbox_tty.rs
Normal file
132
codex-rs/cli/tests/sandbox_tty.rs
Normal file
@@ -0,0 +1,132 @@
|
||||
//! Exercises the public macOS sandbox runner with a disposable controlling terminal.
|
||||
|
||||
#![cfg(target_os = "macos")]
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context as _;
|
||||
use codex_utils_pty::SpawnedProcess;
|
||||
use codex_utils_pty::TerminalSize;
|
||||
use codex_utils_pty::spawn_pty_process;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
const PROBE: &str = r#"
|
||||
import errno, fcntl, os, select, signal, struct, sys, termios, tty
|
||||
|
||||
signal.alarm(15)
|
||||
assert os.isatty(0)
|
||||
assert os.tcgetpgrp(0) == os.getpgrp()
|
||||
assert struct.unpack("HHHH", fcntl.ioctl(0, termios.TIOCGWINSZ, b"\0" * 8))[:2] == (24, 80)
|
||||
original = termios.tcgetattr(0)
|
||||
try:
|
||||
tty.setraw(0)
|
||||
print("__ready__", flush=True)
|
||||
assert os.read(0, 1) == b"k"
|
||||
try:
|
||||
fcntl.ioctl(0, termios.TIOCSTI, b"x")
|
||||
except OSError as error:
|
||||
assert sys.argv[1] == "deny", error
|
||||
assert error.errno == errno.EPERM, error
|
||||
assert not select.select([0], [], [], 0)[0]
|
||||
else:
|
||||
assert os.read(0, 1) == b"x"
|
||||
assert sys.argv[1] == "allow", "TIOCSTI unexpectedly succeeded"
|
||||
finally:
|
||||
termios.tcsetattr(0, termios.TCSANOW, original)
|
||||
print("__passed__", flush=True)
|
||||
"#;
|
||||
|
||||
#[tokio::test]
|
||||
async fn sandbox_blocks_terminal_input_injection() -> anyhow::Result<()> {
|
||||
let availability = Command::new("/usr/bin/sandbox-exec")
|
||||
.args(["-p", "(version 1)(allow default)", "/usr/bin/true"])
|
||||
.output()?;
|
||||
if !availability.status.success()
|
||||
&& String::from_utf8_lossy(&availability.stderr)
|
||||
.contains("sandbox-exec: sandbox_apply: Operation not permitted")
|
||||
{
|
||||
eprintln!("skipping terminal injection test: nested Seatbelt is unavailable");
|
||||
return Ok(());
|
||||
}
|
||||
assert!(availability.status.success(), "{availability:?}");
|
||||
|
||||
let codex_home = TempDir::new()?;
|
||||
let mut env: HashMap<String, String> = std::env::vars().collect();
|
||||
env.insert(
|
||||
"CODEX_HOME".to_string(),
|
||||
codex_home.path().to_string_lossy().into_owned(),
|
||||
);
|
||||
|
||||
// The control proves this is a readable, foreground controlling terminal on
|
||||
// which TIOCSTI would otherwise work. All injected input stays in this PTY.
|
||||
run_probe(
|
||||
"/usr/bin/python3",
|
||||
vec!["-c".to_string(), PROBE.to_string(), "allow".to_string()],
|
||||
codex_home.path(),
|
||||
&env,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
run_probe(
|
||||
&codex.to_string_lossy(),
|
||||
vec![
|
||||
"sandbox".to_string(),
|
||||
"-P".to_string(),
|
||||
":read-only".to_string(),
|
||||
"--".to_string(),
|
||||
"/usr/bin/python3".to_string(),
|
||||
"-c".to_string(),
|
||||
PROBE.to_string(),
|
||||
"deny".to_string(),
|
||||
],
|
||||
codex_home.path(),
|
||||
&env,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn run_probe(
|
||||
program: &str,
|
||||
args: Vec<String>,
|
||||
cwd: &Path,
|
||||
env: &HashMap<String, String>,
|
||||
) -> anyhow::Result<()> {
|
||||
let SpawnedProcess {
|
||||
session,
|
||||
mut stdout_rx,
|
||||
exit_rx,
|
||||
..
|
||||
} = spawn_pty_process(
|
||||
program,
|
||||
&args,
|
||||
cwd,
|
||||
env,
|
||||
/*arg0*/ &None,
|
||||
TerminalSize::default(),
|
||||
codex_utils_pty::ChildFds::Inherited(&[]),
|
||||
)
|
||||
.await?;
|
||||
let mut output = Vec::new();
|
||||
let mut sent_input = false;
|
||||
let code = tokio::time::timeout(Duration::from_secs(30), async {
|
||||
while let Some(bytes) = stdout_rx.recv().await {
|
||||
output.extend_from_slice(&bytes);
|
||||
if !sent_input && String::from_utf8_lossy(&output).contains("__ready__") {
|
||||
session.writer_sender().send(b"k".to_vec()).await?;
|
||||
sent_input = true;
|
||||
}
|
||||
}
|
||||
Ok::<_, anyhow::Error>(exit_rx.await?)
|
||||
})
|
||||
.await
|
||||
.context("terminal probe timed out")??;
|
||||
let output = String::from_utf8_lossy(&output);
|
||||
assert_eq!(code, 0, "terminal probe failed: {output}");
|
||||
assert!(output.contains("__passed__"), "{output}");
|
||||
Ok(())
|
||||
}
|
||||
39
codex-rs/cli/tests/sandbox_uninstall.rs
Normal file
39
codex-rs/cli/tests/sandbox_uninstall.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
//! Exercises uninstall argument handling without performing machine-wide cleanup.
|
||||
|
||||
use anyhow::Result;
|
||||
use predicates::str::contains;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn uninstall_help_and_invalid_arguments_preserve_user_data() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
// Uninstall must work independently of configuration parsing and authentication.
|
||||
std::fs::write(home.path().join("config.toml"), "invalid config [")?;
|
||||
std::fs::write(home.path().join("auth.json"), "preserve credentials")?;
|
||||
|
||||
let mut command = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
command
|
||||
.env("CODEX_HOME", home.path())
|
||||
.args(["sandbox", "uninstall", "--help"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let mut command = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
command
|
||||
.env("CODEX_HOME", home.path())
|
||||
.args(["sandbox", "uninstall", "unexpected"])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("unexpected argument"));
|
||||
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(home.path().join("config.toml"))?,
|
||||
"invalid config ["
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(home.path().join("auth.json"))?,
|
||||
"preserve credentials"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
source: cli/tests/daemon_startup.rs
|
||||
expression: transition
|
||||
---
|
||||
Agent command center Group: Project g
|
||||
All 0 Needs you 0 Working 0 Ready 0 Inactive 0 tab/shift+tab filter
|
||||
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
No tasks yet │
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
│
|
||||
? help ↑/↓ move enter open n new
|
||||
|
||||
--- Start a task ---
|
||||
|
||||
|
||||
Folder access
|
||||
[WORKSPACE]
|
||||
|
||||
Config, hooks, and exec policies from untrusted folders stay disabled. Trusted project folders can still contribute
|
||||
settings. Skills still load, and tools follow your permission settings. Opening will not change saved trust.
|
||||
|
||||
› 1. Open restricted
|
||||
2. Back to Agent Command Center
|
||||
|
||||
enter continue · esc back
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
source: cli/tests/daemon_startup.rs
|
||||
assertion_line: 325
|
||||
expression: warning.trim()
|
||||
---
|
||||
⚠ Running without the shared background server: this Windows launcher requires embedded mode.
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
source: cli/tests/doctor_enterprise_network.rs
|
||||
expression: stdout
|
||||
---
|
||||
Codex Doctor v0.0.0
|
||||
|
||||
Notes
|
||||
[XX] config config could not be loaded - Fix the reported config error, then rerun codex doctor.
|
||||
-------------------------------------------------------------
|
||||
|
||||
Configuration
|
||||
[XX] config config could not be loaded - Fix the reported config error, then rerun codex doctor.
|
||||
feature flags 0 enabled · 0 overridden
|
||||
error invalid configuration
|
||||
file <CODEX_HOME>/config.toml
|
||||
line 1
|
||||
column 18
|
||||
network diagnostics effective network configuration is unavailable
|
||||
|
||||
-------------------------------------------------------------
|
||||
0 ok | 1 notes | 0 warn | 1 fail failed
|
||||
|
||||
--summary compact output --all expand truncated lists
|
||||
--json redacted report
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
source: cli/tests/doctor_enterprise_network.rs
|
||||
expression: stdout
|
||||
---
|
||||
Codex Doctor v0.0.0
|
||||
|
||||
Configuration
|
||||
[ok] config loaded
|
||||
|
||||
Connectivity
|
||||
[ok] network network-related environment looks readable
|
||||
[ok] websocket Responses WebSocket is not enabled for the active provider
|
||||
[ok] reachability active provider endpoints are reachable over HTTP
|
||||
|
||||
-------------------------------------------------------------
|
||||
4 ok | 0 warn | 0 fail ok
|
||||
|
||||
Run codex doctor without --summary for detailed diagnostics.
|
||||
--all expand truncated lists --json redacted report
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
source: cli/tests/doctor_path_safety.rs
|
||||
expression: "serde_json::to_string_pretty(&check)?"
|
||||
---
|
||||
{
|
||||
"category": "config",
|
||||
"details": {
|
||||
"column": "42",
|
||||
"error": "invalid configuration",
|
||||
"file": "FIXTURE/home/config.toml",
|
||||
"line": "1"
|
||||
},
|
||||
"id": "config.load",
|
||||
"remediation": "Fix the reported config error, then rerun codex doctor.",
|
||||
"status": "fail",
|
||||
"summary": "config could not be loaded"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
---
|
||||
source: cli/tests/doctor_path_safety.rs
|
||||
expression: "serde_json::to_string_pretty(&check)?"
|
||||
---
|
||||
{
|
||||
"category": "config",
|
||||
"details": {
|
||||
"error": "invalid data"
|
||||
},
|
||||
"id": "config.load",
|
||||
"remediation": "Fix the reported config error, then rerun codex doctor.",
|
||||
"status": "fail",
|
||||
"summary": "config could not be loaded"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
---
|
||||
source: cli/tests/doctor_path_safety.rs
|
||||
expression: "serde_json::to_string_pretty(&check)?"
|
||||
---
|
||||
{
|
||||
"category": "config",
|
||||
"details": {
|
||||
"error": "entity not found"
|
||||
},
|
||||
"id": "config.load",
|
||||
"remediation": "Fix the reported config error, then rerun codex doctor.",
|
||||
"status": "fail",
|
||||
"summary": "config could not be loaded"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
---
|
||||
source: cli/tests/doctor_path_safety.rs
|
||||
expression: "serde_json::to_string_pretty(&details)?"
|
||||
---
|
||||
{
|
||||
"operation": "resolve paths only; read/write access is not tested",
|
||||
"path 1": "FIXTURE/workspace/probe-existing (read); path resolved (read/write access not tested)",
|
||||
"path 1 source": "permissions.diagnostic.filesystem.FIXTURE/workspace/probe-existing in user (FIXTURE/home/config.toml)",
|
||||
"path 2": "FIXTURE/workspace/probe-missing (write); missing (may be intentional)",
|
||||
"path 2 source": "permissions.diagnostic.filesystem.FIXTURE/workspace/probe-missing in user (FIXTURE/home/config.toml)",
|
||||
"paths checked": "2 of 2",
|
||||
"permission profile": "diagnostic",
|
||||
"probe budgets": "2 seconds per path, 8 seconds total, at most 32 paths"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
---
|
||||
source: cli/tests/doctor_path_safety.rs
|
||||
expression: "serde_json::to_string_pretty(&details)?"
|
||||
---
|
||||
{
|
||||
"operation": "resolve paths only; read/write access is not tested",
|
||||
"path 1": "FIXTURE/workspace/probe-existing (read); not probed on Windows (network authentication risk)",
|
||||
"path 1 source": "permissions.diagnostic.filesystem.FIXTURE/workspace/probe-existing in user (FIXTURE/home/config.toml)",
|
||||
"path 2": "FIXTURE/workspace/probe-missing (write); not probed on Windows (network authentication risk)",
|
||||
"path 2 source": "permissions.diagnostic.filesystem.FIXTURE/workspace/probe-missing in user (FIXTURE/home/config.toml)",
|
||||
"paths checked": "2 of 2",
|
||||
"permission profile": "diagnostic",
|
||||
"probe budgets": "2 seconds per path, 8 seconds total, at most 32 paths"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
source: cli/tests/doctor_path_safety.rs
|
||||
expression: state_row
|
||||
---
|
||||
[XX] state FIXTURE/sqlite/logs_2.sqlite database failed integrity check
|
||||
-> Move the damaged SQLite database aside, then restart the interactive CLI or app server so it can rebuild that runtime database from saved data. Other entry points may not rebuild automatically.
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
source: cli/tests/doctor_path_safety.rs
|
||||
expression: state_row
|
||||
---
|
||||
[XX] state FIXTURE/sqlite/logs_2.sqlite, FIXTURE/sqlite/goals_1.sqlite databases failed integrity check
|
||||
-> Move the damaged SQLite database aside, then restart the interactive CLI or app server so it can rebuild that runtime database from saved data. Other entry points may not rebuild automatically.
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
source: cli/tests/features.rs
|
||||
expression: output
|
||||
---
|
||||
Error: failed to load bootstrap configuration
|
||||
|
||||
Caused by:
|
||||
unknown key `backslash` in keybinding `backslash`. Use a printable character (for example `a`), function keys (`f1`-`f24`), or one of: enter, tab, backspace, esc, delete, arrows, home/end, page-up/page-down, space, minus.
|
||||
See the Codex keymap documentation for supported actions and examples.
|
||||
in `tui.keymap.editor.insert_newline`
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
source: cli/tests/features.rs
|
||||
expression: "String::from_utf8(output)?"
|
||||
---
|
||||
Error: --add-dir is not supported with --remote. Configure additional workspace roots on the server.
|
||||
24
codex-rs/cli/tests/update.rs
Normal file
24
codex-rs/cli/tests/update.rs
Normal file
@@ -0,0 +1,24 @@
|
||||
use anyhow::Result;
|
||||
use predicates::str::contains;
|
||||
use std::path::Path;
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
|
||||
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
cmd.env("CODEX_HOME", codex_home);
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
#[tokio::test]
|
||||
async fn update_does_not_start_interactive_prompt() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
codex_command(codex_home.path())?
|
||||
.arg("update")
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("`codex update` is not available in debug builds"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
989
codex-rs/cli/tests/worktree.rs
Normal file
989
codex-rs/cli/tests/worktree.rs
Normal file
@@ -0,0 +1,989 @@
|
||||
//! Exercises interactive destination policy, startup and fork, and ownership before the first turn.
|
||||
|
||||
use anyhow::Context as _;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::io::Write as _;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
#[cfg(not(unix))]
|
||||
use tempfile::TempDir;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
|
||||
fn git(cwd: &Path, args: &[&str]) -> anyhow::Result<String> {
|
||||
let output = Command::new("git")
|
||||
.current_dir(cwd)
|
||||
.args([
|
||||
"-c",
|
||||
"user.name=Worktree Test",
|
||||
"-c",
|
||||
"user.email=test@example.invalid",
|
||||
])
|
||||
.args(args)
|
||||
.output()?;
|
||||
anyhow::ensure!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
Ok(String::from_utf8(output.stdout)?.trim().to_owned())
|
||||
}
|
||||
|
||||
// Retain only the unfinished terminal query, never the full output stream.
|
||||
#[derive(Default)]
|
||||
struct TerminalQueries(Vec<u8>);
|
||||
|
||||
impl TerminalQueries {
|
||||
fn feed(&mut self, bytes: &[u8]) -> Vec<u8> {
|
||||
let mut replies = Vec::new();
|
||||
for &byte in bytes {
|
||||
self.0.push(byte);
|
||||
if self.0 == b"\x1b[6n" {
|
||||
replies.extend_from_slice(b"\x1b[1;1R");
|
||||
self.0.clear();
|
||||
} else if self.0 == b"\x1b[c" {
|
||||
replies.extend_from_slice(b"\x1b[?1;2c");
|
||||
self.0.clear();
|
||||
} else {
|
||||
while !b"\x1b[6n".starts_with(&self.0) && !b"\x1b[c".starts_with(&self.0) {
|
||||
self.0.remove(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
replies
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_queries_reply_once_across_every_split() {
|
||||
let input = b"noise\x1b[6n\x1b[c\x1b[6n";
|
||||
let expected = b"\x1b[1;1R\x1b[?1;2c\x1b[1;1R";
|
||||
for split in 0..=input.len() {
|
||||
let mut queries = TerminalQueries::default();
|
||||
let mut replies = queries.feed(&input[..split]);
|
||||
replies.extend(queries.feed(&input[split..]));
|
||||
assert_eq!(replies, expected);
|
||||
assert_eq!(queries.feed(b"more output"), Vec::<u8>::new());
|
||||
}
|
||||
}
|
||||
|
||||
async fn rejected_start(
|
||||
program: &Path,
|
||||
args: &[String],
|
||||
cwd: &Path,
|
||||
env: &HashMap<String, String>,
|
||||
expected: &str,
|
||||
) -> anyhow::Result<String> {
|
||||
let spawned = codex_utils_pty::spawn_pty_process(
|
||||
&program.to_string_lossy(),
|
||||
args,
|
||||
cwd,
|
||||
env,
|
||||
/*arg0*/ &None,
|
||||
codex_utils_pty::TerminalSize {
|
||||
rows: 40,
|
||||
cols: 120,
|
||||
},
|
||||
codex_utils_pty::ChildFds::Inherited(&[]),
|
||||
)
|
||||
.await?;
|
||||
let mut stdout = spawned.stdout_rx;
|
||||
let mut exit = spawned.exit_rx;
|
||||
let mut output = String::new();
|
||||
let mut queries = TerminalQueries::default();
|
||||
let result = tokio::time::timeout(Duration::from_secs(/*secs*/ 45), async {
|
||||
loop {
|
||||
tokio::select! {
|
||||
status = &mut exit, if output.contains(expected) => return Ok::<_, anyhow::Error>(status?),
|
||||
bytes = stdout.recv() => {
|
||||
let Some(bytes) = bytes else {
|
||||
anyhow::ensure!(output.contains(expected), "TUI exited before rejection: {output}");
|
||||
return Ok(exit.await?);
|
||||
};
|
||||
output.push_str(&String::from_utf8_lossy(&bytes));
|
||||
let replies = queries.feed(&bytes);
|
||||
if !replies.is_empty() { spawned.session.writer_sender().send(replies).await?; }
|
||||
}
|
||||
}
|
||||
}
|
||||
}).await;
|
||||
if !matches!(&result, Ok(Ok(code)) if *code != 0) {
|
||||
let _ = writeln!(
|
||||
std::io::stderr(),
|
||||
"worktree rejection failed (timeout={}): expected {:?}; output prefix: {:?}",
|
||||
result.is_err(),
|
||||
expected.chars().take(/*n*/ 200).collect::<String>(),
|
||||
output.chars().take(/*n*/ 4000).collect::<String>()
|
||||
);
|
||||
}
|
||||
if result.is_err() {
|
||||
spawned.session.terminate();
|
||||
}
|
||||
assert_ne!(
|
||||
result.with_context(|| format!("rejection timed out: {output}"))??,
|
||||
0,
|
||||
"{output}"
|
||||
);
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn interactive_worktree_start_and_fork_bind_owner_before_turn() -> anyhow::Result<()> {
|
||||
worktree_start_and_fork("embedded").await
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[cfg_attr(
|
||||
windows,
|
||||
ignore = "requires a non-elevated terminal with daemon breakaway support"
|
||||
)]
|
||||
async fn daemon_worktree_start_and_fork_bind_owner_before_turn() -> anyhow::Result<()> {
|
||||
worktree_start_and_fork("daemon").await
|
||||
}
|
||||
|
||||
async fn worktree_start_and_fork(backend: &str) -> anyhow::Result<()> {
|
||||
// Leave room for the local control socket on Unix platforms with short sun_path limits.
|
||||
#[cfg(unix)]
|
||||
let root = tempfile::Builder::new().tempdir_in("/tmp")?;
|
||||
#[cfg(not(unix))]
|
||||
let root = TempDir::new()?;
|
||||
let root = codex_utils_absolute_path::AbsolutePathBuf::from_absolute_path(root.path())?
|
||||
.canonicalize()?
|
||||
.into_path_buf();
|
||||
let home = root.join("home");
|
||||
let source = root.join("source");
|
||||
let launcher = root.join("launcher");
|
||||
for path in [&home, &source, &launcher, &launcher.join("extra")] {
|
||||
fs::create_dir(path)?;
|
||||
}
|
||||
// Forking without --cd must select the daemon using the resolved project, not this launcher.
|
||||
fs::create_dir(launcher.join(".codex"))?;
|
||||
fs::write(
|
||||
launcher.join(".codex/config.toml"),
|
||||
"features.auth_elicitation = false\n",
|
||||
)?;
|
||||
fs::write(
|
||||
source.join("AGENTS.md"),
|
||||
"committed destination instructions",
|
||||
)?;
|
||||
let server = MockServer::start().await;
|
||||
fs::create_dir(source.join(".codex"))?;
|
||||
fs::write(
|
||||
source.join(".codex/config.toml"),
|
||||
"model = \"destination-model\"\nanalytics.enabled = false\ncli_auth_credentials_store = \"file\"\n",
|
||||
)?;
|
||||
git(&source, &["init", "--quiet"])?;
|
||||
git(&source, &["add", "."])?;
|
||||
git(
|
||||
&source,
|
||||
&["commit", "--quiet", "--no-gpg-sign", "-m", "initial"],
|
||||
)?;
|
||||
fs::write(
|
||||
home.join("config.toml"),
|
||||
format!(
|
||||
r#"
|
||||
cli_auth_credentials_store = "file"
|
||||
chatgpt_base_url = "{}/source/backend-api"
|
||||
analytics.enabled = false
|
||||
check_for_update_on_startup = false
|
||||
features.daemon_auto_start = {}
|
||||
features.mcp_oauth_refresh_coordination = true
|
||||
model_provider = "local"
|
||||
model = "test-model"
|
||||
sandbox_mode = "workspace-write"
|
||||
windows.sandbox = "unelevated"
|
||||
tui.disable_paste_burst = true
|
||||
[otel]
|
||||
metrics_exporter = "none"
|
||||
[model_providers.local]
|
||||
name = "local test"
|
||||
base_url = "{}/v1"
|
||||
wire_api = "responses"
|
||||
[projects.{}]
|
||||
trust_level = "trusted"
|
||||
[projects.{}]
|
||||
trust_level = "trusted"
|
||||
"#,
|
||||
server.uri(),
|
||||
backend == "daemon",
|
||||
server.uri(),
|
||||
serde_json::to_string(&source)?,
|
||||
serde_json::to_string(&launcher)?
|
||||
),
|
||||
)?;
|
||||
fs::write(
|
||||
source.join("AGENTS.md"),
|
||||
"uncommitted launcher instructions",
|
||||
)?;
|
||||
fs::write(
|
||||
source.join(".codex/config.toml"),
|
||||
"model = \"source-model\"\nanalytics.enabled = true\n",
|
||||
)?;
|
||||
app_test_support::write_chatgpt_auth(
|
||||
&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"),
|
||||
codex_config::types::AuthCredentialsStoreMode::File,
|
||||
)?;
|
||||
let program = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
// Keep cold Rosetta translation outside the timed startup assertions.
|
||||
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
|
||||
anyhow::ensure!(
|
||||
Command::new(&program)
|
||||
.env("CODEX_HOME", &home)
|
||||
.arg("--version")
|
||||
.output()?
|
||||
.status
|
||||
.success(),
|
||||
"failed to prepare CLI test executable"
|
||||
);
|
||||
let mut env: HashMap<String, String> = std::env::vars().collect();
|
||||
env.insert("CODEX_HOME".into(), home.display().to_string());
|
||||
env.insert("CODEX_SQLITE_HOME".into(), home.display().to_string());
|
||||
env.insert("NO_PROXY".into(), "127.0.0.1,localhost".into());
|
||||
env.insert("no_proxy".into(), "127.0.0.1,localhost".into());
|
||||
env.insert("TERM".into(), "xterm-256color".into());
|
||||
env.insert("TERM_PROGRAM".into(), "unrecognized-terminal".into());
|
||||
env.insert("OTEL_METRIC_EXPORT_INTERVAL".into(), "100".into());
|
||||
env.insert(
|
||||
"OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE".into(),
|
||||
"delta".into(),
|
||||
);
|
||||
for key in [
|
||||
"CODEX_EXEC_SERVER_URL",
|
||||
"CODEX_ACCESS_TOKEN",
|
||||
"OPENAI_API_KEY",
|
||||
"CODEX_API_KEY",
|
||||
"TMUX",
|
||||
"TMUX_PANE",
|
||||
"ZELLIJ",
|
||||
"ZELLIJ_SESSION_NAME",
|
||||
"ZELLIJ_VERSION",
|
||||
] {
|
||||
env.remove(key);
|
||||
}
|
||||
// Keep the managed package local; no installer or updater participates in this test.
|
||||
struct StopDaemon(Command);
|
||||
impl Drop for StopDaemon {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.output();
|
||||
}
|
||||
}
|
||||
let _daemon = if backend == "daemon" {
|
||||
let bin = home.join("packages/app-server-daemon/current/bin");
|
||||
fs::create_dir_all(&bin)?;
|
||||
let managed = bin.join(if cfg!(windows) { "codex.exe" } else { "codex" });
|
||||
// Hard links change the executable's ctime and invalidate Rosetta's translation cache.
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(program.canonicalize()?, &managed)?;
|
||||
#[cfg(not(unix))]
|
||||
fs::hard_link(&program, &managed)
|
||||
.or_else(|_| codex_utils_cargo_bin::copy_executable(&program, &managed))?;
|
||||
fs::create_dir(home.join("app-server-daemon"))?;
|
||||
fs::write(
|
||||
home.join("app-server-daemon/settings.json"),
|
||||
r#"{"shutdownGraceSeconds":0,"updater":{"autoUpdateEnabled":false}}"#,
|
||||
)?;
|
||||
let mut daemon_stop = Command::new(&program);
|
||||
daemon_stop
|
||||
.envs(&env)
|
||||
.args(["app-server", "daemon", "stop"]);
|
||||
Some(StopDaemon(daemon_stop))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Every launch, including rejection cases, exercises the same CLI feature opt-in.
|
||||
let worktree_args: Vec<String> = vec![
|
||||
"--worktree".into(),
|
||||
"--enable".into(),
|
||||
"worktrees".into(),
|
||||
"--no-alt-screen".into(),
|
||||
"-c".into(),
|
||||
"suppress_unstable_features_warning=true".into(),
|
||||
];
|
||||
let mut owner = None;
|
||||
let mut previous: Vec<String> = Vec::new();
|
||||
let prompt = "describe checkout";
|
||||
for (fork, explicit_cd, analytics, auth_failure) in [
|
||||
(false, false, false, false),
|
||||
(true, false, false, false),
|
||||
(true, true, false, false),
|
||||
(false, false, true, false),
|
||||
(false, false, false, true),
|
||||
] {
|
||||
if auth_failure {
|
||||
fs::write(
|
||||
source.join(".codex/config.toml"),
|
||||
"forced_login_method = \"api\"\n",
|
||||
)?;
|
||||
git(
|
||||
&source,
|
||||
&[
|
||||
"commit",
|
||||
"--quiet",
|
||||
"--no-gpg-sign",
|
||||
"-am",
|
||||
"require API login",
|
||||
],
|
||||
)?;
|
||||
fs::write(source.join(".codex/config.toml"), "")?;
|
||||
}
|
||||
let (metric_tx, mut metric_rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
Mock::given(wiremock::matchers::path("/metrics"))
|
||||
.respond_with(move |request: &wiremock::Request| {
|
||||
let _ = metric_tx.send(request.body.clone());
|
||||
ResponseTemplate::new(200).set_body_json(serde_json::json!({}))
|
||||
})
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(wiremock::matchers::method("GET"))
|
||||
.and(wiremock::matchers::path(
|
||||
"/source/backend-api/wham/config/bundle",
|
||||
))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"config_toml": { "enterprise_managed": [{ "id": "test", "name": "test",
|
||||
"contents": "developer_instructions = \"managed cloud instructions\"" }] }
|
||||
})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
let response = app_test_support::create_final_assistant_message_sse_response("done")?;
|
||||
let observed_source = source.clone();
|
||||
let observed_pool = home.join("worktrees");
|
||||
let observed_previous = previous.clone();
|
||||
Mock::given(wiremock::matchers::method("POST"))
|
||||
.and(wiremock::matchers::path("/v1/responses"))
|
||||
.respond_with(move |request: &wiremock::Request| {
|
||||
let observed = (|| {
|
||||
let checkouts = git(&observed_source, &["worktree", "list", "--porcelain"])?;
|
||||
let checkout = checkouts
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix("worktree "))
|
||||
.find(|path| {
|
||||
Path::new(path).starts_with(&observed_pool)
|
||||
&& !observed_previous.contains(&path.to_string())
|
||||
})
|
||||
.context("new managed checkout")?
|
||||
.to_owned();
|
||||
let metadata = git(
|
||||
Path::new(&checkout),
|
||||
&["rev-parse", "--git-path", "codex-thread.json"],
|
||||
)?;
|
||||
let metadata: Value =
|
||||
serde_json::from_slice(&fs::read(Path::new(&checkout).join(metadata))?)?;
|
||||
Ok::<_, anyhow::Error>((request.body.clone(), checkout, metadata))
|
||||
})();
|
||||
let _ = tx.send(observed);
|
||||
ResponseTemplate::new(200)
|
||||
.insert_header("content-type", "text/event-stream")
|
||||
.set_body_string(response.clone())
|
||||
})
|
||||
.mount(&server)
|
||||
.await;
|
||||
let mut args = worktree_args.clone();
|
||||
if backend == "daemon" && previous.is_empty() {
|
||||
args.extend(["-c".into(), "features.auth_elicitation=true".into()]);
|
||||
}
|
||||
if fork {
|
||||
args.extend([
|
||||
"--add-dir".into(),
|
||||
"extra".into(),
|
||||
"fork".into(),
|
||||
if explicit_cd {
|
||||
owner.clone().context("previous fork owner")?
|
||||
} else {
|
||||
"managed-source".to_owned()
|
||||
},
|
||||
]);
|
||||
} else {
|
||||
args.extend(["--cd".into(), source.display().to_string()]);
|
||||
}
|
||||
if explicit_cd {
|
||||
args.extend(["--cd".into(), source.join(".codex").display().to_string()]);
|
||||
}
|
||||
if analytics {
|
||||
args.extend([
|
||||
"-c".into(),
|
||||
// An explicit collector is independent of built-in analytics consent.
|
||||
"analytics.enabled=false".into(),
|
||||
"-c".into(),
|
||||
format!(
|
||||
"otel.metrics_exporter={{otlp-http={{endpoint=\"{}/metrics\",protocol=\"json\"}}}}",
|
||||
server.uri()
|
||||
),
|
||||
]);
|
||||
}
|
||||
args.push(prompt.into());
|
||||
if previous.is_empty() {
|
||||
let mut untrusted_args = args.clone();
|
||||
untrusted_args.extend([
|
||||
"-c".into(),
|
||||
format!(
|
||||
"projects={{{}={{trust_level=\"untrusted\"}}}}",
|
||||
serde_json::to_string(&source)?
|
||||
),
|
||||
]);
|
||||
rejected_start(
|
||||
&program,
|
||||
&untrusted_args,
|
||||
&launcher,
|
||||
&env,
|
||||
"cannot create a checkout from an explicitly untrusted source",
|
||||
)
|
||||
.await?;
|
||||
assert!(!home.join("worktrees").exists());
|
||||
}
|
||||
let spawned = codex_utils_pty::spawn_pty_process(
|
||||
&program.to_string_lossy(),
|
||||
&args,
|
||||
&launcher,
|
||||
&env,
|
||||
/*arg0*/ &None,
|
||||
codex_utils_pty::TerminalSize {
|
||||
rows: 40,
|
||||
cols: 120,
|
||||
},
|
||||
codex_utils_pty::ChildFds::Inherited(&[]),
|
||||
)
|
||||
.await?;
|
||||
let session = spawned.session;
|
||||
let mut stdout = spawned.stdout_rx;
|
||||
let mut output = String::new();
|
||||
let mut queries = TerminalQueries::default();
|
||||
let observed = tokio::time::timeout(Duration::from_secs(/*secs*/ 45), async {
|
||||
loop {
|
||||
tokio::select! {
|
||||
body = rx.recv() => {
|
||||
let (body, checkout, metadata) = body.context("model request")??;
|
||||
let body: Value = serde_json::from_slice(&body)?;
|
||||
// Background title generation can reach the model before the user turn.
|
||||
let is_user_turn = body["input"].as_array().is_some_and(|input| {
|
||||
input.iter().any(|item| {
|
||||
item["role"] == "user"
|
||||
&& item["content"].as_array().is_some_and(|content| {
|
||||
content.iter().any(|part| part["text"] == prompt)
|
||||
})
|
||||
})
|
||||
});
|
||||
if !is_user_turn {
|
||||
continue;
|
||||
}
|
||||
return Ok::<_, anyhow::Error>((body, checkout, metadata));
|
||||
}
|
||||
bytes = stdout.recv() => {
|
||||
let bytes = bytes.context("TUI exited before model request")?;
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
output.push_str(&text);
|
||||
if auth_failure && output.contains("API key login is required") && output.contains("Do not use --force.") {
|
||||
anyhow::bail!("observed required API login rejection");
|
||||
}
|
||||
let replies = queries.feed(&bytes);
|
||||
if !replies.is_empty() { session.writer_sender().send(replies).await?; }
|
||||
}
|
||||
}
|
||||
}
|
||||
}).await;
|
||||
if auth_failure {
|
||||
assert!(observed.is_ok_and(|result| result.is_err()), "{output}");
|
||||
let exit =
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), spawned.exit_rx).await??;
|
||||
assert_ne!(exit, 0);
|
||||
assert!(output.contains("API key login is required"), "{output}");
|
||||
assert!(!home.join("auth.json").exists());
|
||||
assert!(output.contains("The checkout was kept"), "{output}");
|
||||
continue;
|
||||
}
|
||||
let renamed = if !fork && let Ok(Ok((_, _, metadata))) = &observed {
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), async {
|
||||
session
|
||||
.writer_sender()
|
||||
.send(b"/rename managed-source\r".to_vec())
|
||||
.await?;
|
||||
let thread_id = codex_protocol::ThreadId::from_string(
|
||||
metadata["ownerThreadId"].as_str().context("owner id")?,
|
||||
)?;
|
||||
loop {
|
||||
if codex_rollout::find_thread_name_by_id(&home, &thread_id)
|
||||
.await?
|
||||
.as_deref()
|
||||
== Some("managed-source")
|
||||
{
|
||||
return Ok::<_, anyhow::Error>(());
|
||||
}
|
||||
tokio::select! {
|
||||
bytes = stdout.recv() => {
|
||||
let bytes = bytes.context("TUI exited before rename confirmation")?;
|
||||
output.push_str(&String::from_utf8_lossy(&bytes));
|
||||
let replies = queries.feed(&bytes);
|
||||
if !replies.is_empty() { session.writer_sender().send(replies).await?; }
|
||||
}
|
||||
_ = tokio::time::sleep(Duration::from_millis(/*millis*/ 25)) => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.context("rename timed out")
|
||||
.and_then(std::convert::identity)
|
||||
} else {
|
||||
Ok(())
|
||||
};
|
||||
if backend == "daemon" && !analytics && matches!(observed, Ok(Ok(_))) {
|
||||
session.writer_sender().send(b"/status\r".to_vec()).await?;
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), async {
|
||||
while !output.contains("Local background server") {
|
||||
let bytes = stdout
|
||||
.recv()
|
||||
.await
|
||||
.context("TUI exited before daemon status")?;
|
||||
output.push_str(&String::from_utf8_lossy(&bytes));
|
||||
let replies = queries.feed(&bytes);
|
||||
if !replies.is_empty() {
|
||||
session.writer_sender().send(replies).await?;
|
||||
}
|
||||
}
|
||||
Ok::<_, anyhow::Error>(())
|
||||
})
|
||||
.await
|
||||
.with_context(|| format!("daemon status timed out: {output}"))??;
|
||||
}
|
||||
if analytics {
|
||||
for reason in ["turn_start", "resize"] {
|
||||
let started = Instant::now();
|
||||
let wait = if reason == "resize" {
|
||||
session.resize(codex_utils_pty::TerminalSize {
|
||||
rows: 80,
|
||||
cols: 240,
|
||||
})?;
|
||||
Duration::from_secs(/*secs*/ 30)
|
||||
} else {
|
||||
Duration::from_secs(/*secs*/ 10)
|
||||
};
|
||||
tokio::time::timeout(wait, async {
|
||||
loop {
|
||||
tokio::select! {
|
||||
body = metric_rx.recv() => {
|
||||
let payload: Value = serde_json::from_slice(&body.context("metric body")?)?;
|
||||
let found = payload["resourceMetrics"].as_array().into_iter().flatten()
|
||||
.flat_map(|resource| resource["scopeMetrics"].as_array().into_iter().flatten())
|
||||
.flat_map(|scope| scope["metrics"].as_array().into_iter().flatten())
|
||||
.filter(|metric| metric["name"] == "codex.tui.terminal_size")
|
||||
.flat_map(|metric| metric["sum"]["dataPoints"].as_array().into_iter().flatten())
|
||||
.any(|point| point["attributes"].as_array().into_iter().flatten().any(|attribute|
|
||||
attribute["key"] == "observation_reason" && attribute["value"]["stringValue"] == reason));
|
||||
if found { return Ok::<_, anyhow::Error>(()); }
|
||||
}
|
||||
bytes = stdout.recv() => {
|
||||
let bytes = bytes.context("TUI exited before size observation")?;
|
||||
output.push_str(&String::from_utf8_lossy(&bytes));
|
||||
let replies = queries.feed(&bytes);
|
||||
if !replies.is_empty() { session.writer_sender().send(replies).await?; }
|
||||
}
|
||||
}
|
||||
}
|
||||
}).await.with_context(|| format!("waiting for {reason} observation"))??;
|
||||
if reason == "resize" {
|
||||
assert!(started.elapsed() >= Duration::from_secs(/*secs*/ 15));
|
||||
}
|
||||
}
|
||||
}
|
||||
let startup_result = observed.as_ref().map(|result| result.as_ref().map(|_| ()));
|
||||
assert!(
|
||||
!output.contains("Under-development features enabled:"),
|
||||
"{output}"
|
||||
);
|
||||
if !matches!(startup_result, Ok(Ok(()))) || renamed.is_err() {
|
||||
// Bypass libtest capture and report before tearing down the Windows PTY.
|
||||
let _ = writeln!(
|
||||
std::io::stderr(),
|
||||
"worktree failure (fork={fork}, explicit_cd={explicit_cd}): startup={startup_result:?}, rename={renamed:?}\nTUI output: {:?}",
|
||||
output.chars().take(/*n*/ 4000).collect::<String>()
|
||||
);
|
||||
}
|
||||
if matches!(startup_result, Ok(Ok(()))) && renamed.is_ok() {
|
||||
if !fork && backend == "embedded" {
|
||||
for (input, expected) in [
|
||||
("/daemon\r", "Install latest public stable"),
|
||||
("\r", "Update and exit"),
|
||||
("\x1b[B\r", "Updating the local background server..."),
|
||||
] {
|
||||
session
|
||||
.writer_sender()
|
||||
.send(input.as_bytes().to_vec())
|
||||
.await?;
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), async {
|
||||
while !output.contains(expected) {
|
||||
let bytes = stdout.recv().await.context("TUI exited before handoff")?;
|
||||
output.push_str(&String::from_utf8_lossy(&bytes));
|
||||
}
|
||||
Ok::<_, anyhow::Error>(())
|
||||
})
|
||||
.await
|
||||
.with_context(|| format!("waiting for {expected}: {output}"))??;
|
||||
}
|
||||
} else {
|
||||
session.writer_sender().send(b"/quit\r".to_vec()).await?;
|
||||
}
|
||||
} else {
|
||||
session.terminate();
|
||||
}
|
||||
let exit =
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), spawned.exit_rx).await??;
|
||||
// Include shutdown output: ConPTY can retain the channel after process exit.
|
||||
let _ = tokio::time::timeout(Duration::from_secs(/*secs*/ 1), async {
|
||||
while let Some(bytes) = stdout.recv().await {
|
||||
output.push_str(&String::from_utf8_lossy(&bytes));
|
||||
}
|
||||
})
|
||||
.await;
|
||||
let elevated_handoff = cfg!(windows)
|
||||
&& output.contains("start the Windows daemon from a non-elevated terminal");
|
||||
assert_eq!(exit, i32::from(elevated_handoff), "{output}");
|
||||
assert!(!output.contains("The checkout was kept"), "{output}");
|
||||
let metrics = server
|
||||
.received_requests()
|
||||
.await
|
||||
.context("requests")?
|
||||
.into_iter()
|
||||
.filter(|request| request.url.path() == "/metrics")
|
||||
.map(|request| serde_json::from_slice::<Value>(&request.body))
|
||||
.collect::<serde_json::Result<Vec<_>>>()?;
|
||||
if analytics {
|
||||
let exported = metrics
|
||||
.iter()
|
||||
.flat_map(|payload| payload["resourceMetrics"].as_array().into_iter().flatten())
|
||||
.flat_map(|resource| resource["scopeMetrics"].as_array().into_iter().flatten())
|
||||
.flat_map(|scope| scope["metrics"].as_array().into_iter().flatten())
|
||||
.collect::<Vec<_>>();
|
||||
if backend == "embedded" {
|
||||
let update = exported
|
||||
.iter()
|
||||
.find(|metric| metric["name"] == "codex.daemon.update")
|
||||
.context("handoff metric")?;
|
||||
let update_point = &update["sum"]["dataPoints"][0];
|
||||
assert_eq!(update_point["asInt"], 1);
|
||||
}
|
||||
let point = exported
|
||||
.iter()
|
||||
.filter(|metric| metric["name"] == "codex.tui.start")
|
||||
.flat_map(|metric| metric["sum"]["dataPoints"].as_array().into_iter().flatten())
|
||||
.next()
|
||||
.context("codex.tui.start data point")?;
|
||||
assert_eq!(point["asInt"], 1);
|
||||
let tags = point["attributes"]
|
||||
.as_array()
|
||||
.context("codex.tui.start attributes")?
|
||||
.iter()
|
||||
.map(|attribute| {
|
||||
Ok((
|
||||
attribute["key"].as_str().context("metric tag key")?,
|
||||
attribute["value"]["stringValue"]
|
||||
.as_str()
|
||||
.context("metric tag value")?,
|
||||
))
|
||||
})
|
||||
.collect::<anyhow::Result<HashMap<_, _>>>()?;
|
||||
let mut expected_tags = HashMap::from([
|
||||
("app_server_mode", "in_process"),
|
||||
("terminal_name", "unknown"),
|
||||
("terminal_columns", "120-239"),
|
||||
("terminal_rows", "40-79"),
|
||||
("multiplexer", "none"),
|
||||
("daemon_selection_reason", "incompatible_option"),
|
||||
(
|
||||
"daemon_auto_start",
|
||||
if backend == "daemon" {
|
||||
"enabled"
|
||||
} else {
|
||||
"disabled"
|
||||
},
|
||||
),
|
||||
("auto_update", "enabled"),
|
||||
("auto_update_setting", "default"),
|
||||
("update_interval_setting", "default"),
|
||||
("shutdown_grace_setting", "default"),
|
||||
]);
|
||||
#[cfg(windows)]
|
||||
if codex_app_server_daemon::is_elevated()? {
|
||||
expected_tags.insert("daemon_selection_reason", "elevated_windows");
|
||||
}
|
||||
if backend == "daemon" {
|
||||
expected_tags.extend([
|
||||
("auto_update", "disabled"),
|
||||
("auto_update_setting", "configured"),
|
||||
("shutdown_grace_setting", "configured"),
|
||||
]);
|
||||
}
|
||||
assert_eq!(tags, expected_tags);
|
||||
let observations = exported
|
||||
.iter()
|
||||
.filter(|metric| metric["name"] == "codex.tui.terminal_size")
|
||||
.flat_map(|metric| metric["sum"]["dataPoints"].as_array().into_iter().flatten())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(observations.len(), 2);
|
||||
for observation in observations {
|
||||
assert_eq!(observation["asInt"], 1);
|
||||
let observation_tags = observation["attributes"]
|
||||
.as_array()
|
||||
.context("observation attributes")?
|
||||
.iter()
|
||||
.map(|attribute| {
|
||||
Ok((
|
||||
attribute["key"].as_str().context("observation key")?,
|
||||
attribute["value"]["stringValue"]
|
||||
.as_str()
|
||||
.context("observation value")?,
|
||||
))
|
||||
})
|
||||
.collect::<anyhow::Result<HashMap<_, _>>>()?;
|
||||
let reason = observation_tags["observation_reason"];
|
||||
let mut expected = expected_tags.clone();
|
||||
expected.insert("observation_reason", reason);
|
||||
match reason {
|
||||
"turn_start" => {}
|
||||
"resize" => {
|
||||
expected.insert("terminal_columns", "240-479");
|
||||
expected.insert("terminal_rows", "80-119");
|
||||
}
|
||||
other => anyhow::bail!("unexpected observation: {other}"),
|
||||
}
|
||||
assert_eq!(observation_tags, expected);
|
||||
}
|
||||
} else {
|
||||
assert!(metrics.is_empty(), "metrics exporter disabled");
|
||||
}
|
||||
let (body, checkout, metadata) = observed
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"startup timed out: {}",
|
||||
output.chars().take(/*n*/ 4000).collect::<String>()
|
||||
)
|
||||
})?
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"startup output: {}",
|
||||
output.chars().take(/*n*/ 4000).collect::<String>()
|
||||
)
|
||||
})?;
|
||||
renamed.with_context(|| {
|
||||
format!(
|
||||
"rename output: {}",
|
||||
output.chars().take(/*n*/ 4000).collect::<String>()
|
||||
)
|
||||
})?;
|
||||
let next_owner = metadata["ownerThreadId"]
|
||||
.as_str()
|
||||
.context("owner bound before request")?
|
||||
.to_owned();
|
||||
assert_ne!(owner.as_ref(), Some(&next_owner));
|
||||
assert_eq!(
|
||||
git(Path::new(&checkout), &["show", "HEAD:AGENTS.md"])?,
|
||||
"committed destination instructions"
|
||||
);
|
||||
let context = body["input"]
|
||||
.as_array()
|
||||
.context("message input")?
|
||||
.iter()
|
||||
.filter_map(|item| item["content"].as_array())
|
||||
.flatten()
|
||||
.filter_map(|part| part["text"].as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
if explicit_cd {
|
||||
let expected = format!("{checkout}/.codex").replace('\\', "/");
|
||||
assert!(context.replace('\\', "/").contains(&expected), "{context}");
|
||||
}
|
||||
assert!(
|
||||
context.contains("committed destination instructions"),
|
||||
"{context}"
|
||||
);
|
||||
assert!(
|
||||
!context.contains("uncommitted launcher instructions"),
|
||||
"{context}"
|
||||
);
|
||||
if fork {
|
||||
assert!(
|
||||
context.contains(&launcher.join("extra").display().to_string()),
|
||||
"{context}"
|
||||
);
|
||||
}
|
||||
assert_eq!(body["model"], "destination-model");
|
||||
assert!(context.contains("managed cloud instructions"), "{context}");
|
||||
if previous.is_empty() {
|
||||
// A legacy summary still says launcher A, but persisted turns use checkout B.
|
||||
let sqlite = codex_state::SqliteConfig::new_for_testing(
|
||||
codex_utils_absolute_path::AbsolutePathBuf::from_absolute_path(&home)?,
|
||||
);
|
||||
let db = sqlite.open_read_write_pool(&sqlite.state_db_path()).await?;
|
||||
sqlx::query("UPDATE threads SET cwd = ? WHERE id = ?")
|
||||
.bind(launcher.to_string_lossy().as_ref())
|
||||
.bind(&next_owner)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
db.close().await;
|
||||
// B inherits trust from its primary repository; no exact trusted entry masks cloud distrust.
|
||||
let home_config = home.join("config.toml");
|
||||
let launcher_config = fs::read_to_string(&home_config)?;
|
||||
fs::write(
|
||||
&home_config,
|
||||
launcher_config.replace(
|
||||
"cli_auth_credentials_store = \"file\"",
|
||||
"cli_auth_credentials_store = \"ephemeral\"",
|
||||
),
|
||||
)?;
|
||||
let cache = home.join("cloud-config-bundle-cache.json");
|
||||
if cache.exists() {
|
||||
fs::remove_file(&cache)?;
|
||||
}
|
||||
let request_count = server.received_requests().await.context("requests")?.len();
|
||||
Mock::given(wiremock::matchers::path("/source/backend-api/wham/config/bundle"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"config_toml": {"enterprise_managed": [{"id":"distrust", "name":"distrust",
|
||||
"contents": format!("[projects.{}]\ntrust_level = \"untrusted\"\n", serde_json::to_string(&codex_config::loader::project_trust_key(Path::new(&checkout)))?)}]}
|
||||
}))).with_priority(/*priority*/ 1).mount(&server).await;
|
||||
let before = git(&source, &["worktree", "list", "--porcelain"])?;
|
||||
rejected_start(
|
||||
&program,
|
||||
&[
|
||||
"--worktree".into(),
|
||||
"--enable".into(),
|
||||
"worktrees".into(),
|
||||
"--no-alt-screen".into(),
|
||||
"fork".into(),
|
||||
next_owner.clone(),
|
||||
],
|
||||
&launcher,
|
||||
&env,
|
||||
"cannot create a checkout from an explicitly untrusted source",
|
||||
)
|
||||
.await?;
|
||||
assert!(
|
||||
server
|
||||
.received_requests()
|
||||
.await
|
||||
.context("requests")?
|
||||
.iter()
|
||||
.skip(request_count)
|
||||
.any(|request| request.url.path() == "/source/backend-api/wham/config/bundle")
|
||||
);
|
||||
assert_eq!(git(&source, &["worktree", "list", "--porcelain"])?, before);
|
||||
server.reset().await;
|
||||
if cache.exists() {
|
||||
fs::remove_file(&cache)?;
|
||||
}
|
||||
let count = server.received_requests().await.context("requests")?.len();
|
||||
Mock::given(wiremock::matchers::path("/source/backend-api/wham/config/bundle"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"config_toml": {"enterprise_managed": [{"id":"distrust-source", "name":"distrust-source",
|
||||
"contents": format!("[projects.{}]\ntrust_level = \"untrusted\"\n", serde_json::to_string(&codex_config::loader::project_trust_key(&source.join(".codex")))?)}]}
|
||||
}))).mount(&server).await;
|
||||
let output = rejected_start(
|
||||
&program,
|
||||
&[
|
||||
"--worktree".into(),
|
||||
"--enable".into(),
|
||||
"worktrees".into(),
|
||||
"--no-alt-screen".into(),
|
||||
"--cd".into(),
|
||||
source.join(".codex").display().to_string(),
|
||||
],
|
||||
&launcher,
|
||||
&env,
|
||||
"cannot create a checkout from an explicitly untrusted source",
|
||||
)
|
||||
.await?;
|
||||
let requests = server.received_requests().await.context("requests")?;
|
||||
let paths = requests
|
||||
.iter()
|
||||
.skip(count)
|
||||
.map(|r| r.url.path())
|
||||
.collect::<Vec<_>>();
|
||||
assert!(paths.contains(&"/source/backend-api/wham/config/bundle"));
|
||||
assert!(!paths.contains(&"/v1/responses"));
|
||||
let after = git(&source, &["worktree", "list", "--porcelain"])?;
|
||||
let retained = after
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix("worktree "))
|
||||
.find(|path| {
|
||||
!before
|
||||
.lines()
|
||||
.any(|line| line.strip_prefix("worktree ") == Some(*path))
|
||||
})
|
||||
.context("retained untrusted checkout")?;
|
||||
assert!(output.contains("The checkout was kept"), "{output}");
|
||||
let metadata = git(
|
||||
Path::new(retained),
|
||||
&["rev-parse", "--git-path", "codex-thread.json"],
|
||||
)?;
|
||||
assert!(!Path::new(retained).join(metadata).exists());
|
||||
previous.push(retained.to_owned());
|
||||
fs::write(&home_config, launcher_config)?;
|
||||
if cache.exists() {
|
||||
fs::remove_file(&cache)?;
|
||||
}
|
||||
}
|
||||
previous.push(checkout);
|
||||
owner = Some(next_owner);
|
||||
server.reset().await;
|
||||
}
|
||||
// Source loads its healthy uncommitted config, but the new checkout loads malformed HEAD.
|
||||
fs::write(source.join(".codex/config.toml"), "not = [valid toml")?;
|
||||
git(
|
||||
&source,
|
||||
&[
|
||||
"commit",
|
||||
"--quiet",
|
||||
"--no-gpg-sign",
|
||||
"-am",
|
||||
"invalid destination",
|
||||
],
|
||||
)?;
|
||||
fs::write(source.join(".codex/config.toml"), "")?;
|
||||
let before = git(&source, &["worktree", "list", "--porcelain"])?;
|
||||
let output = rejected_start(
|
||||
&program,
|
||||
&[
|
||||
"--worktree".into(),
|
||||
"--enable".into(),
|
||||
"worktrees".into(),
|
||||
"--no-alt-screen".into(),
|
||||
"--cd".into(),
|
||||
source.display().to_string(),
|
||||
],
|
||||
&launcher,
|
||||
&env,
|
||||
"Do not use --force.",
|
||||
)
|
||||
.await?;
|
||||
let after = git(&source, &["worktree", "list", "--porcelain"])?;
|
||||
let retained = after
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix("worktree "))
|
||||
.find(|path| {
|
||||
!before
|
||||
.lines()
|
||||
.any(|line| line.strip_prefix("worktree ") == Some(*path))
|
||||
})
|
||||
.context("retained failed checkout")?;
|
||||
assert!(
|
||||
output.contains(&format!(
|
||||
"{:?}",
|
||||
Path::new(&retained.replace('/', std::path::MAIN_SEPARATOR_STR))
|
||||
)),
|
||||
"{output}"
|
||||
);
|
||||
assert!(output.contains("The checkout was kept"), "{output}");
|
||||
assert!(
|
||||
output.contains("worktree remove <checkout-path>"),
|
||||
"{output}"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user