Base: codex-main originale (prima del fork aKode)
This commit is contained in:
7
codex-rs/exec/tests/all.rs
Normal file
7
codex-rs/exec/tests/all.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
#![allow(clippy::expect_used)]
|
||||
|
||||
// Single integration test binary that aggregates all test modules.
|
||||
// The submodules live in `tests/suite/`.
|
||||
mod suite;
|
||||
|
||||
mod event_processor_with_json_output;
|
||||
1819
codex-rs/exec/tests/event_processor_with_json_output.rs
Normal file
1819
codex-rs/exec/tests/event_processor_with_json_output.rs
Normal file
File diff suppressed because it is too large
Load Diff
4
codex-rs/exec/tests/fixtures/apply_patch_freeform_final.txt
vendored
Normal file
4
codex-rs/exec/tests/fixtures/apply_patch_freeform_final.txt
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
class BaseClass:
|
||||
def method():
|
||||
|
||||
return True
|
||||
72
codex-rs/exec/tests/suite/add_dir.rs
Normal file
72
codex-rs/exec/tests/suite/add_dir.rs
Normal file
@@ -0,0 +1,72 @@
|
||||
#![cfg(not(target_os = "windows"))]
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
|
||||
/// Verify that the --add-dir flag is accepted and the command runs successfully.
|
||||
/// This test confirms the CLI argument is properly wired up.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
|
||||
async fn accepts_add_dir_flag() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("response_1"),
|
||||
responses::ev_assistant_message("response_1", "Task completed"),
|
||||
responses::ev_completed("response_1"),
|
||||
]);
|
||||
responses::mount_sse_once(&server, body).await;
|
||||
|
||||
// Create temporary directories to use with --add-dir
|
||||
let temp_dir1 = tempfile::tempdir()?;
|
||||
let temp_dir2 = tempfile::tempdir()?;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("--sandbox")
|
||||
.arg("workspace-write")
|
||||
.arg("--add-dir")
|
||||
.arg(temp_dir1.path())
|
||||
.arg("--add-dir")
|
||||
.arg(temp_dir2.path())
|
||||
.arg("test with additional directories")
|
||||
.assert()
|
||||
.code(0);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Verify that multiple --add-dir flags can be specified.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn accepts_multiple_add_dir_flags() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("response_1"),
|
||||
responses::ev_assistant_message("response_1", "Multiple directories accepted"),
|
||||
responses::ev_completed("response_1"),
|
||||
]);
|
||||
responses::mount_sse_once(&server, body).await;
|
||||
|
||||
let temp_dir1 = tempfile::tempdir()?;
|
||||
let temp_dir2 = tempfile::tempdir()?;
|
||||
let temp_dir3 = tempfile::tempdir()?;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("--sandbox")
|
||||
.arg("workspace-write")
|
||||
.arg("--add-dir")
|
||||
.arg(temp_dir1.path())
|
||||
.arg("--add-dir")
|
||||
.arg(temp_dir2.path())
|
||||
.arg("--add-dir")
|
||||
.arg(temp_dir3.path())
|
||||
.arg("test with three directories")
|
||||
.assert()
|
||||
.code(0);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
74
codex-rs/exec/tests/suite/agents_md.rs
Normal file
74
codex-rs/exec/tests/suite/agents_md.rs
Normal file
@@ -0,0 +1,74 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_includes_workspace_agents_md_in_request() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
std::fs::write(test.cwd_path().join("AGENTS.md"), "workspace instructions")?;
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("resp1"),
|
||||
responses::ev_assistant_message("m1", "fixture hello"),
|
||||
responses::ev_completed("resp1"),
|
||||
]);
|
||||
let response_mock = responses::mount_sse_once(&server, body).await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("tell me something")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let user_messages = response_mock.single_request().message_input_texts("user");
|
||||
assert!(
|
||||
user_messages
|
||||
.iter()
|
||||
.any(|text| text.contains("workspace instructions")),
|
||||
"request should include workspace AGENTS.md instructions: {user_messages:?}"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_prefers_workspace_agents_override_md() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
std::fs::write(test.cwd_path().join("AGENTS.md"), "base instructions")?;
|
||||
std::fs::write(
|
||||
test.cwd_path().join("AGENTS.override.md"),
|
||||
"override instructions",
|
||||
)?;
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("resp1"),
|
||||
responses::ev_assistant_message("m1", "fixture hello"),
|
||||
responses::ev_completed("resp1"),
|
||||
]);
|
||||
let response_mock = responses::mount_sse_once(&server, body).await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("tell me something")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let user_messages = response_mock.single_request().message_input_texts("user");
|
||||
assert!(
|
||||
user_messages
|
||||
.iter()
|
||||
.any(|text| text.contains("override instructions")),
|
||||
"request should include AGENTS.override.md instructions: {user_messages:?}"
|
||||
);
|
||||
assert!(
|
||||
user_messages
|
||||
.iter()
|
||||
.all(|text| !text.contains("base instructions")),
|
||||
"request should exclude shadowed AGENTS.md instructions: {user_messages:?}"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
519
codex-rs/exec/tests/suite/apply_patch.rs
Normal file
519
codex-rs/exec/tests/suite/apply_patch.rs
Normal file
@@ -0,0 +1,519 @@
|
||||
#![allow(clippy::unwrap_used, unused_imports)]
|
||||
|
||||
use anyhow::Context;
|
||||
use assert_cmd::prelude::*;
|
||||
use codex_apply_patch::CODEX_CORE_APPLY_PATCH_ARG1;
|
||||
use core_test_support::responses::ev_apply_patch_custom_tool_call;
|
||||
use core_test_support::responses::ev_assistant_message;
|
||||
use core_test_support::responses::ev_completed;
|
||||
use core_test_support::responses::ev_exec_command_call_with_args;
|
||||
use core_test_support::responses::mount_sse_sequence;
|
||||
use core_test_support::responses::sse;
|
||||
use core_test_support::responses::start_mock_server;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
use std::process::Command;
|
||||
use tempfile::tempdir;
|
||||
|
||||
/// While we may add an `apply-patch` subcommand to the `codex` CLI multitool
|
||||
/// at some point, we must ensure that the smaller `codex-exec` CLI can still
|
||||
/// emulate the `apply_patch` CLI.
|
||||
#[test]
|
||||
fn test_standalone_exec_cli_can_use_apply_patch() -> anyhow::Result<()> {
|
||||
let tmp = tempdir()?;
|
||||
let relative_path = "source.txt";
|
||||
let absolute_path = tmp.path().join(relative_path);
|
||||
fs::write(&absolute_path, "original content\n")?;
|
||||
|
||||
Command::new(codex_utils_cargo_bin::cargo_bin("codex-exec")?)
|
||||
.arg(CODEX_CORE_APPLY_PATCH_ARG1)
|
||||
.arg(
|
||||
r#"*** Begin Patch
|
||||
*** Update File: source.txt
|
||||
@@
|
||||
-original content
|
||||
+modified by apply_patch
|
||||
*** End Patch"#,
|
||||
)
|
||||
.current_dir(tmp.path())
|
||||
.assert()
|
||||
.success()
|
||||
.stdout("Success. Updated the following files:\nM source.txt\n")
|
||||
.stderr(predicates::str::is_empty());
|
||||
assert_eq!(
|
||||
fs::read_to_string(absolute_path)?,
|
||||
"modified by apply_patch\n"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn test_apply_patch_tool() -> anyhow::Result<()> {
|
||||
use core_test_support::skip_if_no_network;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let test = test_codex_exec();
|
||||
let tmp_path = test.cwd_path().to_path_buf();
|
||||
let add_patch = r#"*** Begin Patch
|
||||
*** Add File: test.md
|
||||
+Hello world
|
||||
*** End Patch"#;
|
||||
let update_patch = r#"*** Begin Patch
|
||||
*** Update File: test.md
|
||||
@@
|
||||
-Hello world
|
||||
+Final text
|
||||
*** End Patch"#;
|
||||
let response_streams = vec![
|
||||
sse(vec![
|
||||
ev_apply_patch_custom_tool_call("request_0", add_patch),
|
||||
ev_completed("request_0"),
|
||||
]),
|
||||
sse(vec![
|
||||
ev_apply_patch_custom_tool_call("request_1", update_patch),
|
||||
ev_completed("request_1"),
|
||||
]),
|
||||
sse(vec![ev_completed("request_2")]),
|
||||
];
|
||||
let server = start_mock_server().await;
|
||||
mount_sse_sequence(&server, response_streams).await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-s")
|
||||
.arg("danger-full-access")
|
||||
.arg("foo")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let final_path = tmp_path.join("test.md");
|
||||
let contents = std::fs::read_to_string(&final_path).expect("final file should be readable");
|
||||
assert_eq!(contents, "Final text\n");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn human_output_prints_unchanged_turn_diff_once() -> anyhow::Result<()> {
|
||||
use core_test_support::skip_if_no_network;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let test = test_codex_exec();
|
||||
let run_dir = test.cwd_path();
|
||||
Command::new("git")
|
||||
.args(["init", "--quiet"])
|
||||
.current_dir(run_dir)
|
||||
.assert()
|
||||
.success();
|
||||
fs::write(run_dir.join("probe.txt"), "value=1\n")?;
|
||||
Command::new("git")
|
||||
.args(["add", "probe.txt"])
|
||||
.current_dir(run_dir)
|
||||
.assert()
|
||||
.success();
|
||||
Command::new("git")
|
||||
.args([
|
||||
"-c",
|
||||
"user.name=Reproducer",
|
||||
"-c",
|
||||
"user.email=reproducer@example.invalid",
|
||||
"commit",
|
||||
"--quiet",
|
||||
"-m",
|
||||
"baseline",
|
||||
])
|
||||
.current_dir(run_dir)
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
// Replay the reported single edit, unrelated command, and final response.
|
||||
let server = start_mock_server().await;
|
||||
let mock = mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
sse(vec![
|
||||
ev_apply_patch_custom_tool_call(
|
||||
"patch",
|
||||
"*** Begin Patch\n*** Update File: probe.txt\n@@\n-value=1\n+value=2\n*** End Patch",
|
||||
),
|
||||
ev_completed("response-1"),
|
||||
]),
|
||||
sse(vec![
|
||||
ev_exec_command_call_with_args(
|
||||
"command",
|
||||
&serde_json::json!({
|
||||
"cmd": "printf 'DIAG_CMD_OK\\n'",
|
||||
"shell": "/bin/sh",
|
||||
"login": false,
|
||||
"yield_time_ms": 10_000,
|
||||
}),
|
||||
),
|
||||
ev_completed("response-2"),
|
||||
]),
|
||||
sse(vec![
|
||||
ev_assistant_message("message", "DIAG_DONE"),
|
||||
ev_completed("response-3"),
|
||||
]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
let result = test
|
||||
.cmd_with_server(&server)
|
||||
.args([
|
||||
"--ephemeral",
|
||||
"--color",
|
||||
"never",
|
||||
"-s",
|
||||
"danger-full-access",
|
||||
"-c",
|
||||
"features.hooks=false",
|
||||
"-c",
|
||||
"features.shell_snapshot=false",
|
||||
"-c",
|
||||
"features.shell_snapshot_v2=false",
|
||||
"Replace value=1 with value=2 once, print DIAG_CMD_OK, then finish with DIAG_DONE.",
|
||||
])
|
||||
.assert()
|
||||
.success()
|
||||
.stdout("DIAG_DONE\n");
|
||||
let stderr = String::from_utf8_lossy(&result.get_output().stderr);
|
||||
assert_eq!(fs::read_to_string(run_dir.join("probe.txt"))?, "value=2\n");
|
||||
assert_eq!(mock.requests().len(), 3);
|
||||
assert_eq!(stderr.matches("patch: completed").count(), 1, "{stderr}");
|
||||
assert_eq!(
|
||||
stderr.lines().filter(|line| *line == "DIAG_CMD_OK").count(),
|
||||
1,
|
||||
"{stderr}"
|
||||
);
|
||||
assert_eq!(
|
||||
stderr
|
||||
.lines()
|
||||
.filter(|line| *line == "diff --git a/probe.txt b/probe.txt")
|
||||
.count(),
|
||||
1,
|
||||
"{stderr}"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn nested_apply_patch_alias_works_with_restricted_reads() -> anyhow::Result<()> {
|
||||
use core_test_support::skip_if_no_network;
|
||||
use core_test_support::skip_if_sandbox;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
|
||||
skip_if_no_network!(Ok(()));
|
||||
skip_if_sandbox!(Ok(()));
|
||||
#[cfg(target_os = "linux")]
|
||||
if super::sandbox::linux_sandbox_test_env().await.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
let test = test_codex_exec();
|
||||
let binary = codex_utils_cargo_bin::cargo_bin("codex-exec")?.canonicalize()?;
|
||||
let binary_dir = serde_json::to_string(binary.parent().expect("binary directory"))?;
|
||||
let codex_home = serde_json::to_string(test.home_path())?;
|
||||
fs::write(
|
||||
test.home_path().join("config.toml"),
|
||||
format!(
|
||||
r#"default_permissions = "aliases"
|
||||
approval_policy = "never"
|
||||
[features]
|
||||
shell_snapshot = false
|
||||
shell_snapshot_v2 = false
|
||||
[permissions.aliases.filesystem]
|
||||
":minimal" = "read"
|
||||
":project_roots" = "write"
|
||||
{binary_dir} = "read"
|
||||
{codex_home} = "none"
|
||||
"#
|
||||
),
|
||||
)?;
|
||||
fs::write(
|
||||
test.home_path().join("outside-workspace.txt"),
|
||||
"must remain unreadable to the script",
|
||||
)?;
|
||||
fs::write(
|
||||
test.cwd_path().join("patch.sh"),
|
||||
"if cat \"$HOME/outside-workspace.txt\" >/dev/null 2>&1; then exit 99; fi\napply_patch <<'PATCH'\n*** Begin Patch\n*** Add File: patched.txt\n+through the nested alias\n*** End Patch\nPATCH\n",
|
||||
)?;
|
||||
let server = start_mock_server().await;
|
||||
let mock = mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
sse(vec![
|
||||
ev_exec_command_call_with_args(
|
||||
"nested-patch",
|
||||
&serde_json::json!({
|
||||
"cmd": "/bin/sh patch.sh",
|
||||
"shell": "/bin/sh",
|
||||
"login": false,
|
||||
"yield_time_ms": 10_000,
|
||||
}),
|
||||
),
|
||||
ev_completed("response-1"),
|
||||
]),
|
||||
sse(vec![ev_completed("response-2")]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
let run = test.cmd_with_server(&server)
|
||||
.env("HOME", test.home_path())
|
||||
.env_remove("CODEX_API_KEY")
|
||||
.env_remove("OPENAI_API_KEY")
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-c")
|
||||
.arg("default_permissions=\"aliases\"")
|
||||
.arg("-c")
|
||||
.arg("approvals_reviewer=\"user\"")
|
||||
.arg("-c")
|
||||
.arg("model_provider=\"test\"")
|
||||
.arg("-c")
|
||||
.arg(format!(
|
||||
"model_providers.test={{name=\"test\",base_url={:?},wire_api=\"responses\",requires_openai_auth=false,supports_websockets=false}}",
|
||||
format!("{}/v1", server.uri())
|
||||
))
|
||||
.arg("run the patch script")
|
||||
.assert()
|
||||
.success();
|
||||
let output = mock
|
||||
.function_call_output_text("nested-patch")
|
||||
.expect("tool output");
|
||||
assert!(
|
||||
output.contains("Process exited with code 0"),
|
||||
"{output}\n{}",
|
||||
String::from_utf8_lossy(&run.get_output().stderr)
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_to_string(test.cwd_path().join("patched.txt"))?,
|
||||
"through the nested alias\n"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn test_apply_patch_freeform_tool() -> anyhow::Result<()> {
|
||||
use core_test_support::skip_if_no_network;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let test = test_codex_exec();
|
||||
let freeform_add_patch = r#"*** Begin Patch
|
||||
*** Add File: app.py
|
||||
+class BaseClass:
|
||||
+ def method():
|
||||
+ return False
|
||||
*** End Patch"#;
|
||||
let freeform_update_patch = r#"*** Begin Patch
|
||||
*** Update File: app.py
|
||||
@@ def method():
|
||||
- return False
|
||||
+
|
||||
+ return True
|
||||
*** End Patch"#;
|
||||
let response_streams = vec![
|
||||
sse(vec![
|
||||
ev_apply_patch_custom_tool_call("request_0", freeform_add_patch),
|
||||
ev_completed("request_0"),
|
||||
]),
|
||||
sse(vec![
|
||||
ev_apply_patch_custom_tool_call("request_1", freeform_update_patch),
|
||||
ev_completed("request_1"),
|
||||
]),
|
||||
sse(vec![ev_completed("request_2")]),
|
||||
];
|
||||
let server = start_mock_server().await;
|
||||
mount_sse_sequence(&server, response_streams).await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-s")
|
||||
.arg("danger-full-access")
|
||||
.arg("foo")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
// Verify final file contents
|
||||
let final_path = test.cwd_path().join("app.py");
|
||||
let contents = std::fs::read_to_string(&final_path).expect("final file should be readable");
|
||||
assert_eq!(
|
||||
contents,
|
||||
include_str!("../fixtures/apply_patch_freeform_final.txt")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn shutdown_flushes_completed_turn_and_file_diff() -> anyhow::Result<()> {
|
||||
use codex_login::AuthDotJson;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use codex_login::TokenData;
|
||||
use codex_login::save_auth;
|
||||
use codex_login::token_data::IdTokenInfo;
|
||||
use codex_protocol::auth::AuthMode;
|
||||
use core_test_support::skip_if_no_network;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use wiremock::Mock;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let test = test_codex_exec();
|
||||
let run_dir = test.cwd_path();
|
||||
assert!(
|
||||
std::process::Command::new("git")
|
||||
.args(["init", "--quiet"])
|
||||
.current_dir(run_dir)
|
||||
.status()
|
||||
.context("initialize test git repository")?
|
||||
.success()
|
||||
);
|
||||
assert!(
|
||||
std::process::Command::new("git")
|
||||
.args([
|
||||
"remote",
|
||||
"add",
|
||||
"origin",
|
||||
"https://github.com/test-org/turn-profile-test.git",
|
||||
])
|
||||
.current_dir(run_dir)
|
||||
.status()
|
||||
.context("add test git remote")?
|
||||
.success()
|
||||
);
|
||||
save_auth(
|
||||
test.home_path(),
|
||||
&AuthDotJson {
|
||||
auth_mode: Some(AuthMode::Chatgpt),
|
||||
openai_api_key: None,
|
||||
tokens: Some(TokenData {
|
||||
id_token: IdTokenInfo {
|
||||
raw_jwt: "header.eyJhbGciOiJub25lIn0.eyJzdWIiOiJ1c2VyLTEyMyJ9.".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
access_token: "test-access-token".to_string(),
|
||||
refresh_token: "test-refresh-token".to_string(),
|
||||
oauth_provenance: None,
|
||||
login_owner_id: None,
|
||||
account_id: None,
|
||||
}),
|
||||
last_refresh: None,
|
||||
agent_identity: None,
|
||||
personal_access_token: None,
|
||||
bedrock_api_key: None,
|
||||
bedrock_access_keys: None,
|
||||
},
|
||||
codex_login::AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)?;
|
||||
|
||||
let server = start_mock_server().await;
|
||||
let deliveries = Arc::new(AtomicUsize::new(0));
|
||||
let completed_deliveries = Arc::clone(&deliveries);
|
||||
Mock::given(method("POST"))
|
||||
.and(|request: &wiremock::Request| request.url.path().ends_with("events"))
|
||||
.respond_with(move |_request: &wiremock::Request| {
|
||||
// A request is counted only once its delayed handler has completed.
|
||||
std::thread::sleep(Duration::from_millis(750));
|
||||
completed_deliveries.fetch_add(1, Ordering::Release);
|
||||
ResponseTemplate::new(200)
|
||||
})
|
||||
.expect(3..)
|
||||
.mount(&server)
|
||||
.await;
|
||||
mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
sse(vec![
|
||||
ev_apply_patch_custom_tool_call(
|
||||
"request_0",
|
||||
"*** Begin Patch\n*** Add File: flushed.md\n+persist this line\n*** End Patch",
|
||||
),
|
||||
ev_completed("request_0"),
|
||||
]),
|
||||
sse(vec![ev_completed("request_1")]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.env_remove("CODEX_API_KEY")
|
||||
.env_remove("CODEX_ANALYTICS_EVENTS_CAPTURE_FILE")
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-s")
|
||||
.arg("danger-full-access")
|
||||
.arg("-c")
|
||||
.arg("model_provider=\"test\"")
|
||||
.arg("-c")
|
||||
.arg(format!(
|
||||
"model_providers.test={{name=\"test\",base_url={:?},wire_api=\"responses\",requires_openai_auth=false,supports_websockets=false}}",
|
||||
format!("{}/v1", server.uri())
|
||||
))
|
||||
.arg("-c")
|
||||
.arg("analytics.enabled=true")
|
||||
.arg("-c")
|
||||
.arg(format!("chatgpt_base_url={}", server.uri()))
|
||||
.arg("write the file")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let persisted = std::fs::read_to_string(run_dir.join("flushed.md"))
|
||||
.context("read file written by apply_patch")?;
|
||||
assert_eq!(persisted, "persist this line\n");
|
||||
|
||||
let requests = server
|
||||
.received_requests()
|
||||
.await
|
||||
.context("read analytics requests")?;
|
||||
let request_paths = requests
|
||||
.iter()
|
||||
.map(|request| request.url.path().to_string())
|
||||
.collect::<Vec<_>>();
|
||||
let event_types = requests
|
||||
.iter()
|
||||
.filter(|request| request.url.path().ends_with("events"))
|
||||
.flat_map(|request| {
|
||||
serde_json::from_slice::<serde_json::Value>(&request.body)
|
||||
.ok()
|
||||
.and_then(|body| {
|
||||
body.get("events")
|
||||
.and_then(serde_json::Value::as_array)
|
||||
.cloned()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter_map(|event| event["event_type"].as_str().map(str::to_owned))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert!(
|
||||
deliveries.load(Ordering::Acquire) >= 3,
|
||||
"the runtime exited before the delayed analytics deliveries completed (completed={}, events={event_types:?}, paths={request_paths:?})",
|
||||
deliveries.load(Ordering::Acquire)
|
||||
);
|
||||
assert!(
|
||||
event_types.iter().any(|event| event == "codex_turn_event"),
|
||||
"no completed event was delivered; request paths: {request_paths:?}"
|
||||
);
|
||||
assert!(
|
||||
event_types
|
||||
.iter()
|
||||
.any(|event| event == "codex_accepted_line_fingerprints"),
|
||||
"no accepted-line event was delivered; request paths: {request_paths:?}"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
78
codex-rs/exec/tests/suite/approval_policy.rs
Normal file
78
codex-rs/exec/tests/suite/approval_policy.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
#![cfg(not(target_os = "windows"))]
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
|
||||
async fn run_exec_with_config(config_toml: &str, extra_args: &[&str]) -> anyhow::Result<String> {
|
||||
let test = test_codex_exec();
|
||||
std::fs::write(test.home_path().join("config.toml"), config_toml)?;
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("response_1"),
|
||||
responses::ev_assistant_message("response_1", "done"),
|
||||
responses::ev_completed("response_1"),
|
||||
]);
|
||||
responses::mount_sse_once(&server, body).await;
|
||||
|
||||
let mut cmd = test.cmd_with_server(&server);
|
||||
let output = cmd
|
||||
.arg("--skip-git-repo-check")
|
||||
.args(extra_args)
|
||||
.arg("check approval mode")
|
||||
.output()?;
|
||||
|
||||
assert!(output.status.success(), "exec run failed: {output:?}");
|
||||
|
||||
Ok(String::from_utf8(output.stderr)?)
|
||||
}
|
||||
|
||||
async fn run_exec_with_auto_review_config(extra_args: &[&str]) -> anyhow::Result<String> {
|
||||
run_exec_with_config(
|
||||
r#"
|
||||
approval_policy = "on-request"
|
||||
approvals_reviewer = "auto_review"
|
||||
"#,
|
||||
extra_args,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_preserves_on_request_for_auto_review_config() -> anyhow::Result<()> {
|
||||
let stderr = run_exec_with_auto_review_config(&[]).await?;
|
||||
assert!(
|
||||
stderr.contains("approval: on-request"),
|
||||
"stderr missing preserved auto-review approval mode: {stderr}"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_approve_for_me_flag_sets_approval_mode_and_sandbox() -> anyhow::Result<()> {
|
||||
let stderr = run_exec_with_config("", &["--approve-for-me"]).await?;
|
||||
assert!(
|
||||
stderr.contains("approval: on-request"),
|
||||
"stderr missing --approve-for-me approval mode: {stderr}"
|
||||
);
|
||||
assert!(
|
||||
stderr.contains("sandbox: workspace-write"),
|
||||
"stderr missing --approve-for-me sandbox mode: {stderr}"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_bypass_preserves_never_for_auto_review_config() -> anyhow::Result<()> {
|
||||
let stderr =
|
||||
run_exec_with_auto_review_config(&["--dangerously-bypass-approvals-and-sandbox"]).await?;
|
||||
assert!(
|
||||
stderr.contains("approval: never"),
|
||||
"stderr missing bypass approval mode: {stderr}"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
195
codex-rs/exec/tests/suite/auth_env.rs
Normal file
195
codex-rs/exec/tests/suite/auth_env.rs
Normal file
@@ -0,0 +1,195 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use core_test_support::responses::ev_completed;
|
||||
use core_test_support::responses::mount_sse_once_match;
|
||||
use core_test_support::responses::sse;
|
||||
use core_test_support::responses::start_mock_server;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use serde_json::json;
|
||||
use wiremock::Mock;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_uses_codex_api_key_env_var() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let server = start_mock_server().await;
|
||||
let repo_root = codex_utils_cargo_bin::repo_root()?;
|
||||
|
||||
mount_sse_once_match(
|
||||
&server,
|
||||
header("Authorization", "Bearer dummy"),
|
||||
sse(vec![ev_completed("request_0")]),
|
||||
)
|
||||
.await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(&repo_root)
|
||||
.arg("echo testing codex api key")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_api_key_cannot_discard_stored_workspace_network_policy() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let policy_server = start_mock_server().await;
|
||||
let inference_server = start_mock_server().await;
|
||||
let token = concat!(
|
||||
"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.",
|
||||
"eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF9wbGFuX3R5cGUiOiJlbnRlcnByaXNlIiwiY2hhdGdwdF9hY2NvdW50X2lkIjoid29ya3NwYWNlIn19.",
|
||||
"c2lnbmF0dXJl",
|
||||
);
|
||||
std::fs::write(
|
||||
test.home_path().join("auth.json"),
|
||||
serde_json::to_vec(&json!({
|
||||
"auth_mode": "chatgpt",
|
||||
"tokens": {"id_token": token, "access_token": "workspace-token",
|
||||
"refresh_token": "refresh-token", "account_id": "workspace"},
|
||||
"last_refresh": "2099-01-01T00:00:00Z",
|
||||
}))?,
|
||||
)?;
|
||||
std::fs::write(
|
||||
test.home_path().join("config.toml"),
|
||||
format!(
|
||||
"chatgpt_base_url = '{}/backend-api/'\ncli_auth_credentials_store = 'file'\n",
|
||||
policy_server.uri()
|
||||
),
|
||||
)?;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/wham/config/bundle"))
|
||||
.and(header("authorization", "Bearer workspace-token"))
|
||||
.and(header("chatgpt-account-id", "workspace"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"requirements_toml": {"enterprise_managed": [{
|
||||
"id": "workspace-network", "name": "Workspace network",
|
||||
"contents": "[application.network]\nenabled = true",
|
||||
}]},
|
||||
})))
|
||||
.expect(1..)
|
||||
.mount(&policy_server)
|
||||
.await;
|
||||
let inference = mount_sse_once_match(
|
||||
&inference_server,
|
||||
header("Authorization", "Bearer dummy"),
|
||||
sse(vec![ev_completed("unexpected-request")]),
|
||||
)
|
||||
.await;
|
||||
|
||||
test.cmd_with_server(&inference_server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("echo testing workspace network policy")
|
||||
.assert()
|
||||
.failure();
|
||||
|
||||
assert!(
|
||||
inference.requests().is_empty(),
|
||||
"an environment API key sent model traffic despite workspace policy"
|
||||
);
|
||||
policy_server.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_bootstrap_rejects_redirected_oauth_and_cloud_policy() -> anyhow::Result<()> {
|
||||
for redirect_oauth in [true, false] {
|
||||
let test = test_codex_exec();
|
||||
let origin = start_mock_server().await;
|
||||
let destination = start_mock_server().await;
|
||||
let inference = start_mock_server().await;
|
||||
let token = concat!(
|
||||
"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.",
|
||||
"eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF9wbGFuX3R5cGUiOiJlbnRlcnByaXNlIiwiY2hhdGdwdF9hY2NvdW50X2lkIjoid29ya3NwYWNlIn19.",
|
||||
"c2lnbmF0dXJl",
|
||||
);
|
||||
let last_refresh = if redirect_oauth {
|
||||
"2000-01-01T00:00:00Z"
|
||||
} else {
|
||||
"2099-01-01T00:00:00Z"
|
||||
};
|
||||
std::fs::write(
|
||||
test.home_path().join("auth.json"),
|
||||
serde_json::to_vec(&json!({
|
||||
"auth_mode": "chatgpt",
|
||||
"tokens": {"id_token": token, "access_token": "workspace-token",
|
||||
"refresh_token": "refresh-token", "account_id": "workspace"},
|
||||
"last_refresh": last_refresh,
|
||||
}))?,
|
||||
)?;
|
||||
std::fs::write(
|
||||
test.home_path().join("config.toml"),
|
||||
format!(
|
||||
"chatgpt_base_url = '{}/backend-api/'\ncli_auth_credentials_store = 'file'\n",
|
||||
origin.uri()
|
||||
),
|
||||
)?;
|
||||
let cloud_response = if redirect_oauth {
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/oauth/token"))
|
||||
.and(wiremock::matchers::body_string_contains("refresh-token"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(307)
|
||||
.insert_header("location", format!("{}/stolen", destination.uri())),
|
||||
)
|
||||
.expect(1..)
|
||||
.mount(&origin)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/stolen"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"id_token": token, "access_token": "replacement", "refresh_token": "replacement",
|
||||
})))
|
||||
.mount(&destination)
|
||||
.await;
|
||||
ResponseTemplate::new(200).set_body_json(json!({}))
|
||||
} else {
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/policy"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"requirements_toml": {"enterprise_managed": [{
|
||||
"id": "redirected", "name": "Redirected policy",
|
||||
"contents": "[application.network.domains]\n'foreign.example' = 'allow'",
|
||||
}]},
|
||||
})))
|
||||
.mount(&destination)
|
||||
.await;
|
||||
ResponseTemplate::new(308)
|
||||
.insert_header("location", format!("{}/policy", destination.uri()))
|
||||
};
|
||||
let cloud = Mock::given(method("GET"))
|
||||
.and(path("/backend-api/wham/config/bundle"))
|
||||
.respond_with(cloud_response);
|
||||
if redirect_oauth {
|
||||
cloud.mount(&origin).await;
|
||||
} else {
|
||||
cloud.expect(1..).mount(&origin).await;
|
||||
}
|
||||
mount_sse_once_match(
|
||||
&inference,
|
||||
header("Authorization", "Bearer dummy"),
|
||||
sse(vec![ev_completed("request")]),
|
||||
)
|
||||
.await;
|
||||
|
||||
let output = test
|
||||
.cmd_with_server(&inference)
|
||||
.env(
|
||||
codex_login::REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR,
|
||||
format!("{}/oauth/token", origin.uri()),
|
||||
)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("exercise embedded discovery")
|
||||
.output()?;
|
||||
if !redirect_oauth {
|
||||
assert!(!output.status.success());
|
||||
}
|
||||
origin.verify().await;
|
||||
assert!(destination.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
225
codex-rs/exec/tests/suite/completion_backfill_tests.rs
Normal file
225
codex-rs/exec/tests/suite/completion_backfill_tests.rs
Normal file
@@ -0,0 +1,225 @@
|
||||
use core_test_support::responses;
|
||||
use core_test_support::skip_if_no_network;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
const TRACE_REQUESTS: &str =
|
||||
"codex_app_server::message_processor=trace,codex_app_server::outgoing_message=trace";
|
||||
|
||||
const PARENT_PROMPT: &str = "spawn a child and wait for it";
|
||||
const CHILD_PROMPT: &str = "child: finish first";
|
||||
const SPAWN_CALL_ID: &str = "spawn-call";
|
||||
const WAIT_CALL_ID: &str = "wait-call";
|
||||
|
||||
fn body_contains(request: &wiremock::Request, text: &str) -> bool {
|
||||
std::str::from_utf8(&request.body).is_ok_and(|body| body.contains(text))
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn ignores_unrelated_turn_completion_before_backfilling_primary_turn() -> anyhow::Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let spawn_args = json!({
|
||||
"message": CHILD_PROMPT,
|
||||
"task_name": "worker",
|
||||
"fork_turns": "none",
|
||||
})
|
||||
.to_string();
|
||||
let _parent_turn = responses::mount_sse_once_match(
|
||||
&server,
|
||||
|request: &wiremock::Request| body_contains(request, PARENT_PROMPT),
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("resp-parent-1"),
|
||||
responses::ev_function_call_with_namespace(
|
||||
SPAWN_CALL_ID,
|
||||
"collaboration",
|
||||
"spawn_agent",
|
||||
&spawn_args,
|
||||
),
|
||||
responses::ev_completed("resp-parent-1"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let _child_turn = responses::mount_sse_once_match(
|
||||
&server,
|
||||
|request: &wiremock::Request| {
|
||||
body_contains(request, CHILD_PROMPT) && !body_contains(request, SPAWN_CALL_ID)
|
||||
},
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("resp-child"),
|
||||
responses::ev_assistant_message("msg-child", "child done"),
|
||||
responses::ev_completed("resp-child"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let _parent_wait = responses::mount_sse_once_match(
|
||||
&server,
|
||||
|request: &wiremock::Request| {
|
||||
body_contains(request, SPAWN_CALL_ID) && !body_contains(request, WAIT_CALL_ID)
|
||||
},
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("resp-parent-2"),
|
||||
responses::ev_function_call_with_namespace(
|
||||
WAIT_CALL_ID,
|
||||
"collaboration",
|
||||
"wait_agent",
|
||||
"{}",
|
||||
),
|
||||
responses::ev_completed("resp-parent-2"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let _parent_completion = responses::mount_sse_once_match(
|
||||
&server,
|
||||
|request: &wiremock::Request| body_contains(request, WAIT_CALL_ID),
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("resp-parent-3"),
|
||||
responses::ev_assistant_message("msg-parent", "parent done"),
|
||||
responses::ev_completed("resp-parent-3"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
|
||||
let test = test_codex_exec();
|
||||
let mock_provider = format!(
|
||||
"model_providers.mock_provider={{name=\"Mock provider for test\",base_url=\"{}/v1\",wire_api=\"responses\",supports_websockets=false}}",
|
||||
server.uri()
|
||||
);
|
||||
let output = test
|
||||
.cmd()
|
||||
.env("RUST_LOG", TRACE_REQUESTS)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("--json")
|
||||
.arg("-c")
|
||||
.arg(mock_provider)
|
||||
.args([
|
||||
"-c",
|
||||
"model_provider=\"mock_provider\"",
|
||||
"-c",
|
||||
"features.multi_agent=true",
|
||||
"-c",
|
||||
"features.multi_agent_v2=true",
|
||||
"-c",
|
||||
"features.enable_request_compression=false",
|
||||
])
|
||||
.arg(PARENT_PROMPT)
|
||||
.output()?;
|
||||
assert!(output.status.success(), "exec run failed: {output:?}");
|
||||
|
||||
let stdout = String::from_utf8(output.stdout)?;
|
||||
assert!(
|
||||
stdout.contains("parent done"),
|
||||
"primary completion was not processed: {stdout}"
|
||||
);
|
||||
let stderr = String::from_utf8(output.stderr)?;
|
||||
let lines = stderr.lines().collect::<Vec<_>>();
|
||||
let turn_completions = lines
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, line)| {
|
||||
line.contains("app-server event: turn/completed")
|
||||
.then_some(index)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
turn_completions.len(),
|
||||
2,
|
||||
"expected the child completion before the primary completion: {stderr}"
|
||||
);
|
||||
|
||||
let [child_completion, primary_completion] = turn_completions.as_slice() else {
|
||||
unreachable!("checked turn/completed count")
|
||||
};
|
||||
assert_eq!(
|
||||
lines[*child_completion + 1..*primary_completion]
|
||||
.iter()
|
||||
.filter(|line| line.contains("app-server typed request"))
|
||||
.count(),
|
||||
0,
|
||||
"the unrelated completion must not read history: {stderr}"
|
||||
);
|
||||
assert_eq!(
|
||||
lines[*primary_completion + 1..]
|
||||
.iter()
|
||||
.filter(|line| line.contains("app-server typed request"))
|
||||
.count(),
|
||||
2,
|
||||
"the primary completion should read its items and unsubscribe: {stderr}"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
lines
|
||||
.iter()
|
||||
.filter(|line| line.contains("app-server typed request"))
|
||||
.count(),
|
||||
5,
|
||||
"only the primary completion should issue an extra request: {stderr}"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn failed_fork_recovers_only_its_own_turn() -> anyhow::Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let test = test_codex_exec();
|
||||
let last_message = test.cwd_path().join("last-message");
|
||||
let mut events = vec![responses::ev_response_created("parent")];
|
||||
// The parent's final answer must survive recovery across multiple item pages.
|
||||
for index in 0..120 {
|
||||
events.push(responses::ev_assistant_message(
|
||||
&format!("msg-{index}"),
|
||||
"working",
|
||||
));
|
||||
}
|
||||
events.push(responses::ev_assistant_message("answer", "parent done"));
|
||||
events.push(responses::ev_completed("parent"));
|
||||
let _parent_response = responses::mount_sse_once(&server, responses::sse(events)).await;
|
||||
let parent = test
|
||||
.cmd_with_server(&server)
|
||||
.args(["--skip-git-repo-check", "--json", "--output-last-message"])
|
||||
.arg(&last_message)
|
||||
.arg("Produce a long turn")
|
||||
.assert()
|
||||
.success();
|
||||
assert_eq!(std::fs::read_to_string(last_message)?, "parent done");
|
||||
let stdout = std::str::from_utf8(&parent.get_output().stdout)?;
|
||||
let started: serde_json::Value = serde_json::from_str(stdout.lines().next().unwrap())?;
|
||||
let parent_id = started["thread_id"].as_str().expect("parent thread ID");
|
||||
|
||||
let error = wiremock::ResponseTemplate::new(400).set_body_json(json!({
|
||||
"error": {"code": "model_not_found", "message": "Unknown model", "type": "invalid_request_error"}
|
||||
}));
|
||||
let _fork_response = responses::mount_response_once(&server, error).await;
|
||||
let fork = test
|
||||
.cmd_with_server(&server)
|
||||
.env("RUST_LOG", TRACE_REQUESTS)
|
||||
.args(["--skip-git-repo-check", "--json", "fork", parent_id, "Fail"])
|
||||
.assert()
|
||||
.code(1);
|
||||
let stdout = std::str::from_utf8(&fork.get_output().stdout)?;
|
||||
let terminal: serde_json::Value = serde_json::from_str(stdout.lines().last().unwrap())?;
|
||||
assert_eq!(
|
||||
terminal,
|
||||
json!({"type": "turn.failed", "error": {"message": "Unknown model"}})
|
||||
);
|
||||
|
||||
let stderr = std::str::from_utf8(&fork.get_output().stderr)?;
|
||||
let (_, completion) = stderr
|
||||
.split_once("app-server event: turn/completed")
|
||||
.expect("fork completed");
|
||||
assert!(
|
||||
!completion.contains("app-server event: deprecationNotice"),
|
||||
"{completion}"
|
||||
);
|
||||
assert_eq!(
|
||||
completion.matches("app-server typed request").count(),
|
||||
2,
|
||||
"the failed turn needs one item page and an unsubscribe: {completion}"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
102
codex-rs/exec/tests/suite/cyber_access_program_tests.rs
Normal file
102
codex-rs/exec/tests/suite/cyber_access_program_tests.rs
Normal file
@@ -0,0 +1,102 @@
|
||||
//! Verify exec forwards Cyber selection per turn and rejects unsupported commands.
|
||||
|
||||
use core_test_support::responses;
|
||||
use core_test_support::skip_if_no_network;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn cyber_access_program_is_selected_per_turn() -> anyhow::Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let test = test_codex_exec();
|
||||
std::fs::write(
|
||||
test.home_path().join("config.toml"),
|
||||
"[features]\napi_key_cyber_access_programs = true\napi_key_model_discovery = true\n",
|
||||
)?;
|
||||
let server = responses::start_mock_server().await;
|
||||
let response_mock = responses::mount_sse_sequence(
|
||||
&server,
|
||||
(0..4)
|
||||
.map(|index| {
|
||||
responses::sse(vec![responses::ev_completed(&format!(
|
||||
"resp-cyber-{index}"
|
||||
))])
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
.await;
|
||||
|
||||
let seed = test
|
||||
.cmd_with_server(&server)
|
||||
.args([
|
||||
"--skip-git-repo-check",
|
||||
"--json",
|
||||
"--cyber-access-program",
|
||||
"daybreak_blue",
|
||||
"Respond only OK.",
|
||||
])
|
||||
.assert()
|
||||
.success();
|
||||
let events = std::str::from_utf8(&seed.get_output().stdout)?
|
||||
.lines()
|
||||
.map(serde_json::from_str::<Value>)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let thread_id = events
|
||||
.iter()
|
||||
.find(|event| event["type"] == "thread.started")
|
||||
.and_then(|event| event["thread_id"].as_str())
|
||||
.expect("new turn should emit a thread id");
|
||||
|
||||
for (command, prompt, program) in [
|
||||
("resume", "Respond only OK.", Some("daybreak_red")),
|
||||
("fork", "-", Some("standard")),
|
||||
("fork", "Respond only OK.", None),
|
||||
] {
|
||||
let mut cmd = test.cmd_with_server(&server);
|
||||
cmd.args(["--skip-git-repo-check", command, thread_id]);
|
||||
if let Some(program) = program {
|
||||
cmd.args(["--cyber-access-program", program]);
|
||||
}
|
||||
if prompt == "-" {
|
||||
cmd.write_stdin("Respond only OK.");
|
||||
}
|
||||
cmd.arg(prompt).assert().success();
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
response_mock
|
||||
.requests()
|
||||
.iter()
|
||||
.map(|request| request.body_json().get("access_programs").cloned())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
Some(json!({"cyber": "daybreak_blue"})),
|
||||
Some(json!({"cyber": "daybreak_red"})),
|
||||
Some(json!({"cyber": "standard"})),
|
||||
None,
|
||||
]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cyber_access_program_requires_a_supported_turn() {
|
||||
let test = test_codex_exec();
|
||||
for (args, message) in [
|
||||
(
|
||||
vec!["review", "--uncommitted"],
|
||||
"is not supported with `codex exec review`",
|
||||
),
|
||||
(vec!["fork", "synthetic-session"], "requires a prompt"),
|
||||
] {
|
||||
test.cmd()
|
||||
.args(["--cyber-access-program", "daybreak_blue"])
|
||||
.args(args)
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(predicates::str::contains(message));
|
||||
}
|
||||
}
|
||||
401
codex-rs/exec/tests/suite/daybreak.rs
Normal file
401
codex-rs/exec/tests/suite/daybreak.rs
Normal file
@@ -0,0 +1,401 @@
|
||||
use anyhow::Context;
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex_exec::TestCodexExecBuilder;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use predicates::prelude::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
fn started_thread(output: std::process::Output) -> anyhow::Result<String> {
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
String::from_utf8(output.stdout)?
|
||||
.lines()
|
||||
.filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
|
||||
.find(|event| event["type"] == "thread.started")
|
||||
.and_then(|event| event["thread_id"].as_str().map(str::to_owned))
|
||||
.context("exec should report its thread ID")
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_resolves_daybreak_for_api_keys_and_allows_an_off_override() -> anyhow::Result<()> {
|
||||
let (test, server) = configured_daybreak_exec().await?;
|
||||
std::fs::remove_file(test.home_path().join("auth.json"))?;
|
||||
for (args, expected) in [
|
||||
(vec![], Some("daybreak_blue")),
|
||||
(vec!["-c", "daybreak=false"], Some("standard")),
|
||||
(vec!["-m", "unlisted-model"], None),
|
||||
(
|
||||
vec![
|
||||
"-c",
|
||||
"daybreak=false",
|
||||
"-c",
|
||||
"features.api_key_cyber_access_programs=false",
|
||||
],
|
||||
None,
|
||||
),
|
||||
] {
|
||||
let response =
|
||||
responses::mount_sse_once(&server, responses::sse_completed("response")).await;
|
||||
test.cmd_with_server(&server)
|
||||
.env_remove("CODEX_ACCESS_TOKEN")
|
||||
.arg("--skip-git-repo-check")
|
||||
.args(args)
|
||||
.arg("hello")
|
||||
.assert()
|
||||
.success();
|
||||
assert_eq!(
|
||||
response.single_request().body_json().get("access_programs"),
|
||||
expected.map(|program| json!({"cyber": program})).as_ref()
|
||||
);
|
||||
}
|
||||
let response = responses::mount_sse_once(&server, responses::sse_completed("unexpected")).await;
|
||||
test.cmd_with_server(&server)
|
||||
.env_remove("CODEX_ACCESS_TOKEN")
|
||||
.args([
|
||||
"--skip-git-repo-check",
|
||||
"-c",
|
||||
"features.api_key_cyber_access_programs=false",
|
||||
"hello",
|
||||
])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(predicate::str::contains(
|
||||
"Cyber access programs are disabled for this API-key session.",
|
||||
));
|
||||
assert!(response.requests().is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_rejects_daybreak_for_non_openai_provider() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let server = responses::start_mock_server().await;
|
||||
std::fs::write(
|
||||
test.home_path().join("config.toml"),
|
||||
"daybreak = true\nfeatures.cli_daybreak = true\n",
|
||||
)?;
|
||||
let response = responses::mount_sse_once(&server, responses::sse_completed("response")).await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.env_remove("CODEX_ACCESS_TOKEN")
|
||||
.args([
|
||||
"--oss",
|
||||
"--local-provider",
|
||||
"ollama",
|
||||
"--skip-git-repo-check",
|
||||
"hello",
|
||||
])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(predicate::str::contains(
|
||||
"Daybreak requires the OpenAI model provider",
|
||||
));
|
||||
assert!(response.requests().is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_custom_provider_daybreak_uses_capability() -> anyhow::Result<()> {
|
||||
let (test, server) = configured_daybreak_exec().await?;
|
||||
std::fs::remove_file(test.home_path().join("auth.json"))?;
|
||||
let config_path = test.home_path().join("config.toml");
|
||||
let config = std::fs::read_to_string(&config_path)?;
|
||||
for capability in [None, Some(false), Some(true)] {
|
||||
let capability_config = capability
|
||||
.map(|value| format!("capabilities.cyber_access_programs = {value}\n"))
|
||||
.unwrap_or_default();
|
||||
std::fs::write(
|
||||
&config_path,
|
||||
format!(
|
||||
"{config}model_provider = 'proxy'\n[model_providers.proxy]\nname = 'Proxy'\nbase_url = '{}'\nwire_api = 'responses'\nrequires_openai_auth = true\n{capability_config}",
|
||||
server.uri()
|
||||
),
|
||||
)?;
|
||||
for (enabled, expected) in [(true, "daybreak_blue"), (false, "standard")] {
|
||||
let rejected = enabled && capability != Some(true);
|
||||
let previous_requests = responses::received_responses_requests(&server).await.len();
|
||||
let response = if rejected {
|
||||
None
|
||||
} else {
|
||||
Some(responses::mount_sse_once(&server, responses::sse_completed("response")).await)
|
||||
};
|
||||
let assertion = test
|
||||
.cmd_with_server(&server)
|
||||
.env_remove("CODEX_ACCESS_TOKEN")
|
||||
.args([
|
||||
"--skip-git-repo-check",
|
||||
"-c",
|
||||
&format!("daybreak={enabled}"),
|
||||
"hello",
|
||||
])
|
||||
.assert();
|
||||
if rejected {
|
||||
assertion.failure().stderr(predicate::str::contains(
|
||||
"Daybreak requires a model provider with Cyber access program support",
|
||||
));
|
||||
assert_eq!(
|
||||
responses::received_responses_requests(&server).await.len(),
|
||||
previous_requests
|
||||
);
|
||||
} else {
|
||||
assertion.success();
|
||||
assert_eq!(
|
||||
response
|
||||
.expect("successful turn response")
|
||||
.single_request()
|
||||
.body_json()
|
||||
.get("access_programs"),
|
||||
(capability == Some(true))
|
||||
.then(|| json!({"cyber": expected}))
|
||||
.as_ref()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn configured_daybreak_exec() -> anyhow::Result<(TestCodexExecBuilder, wiremock::MockServer)>
|
||||
{
|
||||
let test = test_codex_exec();
|
||||
let server = responses::start_mock_server().await;
|
||||
let token = concat!(
|
||||
"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.",
|
||||
"eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF9wbGFuX3R5cGUiOiJlbnRlcnByaXNlIiwiY2hhdGdwdF9hY2NvdW50X2lkIjoid29ya3NwYWNlIn19.",
|
||||
"c2lnbmF0dXJl",
|
||||
);
|
||||
std::fs::write(
|
||||
test.home_path().join("auth.json"),
|
||||
serde_json::to_vec(&json!({
|
||||
"auth_mode": "chatgpt",
|
||||
"tokens": {"id_token": token, "access_token": "test-token",
|
||||
"refresh_token": "refresh-token", "account_id": "workspace"},
|
||||
"last_refresh": "2099-01-01T00:00:00Z"
|
||||
}))?,
|
||||
)?;
|
||||
let catalog = test.home_path().join("catalog.json");
|
||||
std::fs::write(
|
||||
&catalog,
|
||||
serde_json::to_vec(&json!({"models": [{
|
||||
"slug": "gpt-test", "display_name": "Test", "base_instructions": "Test instructions", "supported_reasoning_levels": [],
|
||||
"shell_type": "disabled", "visibility": "list", "supported_in_api": true,
|
||||
"priority": 0, "support_verbosity": false,
|
||||
"truncation_policy": {"mode": "tokens", "limit": 10000},
|
||||
"experimental_supported_tools": [],
|
||||
"available_access_programs": {"cyber": ["standard", "daybreak_red", "daybreak_blue"]}
|
||||
}]}))?,
|
||||
)?;
|
||||
std::fs::write(
|
||||
test.home_path().join("config.toml"),
|
||||
format!(
|
||||
"cli_auth_credentials_store = 'file'\nchatgpt_base_url = '{}/backend-api'\nmodel_catalog_json = '{}'\nmodel = 'gpt-test'\ndaybreak = true\nfeatures.cli_daybreak = true\n",
|
||||
server.uri(),
|
||||
catalog.display()
|
||||
),
|
||||
)?;
|
||||
wiremock::Mock::given(wiremock::matchers::method("GET"))
|
||||
.and(wiremock::matchers::path("/backend-api/wham/config/bundle"))
|
||||
.respond_with(wiremock::ResponseTemplate::new(200).set_body_json(json!({
|
||||
"config_toml": {"enterprise_managed": []}
|
||||
})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
wiremock::Mock::given(wiremock::matchers::method("GET"))
|
||||
.and(wiremock::matchers::path("/backend-api/wham/accounts/check"))
|
||||
.respond_with(wiremock::ResponseTemplate::new(200).set_body_json(json!({
|
||||
"accounts": [{"id": "workspace", "workspace_backend_origin": "https://chatgpt.com",
|
||||
"account_routing_override": "NO_CONSTRAINT"}]
|
||||
})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
Ok((test, server))
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_resumes_and_forks_the_saved_daybreak_choice() -> anyhow::Result<()> {
|
||||
let (test, server) = configured_daybreak_exec().await?;
|
||||
let response = responses::mount_sse_once(&server, responses::sse_completed("started")).await;
|
||||
let output = test
|
||||
.cmd_with_server(&server)
|
||||
.env_remove("CODEX_ACCESS_TOKEN")
|
||||
.env_remove("CODEX_API_KEY")
|
||||
.env_remove("OPENAI_API_KEY")
|
||||
.args(["--skip-git-repo-check", "--json", "hello"])
|
||||
.output()?;
|
||||
let thread_id = started_thread(output)?;
|
||||
assert_eq!(
|
||||
response.single_request().body_json()["access_programs"],
|
||||
json!({"cyber": "daybreak_blue"})
|
||||
);
|
||||
|
||||
// The saved choice wins over a changed default; a CLI override affects only its invocation.
|
||||
std::fs::write(
|
||||
test.home_path().join("config.toml"),
|
||||
format!(
|
||||
"cli_auth_credentials_store = 'file'\nchatgpt_base_url = '{}/backend-api'\nmodel_catalog_json = '{}'\nmodel = 'gpt-test'\nfeatures.cli_daybreak = true\n",
|
||||
server.uri(),
|
||||
test.home_path().join("catalog.json").display()
|
||||
),
|
||||
)?;
|
||||
for (args, expected) in [
|
||||
(
|
||||
vec![
|
||||
"-c",
|
||||
"daybreak=false",
|
||||
"resume",
|
||||
thread_id.as_str(),
|
||||
"continue",
|
||||
],
|
||||
Some("standard"),
|
||||
),
|
||||
(
|
||||
vec!["resume", thread_id.as_str(), "continue"],
|
||||
Some("daybreak_blue"),
|
||||
),
|
||||
(
|
||||
vec!["fork", thread_id.as_str(), "continue"],
|
||||
Some("daybreak_blue"),
|
||||
),
|
||||
(
|
||||
vec![
|
||||
"-c",
|
||||
"features.cli_daybreak=false",
|
||||
"--ephemeral",
|
||||
"fork",
|
||||
thread_id.as_str(),
|
||||
"continue",
|
||||
],
|
||||
None,
|
||||
),
|
||||
(
|
||||
vec![
|
||||
"--ephemeral",
|
||||
"-c",
|
||||
"daybreak=false",
|
||||
"fork",
|
||||
thread_id.as_str(),
|
||||
"continue",
|
||||
],
|
||||
Some("standard"),
|
||||
),
|
||||
] {
|
||||
let response =
|
||||
responses::mount_sse_once(&server, responses::sse_completed("continued")).await;
|
||||
test.cmd_with_server(&server)
|
||||
.env_remove("CODEX_ACCESS_TOKEN")
|
||||
.env_remove("CODEX_API_KEY")
|
||||
.env_remove("OPENAI_API_KEY")
|
||||
.arg("--skip-git-repo-check")
|
||||
.args(args)
|
||||
.assert()
|
||||
.success();
|
||||
assert_eq!(
|
||||
response.single_request().body_json().get("access_programs"),
|
||||
expected.map(|program| json!({"cyber": program})).as_ref()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_explicit_cyber_program_overrides_daybreak_for_one_turn() -> anyhow::Result<()> {
|
||||
let (test, server) = configured_daybreak_exec().await?;
|
||||
let response =
|
||||
responses::mount_sse_once(&server, responses::sse_completed("explicit-program")).await;
|
||||
let output = test
|
||||
.cmd_with_server(&server)
|
||||
.env_remove("CODEX_ACCESS_TOKEN")
|
||||
.env_remove("CODEX_API_KEY")
|
||||
.env_remove("OPENAI_API_KEY")
|
||||
.args([
|
||||
"--skip-git-repo-check",
|
||||
"--json",
|
||||
"-c",
|
||||
"features.cli_daybreak=false",
|
||||
"--cyber-access-program",
|
||||
"daybreak_red",
|
||||
"hello",
|
||||
])
|
||||
.output()?;
|
||||
let thread_id = started_thread(output)?;
|
||||
assert_eq!(
|
||||
response.single_request().body_json()["access_programs"],
|
||||
json!({"cyber": "daybreak_red"})
|
||||
);
|
||||
|
||||
let response =
|
||||
responses::mount_sse_once(&server, responses::sse_completed("saved-daybreak")).await;
|
||||
test.cmd_with_server(&server)
|
||||
.env_remove("CODEX_ACCESS_TOKEN")
|
||||
.env_remove("CODEX_API_KEY")
|
||||
.env_remove("OPENAI_API_KEY")
|
||||
.args(["--skip-git-repo-check", "resume", &thread_id, "continue"])
|
||||
.assert()
|
||||
.success();
|
||||
assert_eq!(
|
||||
response.single_request().body_json()["access_programs"],
|
||||
json!({"cyber": "daybreak_blue"})
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_resume_override_does_not_change_a_standard_thread() -> anyhow::Result<()> {
|
||||
let (test, server) = configured_daybreak_exec().await?;
|
||||
let response =
|
||||
responses::mount_sse_once(&server, responses::sse_completed("started-standard")).await;
|
||||
let output = test
|
||||
.cmd_with_server(&server)
|
||||
.env_remove("CODEX_ACCESS_TOKEN")
|
||||
.env_remove("CODEX_API_KEY")
|
||||
.env_remove("OPENAI_API_KEY")
|
||||
.args([
|
||||
"--skip-git-repo-check",
|
||||
"--json",
|
||||
"-c",
|
||||
"features.cli_daybreak=false",
|
||||
"-c",
|
||||
"daybreak=false",
|
||||
"hello",
|
||||
])
|
||||
.output()?;
|
||||
let thread_id = started_thread(output)?;
|
||||
assert_eq!(
|
||||
response.single_request().body_json().get("access_programs"),
|
||||
None
|
||||
);
|
||||
for (args, expected) in [
|
||||
(
|
||||
vec![
|
||||
"-c",
|
||||
"daybreak=true",
|
||||
"resume",
|
||||
thread_id.as_str(),
|
||||
"continue",
|
||||
],
|
||||
"daybreak_blue",
|
||||
),
|
||||
(vec!["resume", thread_id.as_str(), "continue"], "standard"),
|
||||
] {
|
||||
let response =
|
||||
responses::mount_sse_once(&server, responses::sse_completed("continued-standard"))
|
||||
.await;
|
||||
test.cmd_with_server(&server)
|
||||
.env_remove("CODEX_ACCESS_TOKEN")
|
||||
.env_remove("CODEX_API_KEY")
|
||||
.env_remove("OPENAI_API_KEY")
|
||||
.arg("--skip-git-repo-check")
|
||||
.args(args)
|
||||
.assert()
|
||||
.success();
|
||||
assert_eq!(
|
||||
response.single_request().body_json()["access_programs"],
|
||||
json!({"cyber": expected})
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
67
codex-rs/exec/tests/suite/ephemeral.rs
Normal file
67
codex-rs/exec/tests/suite/ephemeral.rs
Normal file
@@ -0,0 +1,67 @@
|
||||
#![cfg(not(target_os = "windows"))]
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use core_test_support::responses;
|
||||
use core_test_support::skip_if_no_network;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use walkdir::WalkDir;
|
||||
use wiremock::MockServer;
|
||||
|
||||
fn exec_sse_response() -> String {
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("resp-ephemeral"),
|
||||
responses::ev_assistant_message("msg-ephemeral", "ephemeral response"),
|
||||
responses::ev_completed("resp-ephemeral"),
|
||||
])
|
||||
}
|
||||
|
||||
fn session_rollout_count(home_path: &std::path::Path) -> usize {
|
||||
let sessions_dir = home_path.join("sessions");
|
||||
if !sessions_dir.exists() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
WalkDir::new(sessions_dir)
|
||||
.into_iter()
|
||||
.filter_map(Result::ok)
|
||||
.filter(|entry| entry.file_type().is_file())
|
||||
.filter(|entry| entry.file_name().to_string_lossy().ends_with(".jsonl"))
|
||||
.count()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn persists_rollout_file_by_default() -> anyhow::Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let test = test_codex_exec();
|
||||
let server = MockServer::start().await;
|
||||
let _response_mock = responses::mount_sse_once(&server, exec_sse_response()).await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("default persistence behavior")
|
||||
.assert()
|
||||
.code(0);
|
||||
|
||||
assert_eq!(session_rollout_count(test.home_path()), 1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn does_not_persist_rollout_file_in_ephemeral_mode() -> anyhow::Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let test = test_codex_exec();
|
||||
let server = MockServer::start().await;
|
||||
let _response_mock = responses::mount_sse_once(&server, exec_sse_response()).await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("--ephemeral")
|
||||
.arg("ephemeral behavior")
|
||||
.assert()
|
||||
.code(0);
|
||||
|
||||
assert_eq!(session_rollout_count(test.home_path()), 0);
|
||||
Ok(())
|
||||
}
|
||||
43
codex-rs/exec/tests/suite/hooks.rs
Normal file
43
codex-rs/exec/tests/suite/hooks.rs
Normal file
@@ -0,0 +1,43 @@
|
||||
#![cfg(not(target_os = "windows"))]
|
||||
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use serde_json::json;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_hook_trust_bypass_runs_session_start_hook() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let marker_path = test.home_path().join("session-start-ran");
|
||||
let command = format!("touch {}", marker_path.display());
|
||||
std::fs::write(
|
||||
test.home_path().join("hooks.json"),
|
||||
serde_json::to_vec_pretty(&json!({
|
||||
"hooks": {
|
||||
"SessionStart": [{
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": command,
|
||||
}],
|
||||
}],
|
||||
},
|
||||
}))?,
|
||||
)?;
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("response_1"),
|
||||
responses::ev_assistant_message("response_1", "done"),
|
||||
responses::ev_completed("response_1"),
|
||||
]);
|
||||
responses::mount_sse_once(&server, body).await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("--dangerously-bypass-hook-trust")
|
||||
.arg("run the session start hook")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
assert!(marker_path.exists(), "session start hook did not run");
|
||||
Ok(())
|
||||
}
|
||||
69
codex-rs/exec/tests/suite/mcp_required_exit.rs
Normal file
69
codex-rs/exec/tests/suite/mcp_required_exit.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
use codex_core::config::set_project_trust_level;
|
||||
use codex_protocol::config_types::TrustLevel;
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use predicates::str::contains;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exits_non_zero_when_required_mcp_server_fails_to_initialize() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
|
||||
let config_toml = r#"
|
||||
[mcp_servers.required_broken]
|
||||
command = "codex-definitely-not-a-real-binary"
|
||||
required = true
|
||||
"#;
|
||||
let user_config = test.home_path().join("config.toml");
|
||||
fs::write(&user_config, config_toml)?;
|
||||
let project = test.cwd_path().join("repo");
|
||||
let cwd = project.join("subdir");
|
||||
fs::create_dir_all(&cwd)?;
|
||||
fs::create_dir(project.join(".codex"))?;
|
||||
fs::create_dir(project.join(".git"))?;
|
||||
fs::write(project.join(".git/HEAD"), "ref: refs/heads/main\n")?;
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
responses::mount_sse_once(&server, responses::sse_completed("resp_1")).await;
|
||||
let run = |args: &[&str]| {
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--cd")
|
||||
.arg(&cwd)
|
||||
.args(["--ephemeral", "--experimental-json"])
|
||||
.args(args)
|
||||
.arg("hello")
|
||||
.assert()
|
||||
};
|
||||
let expect_mcp_failure = |args: &[&str]| {
|
||||
run(args).code(1).stderr(contains(
|
||||
"required MCP servers failed to initialize: required_broken",
|
||||
));
|
||||
};
|
||||
|
||||
expect_mcp_failure(&[]);
|
||||
// The same server in project config requires explicit consent, even with write access.
|
||||
fs::rename(&user_config, project.join(".codex/config.toml"))?;
|
||||
let first = run(&["--sandbox", "workspace-write"]).success();
|
||||
let stderr = std::str::from_utf8(&first.get_output().stderr)?;
|
||||
let warning = stderr
|
||||
.lines()
|
||||
.find(|line| line.contains("codex exec --trust"))
|
||||
.expect("project trust warning");
|
||||
insta::assert_snapshot!(warning, @"warning: Untrusted project-local configuration is disabled. Run `codex exec --trust` to allow project configuration and MCP servers for this and future chats in the project, including MCP commands outside the sandbox. Explicitly untrusted projects must have their trust setting updated first.");
|
||||
expect_mcp_failure(&["--sandbox", "read-only", "--trust"]);
|
||||
expect_mcp_failure(&[]);
|
||||
|
||||
set_project_trust_level(test.home_path(), &project, TrustLevel::Untrusted)?;
|
||||
let refusal = fs::read_to_string(&user_config)?;
|
||||
run(&["--trust"])
|
||||
.failure()
|
||||
.stderr(contains("is marked as untrusted"));
|
||||
run(&["--ignore-user-config", "resume", "--last", "--trust"])
|
||||
.failure()
|
||||
.stderr(contains(
|
||||
"--trust cannot be combined with --ignore-user-config",
|
||||
));
|
||||
assert_eq!(fs::read_to_string(user_config)?, refusal);
|
||||
Ok(())
|
||||
}
|
||||
24
codex-rs/exec/tests/suite/mod.rs
Normal file
24
codex-rs/exec/tests/suite/mod.rs
Normal file
@@ -0,0 +1,24 @@
|
||||
// Aggregates all former standalone integration tests as modules.
|
||||
mod add_dir;
|
||||
mod agents_md;
|
||||
mod apply_patch;
|
||||
mod approval_policy;
|
||||
mod auth_env;
|
||||
#[path = "completion_backfill_tests.rs"]
|
||||
mod completion_backfill;
|
||||
#[path = "cyber_access_program_tests.rs"]
|
||||
mod cyber_access_program;
|
||||
mod daybreak;
|
||||
mod ephemeral;
|
||||
mod hooks;
|
||||
mod mcp_required_exit;
|
||||
mod originator;
|
||||
mod output_last_message;
|
||||
mod output_schema;
|
||||
mod prompt_stdin;
|
||||
mod resume;
|
||||
mod sandbox;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod seatbelt;
|
||||
mod server_error_exit;
|
||||
mod worktree;
|
||||
54
codex-rs/exec/tests/suite/originator.rs
Normal file
54
codex-rs/exec/tests/suite/originator.rs
Normal file
@@ -0,0 +1,54 @@
|
||||
#![cfg(not(target_os = "windows"))]
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use codex_login::default_client::CODEX_INTERNAL_ORIGINATOR_OVERRIDE_ENV_VAR;
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use wiremock::matchers::header;
|
||||
|
||||
/// Verify that when the server reports an error, `codex-exec` exits with a
|
||||
/// non-zero status code so automation can detect failures.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn send_codex_exec_originator() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("response_1"),
|
||||
responses::ev_assistant_message("response_1", "Hello, world!"),
|
||||
responses::ev_completed("response_1"),
|
||||
]);
|
||||
responses::mount_sse_once_match(&server, header("Originator", "codex_exec"), body).await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.env_remove(CODEX_INTERNAL_ORIGINATOR_OVERRIDE_ENV_VAR)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("tell me something")
|
||||
.assert()
|
||||
.code(0);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn supports_originator_override() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("response_1"),
|
||||
responses::ev_assistant_message("response_1", "Hello, world!"),
|
||||
responses::ev_completed("response_1"),
|
||||
]);
|
||||
responses::mount_sse_once_match(&server, header("Originator", "codex_exec_override"), body)
|
||||
.await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.env("CODEX_INTERNAL_ORIGINATOR_OVERRIDE", "codex_exec_override")
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("tell me something")
|
||||
.assert()
|
||||
.code(0);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
110
codex-rs/exec/tests/suite/output_last_message.rs
Normal file
110
codex-rs/exec/tests/suite/output_last_message.rs
Normal file
@@ -0,0 +1,110 @@
|
||||
#![cfg(unix)]
|
||||
|
||||
//! Exercise the CLI output path used by automation with a synthetic model response.
|
||||
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn human_output_to_redirected_stdout_prints_one_answer() -> anyhow::Result<()> {
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
let test = test_codex_exec();
|
||||
let server = responses::start_mock_server().await;
|
||||
let command = test.cmd_with_server(&server);
|
||||
let saved = test.cwd_path().join("stdout");
|
||||
for alias in ["/dev/stdout", "/dev/fd/1", "/proc/self/fd/1"] {
|
||||
responses::mount_sse_once(
|
||||
&server,
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("r"),
|
||||
responses::ev_assistant_message("m", "done"),
|
||||
responses::ev_completed("r"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let output = std::process::Command::new(command.get_program())
|
||||
.args(command.get_args())
|
||||
.envs(command.get_envs().filter_map(|(k, v)| v.map(|v| (k, v))))
|
||||
.current_dir(test.cwd_path())
|
||||
.args(["--skip-git-repo-check", "-o", alias, "reply"])
|
||||
.stdout(std::fs::File::create(&saved)?)
|
||||
.output()?;
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
assert_eq!(std::fs::read(&saved)?, b"done\n", "{alias}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn sandbox_link_cannot_redirect_this_or_the_next_invocation() -> anyhow::Result<()> {
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
core_test_support::skip_if_sandbox!(Ok(()));
|
||||
#[cfg(target_os = "linux")]
|
||||
if super::sandbox::linux_sandbox_test_env().await.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
for mode in [None, Some("--json")] {
|
||||
let test = test_codex_exec();
|
||||
let outside = tempfile::tempdir()?;
|
||||
let target = outside.path().join("victim.txt");
|
||||
let output = test.cwd_path().join("codex-output.md");
|
||||
std::fs::write(&target, "original victim")?;
|
||||
std::fs::write(&output, "original output")?;
|
||||
let mut original = std::fs::File::open(&output)?;
|
||||
let quoted_target = format!("'{}'", target.display().to_string().replace('\'', "'\\''"));
|
||||
let attack = format!(
|
||||
"if (printf forbidden > {quoted_target}) 2>/dev/null; then exit 1; fi; ln -sfn -- {quoted_target} codex-output.md"
|
||||
);
|
||||
let server = responses::start_mock_server().await;
|
||||
let args = serde_json::json!({"cmd": attack, "shell": "/bin/sh", "login": false, "yield_time_ms": 10_000});
|
||||
responses::mount_function_call_agent_response(
|
||||
&server,
|
||||
"plant-output",
|
||||
&args.to_string(),
|
||||
"exec_command",
|
||||
)
|
||||
.await;
|
||||
let command = || {
|
||||
let mut cmd = test.cmd_with_server(&server);
|
||||
cmd.args(["--skip-git-repo-check", "--output-last-message"])
|
||||
.arg(&output);
|
||||
cmd.args(mode);
|
||||
cmd
|
||||
};
|
||||
let mut cmd = command();
|
||||
cmd.args([
|
||||
"--sandbox",
|
||||
"workspace-write",
|
||||
"-c",
|
||||
"approval_policy='never'",
|
||||
"-c",
|
||||
"sandbox_workspace_write.exclude_slash_tmp=true",
|
||||
"-c",
|
||||
"sandbox_workspace_write.exclude_tmpdir_env_var=true",
|
||||
]);
|
||||
cmd.arg("write a response")
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(predicates::str::contains(
|
||||
"Failed to write last message file",
|
||||
));
|
||||
let mut saved = String::new();
|
||||
std::io::Read::read_to_string(&mut original, &mut saved)?;
|
||||
assert_eq!(saved, "original output");
|
||||
assert_eq!(std::fs::read_to_string(&target)?, "original victim");
|
||||
assert_eq!(std::fs::read_link(&output)?, target);
|
||||
|
||||
// The link left by the first invocation must not gain authority on the next one.
|
||||
command()
|
||||
.arg("write another response")
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(predicates::str::contains(
|
||||
"Failed to open last message file",
|
||||
));
|
||||
|
||||
assert_eq!(std::fs::read_to_string(&target)?, "original victim");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
62
codex-rs/exec/tests/suite/output_schema.rs
Normal file
62
codex-rs/exec/tests/suite/output_schema.rs
Normal file
@@ -0,0 +1,62 @@
|
||||
#![cfg(not(target_os = "windows"))]
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use serde_json::Value;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_includes_output_schema_in_request() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
|
||||
let schema_contents = serde_json::json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"answer": { "type": "string" }
|
||||
},
|
||||
"required": ["answer"],
|
||||
"additionalProperties": false
|
||||
});
|
||||
let schema_path = test.cwd_path().join("schema.json");
|
||||
std::fs::write(&schema_path, serde_json::to_vec_pretty(&schema_contents)?)?;
|
||||
let expected_schema: Value = schema_contents;
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("resp1"),
|
||||
responses::ev_assistant_message("m1", "fixture hello"),
|
||||
responses::ev_completed("resp1"),
|
||||
]);
|
||||
let response_mock = responses::mount_sse_once(&server, body).await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
// keep using -C in the test to exercise the flag as well
|
||||
.arg("-C")
|
||||
.arg(test.cwd_path())
|
||||
.arg("--output-schema")
|
||||
.arg(&schema_path)
|
||||
.arg("-m")
|
||||
.arg("gpt-5.1")
|
||||
.arg("tell me a joke")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let request = response_mock.single_request();
|
||||
let payload: Value = request.body_json();
|
||||
let text = payload.get("text").expect("request missing text field");
|
||||
let format = text
|
||||
.get("format")
|
||||
.expect("request missing text.format field");
|
||||
assert_eq!(
|
||||
format,
|
||||
&serde_json::json!({
|
||||
"name": "codex_output_schema",
|
||||
"type": "json_schema",
|
||||
"strict": true,
|
||||
"schema": expected_schema,
|
||||
})
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
171
codex-rs/exec/tests/suite/prompt_stdin.rs
Normal file
171
codex-rs/exec/tests/suite/prompt_stdin.rs
Normal file
@@ -0,0 +1,171 @@
|
||||
#![cfg(not(target_os = "windows"))]
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use predicates::str::contains;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_appends_piped_stdin_to_prompt_argument() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("resp1"),
|
||||
responses::ev_assistant_message("m1", "fixture hello"),
|
||||
responses::ev_completed("resp1"),
|
||||
]);
|
||||
let response_mock = responses::mount_sse_once(&server, body).await;
|
||||
|
||||
// echo "my output" | codex exec --skip-git-repo-check -C <cwd> -m gpt-5.1 "Summarize this concisely"
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(test.cwd_path())
|
||||
.arg("-m")
|
||||
.arg("gpt-5.1")
|
||||
.arg("Summarize this concisely")
|
||||
.write_stdin("my output\n")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let request = response_mock.single_request();
|
||||
assert!(
|
||||
request.has_message_with_input_texts("user", |texts| {
|
||||
texts == ["Summarize this concisely\n\n<stdin>\nmy output\n</stdin>".to_string()]
|
||||
}),
|
||||
"request should include a user message with the prompt plus piped stdin context"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_ignores_empty_piped_stdin_when_prompt_argument_is_present() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("resp1"),
|
||||
responses::ev_assistant_message("m1", "fixture hello"),
|
||||
responses::ev_completed("resp1"),
|
||||
]);
|
||||
let response_mock = responses::mount_sse_once(&server, body).await;
|
||||
|
||||
// printf "" | codex exec --skip-git-repo-check -C <cwd> -m gpt-5.1 "Summarize this concisely"
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(test.cwd_path())
|
||||
.arg("-m")
|
||||
.arg("gpt-5.1")
|
||||
.arg("Summarize this concisely")
|
||||
.write_stdin("")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let request = response_mock.single_request();
|
||||
assert!(
|
||||
request.has_message_with_input_texts("user", |texts| texts
|
||||
== ["Summarize this concisely".to_string()]),
|
||||
"request should preserve the prompt when stdin is empty"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_dash_prompt_reads_stdin_as_the_prompt() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("resp1"),
|
||||
responses::ev_assistant_message("m1", "fixture hello"),
|
||||
responses::ev_completed("resp1"),
|
||||
]);
|
||||
let response_mock = responses::mount_sse_once(&server, body).await;
|
||||
|
||||
// echo "prompt from stdin" | codex exec --skip-git-repo-check -C <cwd> -m gpt-5.1 -
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(test.cwd_path())
|
||||
.arg("-m")
|
||||
.arg("gpt-5.1")
|
||||
.arg("-")
|
||||
.write_stdin("prompt from stdin\n")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let request = response_mock.single_request();
|
||||
assert!(
|
||||
request.has_message_with_input_texts("user", |texts| {
|
||||
texts == ["prompt from stdin\n".to_string()]
|
||||
}),
|
||||
"dash prompt should preserve the existing forced-stdin behavior"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_without_prompt_argument_reads_piped_stdin_as_the_prompt() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("resp1"),
|
||||
responses::ev_assistant_message("m1", "fixture hello"),
|
||||
responses::ev_completed("resp1"),
|
||||
]);
|
||||
let response_mock = responses::mount_sse_once(&server, body).await;
|
||||
|
||||
// echo "prompt from stdin" | codex exec --skip-git-repo-check -C <cwd> -m gpt-5.1
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(test.cwd_path())
|
||||
.arg("-m")
|
||||
.arg("gpt-5.1")
|
||||
.write_stdin("prompt from stdin\n")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let request = response_mock.single_request();
|
||||
assert!(
|
||||
request.has_message_with_input_texts("user", |texts| {
|
||||
texts == ["prompt from stdin\n".to_string()]
|
||||
}),
|
||||
"missing prompt argument should preserve the existing piped-stdin prompt behavior"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_without_prompt_argument_rejects_empty_piped_stdin() {
|
||||
let test = test_codex_exec();
|
||||
|
||||
// printf "" | codex exec --skip-git-repo-check -C <cwd>
|
||||
test.cmd()
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(test.cwd_path())
|
||||
.write_stdin("")
|
||||
.assert()
|
||||
.code(1)
|
||||
.stderr(contains("No prompt provided via stdin."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_dash_prompt_rejects_empty_piped_stdin() {
|
||||
let test = test_codex_exec();
|
||||
|
||||
// printf "" | codex exec --skip-git-repo-check -C <cwd> -
|
||||
test.cmd()
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("-C")
|
||||
.arg(test.cwd_path())
|
||||
.arg("-")
|
||||
.write_stdin("")
|
||||
.assert()
|
||||
.code(1)
|
||||
.stderr(contains("No prompt provided via stdin."));
|
||||
}
|
||||
1066
codex-rs/exec/tests/suite/resume.rs
Normal file
1066
codex-rs/exec/tests/suite/resume.rs
Normal file
File diff suppressed because it is too large
Load Diff
553
codex-rs/exec/tests/suite/sandbox.rs
Normal file
553
codex-rs/exec/tests/suite/sandbox.rs
Normal file
@@ -0,0 +1,553 @@
|
||||
#![cfg(unix)]
|
||||
use codex_core::spawn::StdioPolicy;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::permissions::NetworkSandboxPolicy;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_absolute_path::test_support::PathBufExt;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::process::ExitStatus;
|
||||
use tokio::fs::create_dir_all;
|
||||
use tokio::process::Child;
|
||||
|
||||
pub(super) async fn spawn_command_under_sandbox(
|
||||
command: Vec<String>,
|
||||
command_cwd: AbsolutePathBuf,
|
||||
permission_profile: &PermissionProfile,
|
||||
sandbox_cwd: &AbsolutePathBuf,
|
||||
stdio_policy: StdioPolicy,
|
||||
env: HashMap<String, String>,
|
||||
) -> std::io::Result<Child> {
|
||||
use codex_core::exec::ExecCapturePolicy;
|
||||
use codex_core::exec::ExecParams;
|
||||
use codex_core::exec::build_exec_request;
|
||||
use codex_core::sandboxing::SandboxPermissions;
|
||||
use codex_protocol::config_types::WindowsSandboxLevel;
|
||||
use std::process::Stdio;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
let codex_linux_sandbox_exe = Some(
|
||||
core_test_support::find_codex_linux_sandbox_exe()
|
||||
.map_err(|err| io::Error::new(io::ErrorKind::NotFound, err))?,
|
||||
);
|
||||
#[cfg(target_os = "macos")]
|
||||
let codex_linux_sandbox_exe = None;
|
||||
let exec_request = build_exec_request(
|
||||
ExecParams {
|
||||
command,
|
||||
cwd: command_cwd,
|
||||
expiration: 1000.into(),
|
||||
capture_policy: ExecCapturePolicy::ShellTool,
|
||||
env,
|
||||
network: None,
|
||||
network_environment_id: None,
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
windows_sandbox_level: WindowsSandboxLevel::Disabled,
|
||||
justification: None,
|
||||
arg0: None,
|
||||
},
|
||||
permission_profile,
|
||||
sandbox_cwd,
|
||||
&[PathUri::from_abs_path(sandbox_cwd)],
|
||||
&codex_linux_sandbox_exe,
|
||||
/*codex_self_exe*/ &None,
|
||||
codex_protocol::sandbox::SandboxType::None,
|
||||
/*use_legacy_landlock*/ false,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| io::Error::other(err.to_string()))?;
|
||||
|
||||
let (program, args) = exec_request
|
||||
.command
|
||||
.split_first()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "command args are empty"))?;
|
||||
|
||||
let mut child = tokio::process::Command::new(program);
|
||||
if let Some(arg0) = exec_request.arg0.as_deref() {
|
||||
child.arg0(arg0);
|
||||
}
|
||||
child.args(args);
|
||||
// TODO(anp): Keep PathUri through the macOS sandbox process launch boundary.
|
||||
let native_cwd = exec_request
|
||||
.cwd
|
||||
.to_abs_path()
|
||||
.map_err(|err| io::Error::other(err.to_string()))?;
|
||||
child.current_dir(native_cwd);
|
||||
child.env_clear();
|
||||
child.envs(exec_request.env);
|
||||
|
||||
match stdio_policy {
|
||||
StdioPolicy::RedirectForShellTool => {
|
||||
child.stdin(Stdio::null());
|
||||
child.stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
}
|
||||
StdioPolicy::Inherit => {
|
||||
child
|
||||
.stdin(Stdio::inherit())
|
||||
.stdout(Stdio::inherit())
|
||||
.stderr(Stdio::inherit());
|
||||
}
|
||||
}
|
||||
|
||||
child.kill_on_drop(true).spawn()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
/// Determines whether Linux sandbox tests can run on this host.
|
||||
///
|
||||
/// These tests require an enforceable filesystem sandbox. We run a tiny command
|
||||
/// under the production Landlock path and skip when enforcement is unavailable
|
||||
/// (for example on kernels or container profiles where Landlock is not
|
||||
/// enforced).
|
||||
pub(super) async fn linux_sandbox_test_env() -> Option<HashMap<String, String>> {
|
||||
let command_cwd = AbsolutePathBuf::current_dir().ok()?;
|
||||
let sandbox_cwd = command_cwd.clone();
|
||||
let permission_profile = PermissionProfile::read_only();
|
||||
|
||||
if can_apply_linux_sandbox_policy(
|
||||
&permission_profile,
|
||||
&command_cwd,
|
||||
&sandbox_cwd,
|
||||
HashMap::new(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Some(HashMap::new());
|
||||
}
|
||||
|
||||
eprintln!("Skipping test: Landlock is not enforceable on this host.");
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
/// Returns whether a minimal command can run successfully with the requested
|
||||
/// Linux sandbox policy applied.
|
||||
///
|
||||
/// This is used as a capability probe so sandbox behavior tests only run when
|
||||
/// Landlock enforcement is actually active.
|
||||
async fn can_apply_linux_sandbox_policy(
|
||||
permission_profile: &PermissionProfile,
|
||||
command_cwd: &AbsolutePathBuf,
|
||||
sandbox_cwd: &AbsolutePathBuf,
|
||||
env: HashMap<String, String>,
|
||||
) -> bool {
|
||||
let spawn_result = spawn_command_under_sandbox(
|
||||
vec!["/usr/bin/true".to_string()],
|
||||
command_cwd.clone(),
|
||||
permission_profile,
|
||||
sandbox_cwd,
|
||||
StdioPolicy::RedirectForShellTool,
|
||||
env,
|
||||
)
|
||||
.await;
|
||||
let Ok(mut child) = spawn_result else {
|
||||
return false;
|
||||
};
|
||||
child
|
||||
.wait()
|
||||
.await
|
||||
.map(|status| status.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn python_multiprocessing_lock_works_under_sandbox() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
#[cfg(target_os = "linux")]
|
||||
let sandbox_env = match linux_sandbox_test_env().await {
|
||||
Some(env) => env,
|
||||
// Skip on Linux hosts where Landlock cannot actually be enforced.
|
||||
None => return,
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let sandbox_env = HashMap::new();
|
||||
#[cfg(target_os = "macos")]
|
||||
let writable_roots = Vec::<AbsolutePathBuf>::new();
|
||||
|
||||
// From https://man7.org/linux/man-pages/man7/sem_overview.7.html
|
||||
//
|
||||
// > On Linux, named semaphores are created in a virtual filesystem,
|
||||
// > normally mounted under /dev/shm.
|
||||
#[cfg(target_os = "linux")]
|
||||
let writable_roots: Vec<AbsolutePathBuf> = vec!["/dev/shm".try_into().unwrap()];
|
||||
|
||||
let permission_profile = PermissionProfile::workspace_write_with(
|
||||
&writable_roots,
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
/*exclude_tmpdir_env_var*/ true,
|
||||
/*exclude_slash_tmp*/ true,
|
||||
);
|
||||
|
||||
let python_code = r#"import multiprocessing
|
||||
from multiprocessing import Lock, Process
|
||||
|
||||
def f(lock):
|
||||
with lock:
|
||||
print("Lock acquired in child process")
|
||||
|
||||
if __name__ == '__main__':
|
||||
lock = Lock()
|
||||
p = Process(target=f, args=(lock,))
|
||||
p.start()
|
||||
p.join()
|
||||
"#;
|
||||
|
||||
let command_cwd = AbsolutePathBuf::current_dir().expect("should be able to get current dir");
|
||||
let sandbox_cwd = command_cwd.clone();
|
||||
let mut child = spawn_command_under_sandbox(
|
||||
vec![
|
||||
"python3".to_string(),
|
||||
"-c".to_string(),
|
||||
python_code.to_string(),
|
||||
],
|
||||
command_cwd,
|
||||
&permission_profile,
|
||||
&sandbox_cwd,
|
||||
StdioPolicy::Inherit,
|
||||
sandbox_env,
|
||||
)
|
||||
.await
|
||||
.expect("should be able to spawn python under sandbox");
|
||||
|
||||
let status = child.wait().await.expect("should wait for child process");
|
||||
assert!(status.success(), "python exited with {status:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn python_getpwuid_works_under_sandbox() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
#[cfg(target_os = "linux")]
|
||||
let sandbox_env = match linux_sandbox_test_env().await {
|
||||
Some(env) => env,
|
||||
None => return,
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let sandbox_env = HashMap::new();
|
||||
|
||||
if std::process::Command::new("python3")
|
||||
.arg("--version")
|
||||
.status()
|
||||
.is_err()
|
||||
{
|
||||
eprintln!("python3 not found in PATH, skipping test.");
|
||||
return;
|
||||
}
|
||||
|
||||
let permission_profile = PermissionProfile::read_only();
|
||||
let command_cwd = AbsolutePathBuf::current_dir().expect("should be able to get current dir");
|
||||
let sandbox_cwd = command_cwd.clone();
|
||||
|
||||
let mut child = spawn_command_under_sandbox(
|
||||
vec![
|
||||
"python3".to_string(),
|
||||
"-c".to_string(),
|
||||
"import pwd, os; print(pwd.getpwuid(os.getuid()))".to_string(),
|
||||
],
|
||||
command_cwd,
|
||||
&permission_profile,
|
||||
&sandbox_cwd,
|
||||
StdioPolicy::RedirectForShellTool,
|
||||
sandbox_env,
|
||||
)
|
||||
.await
|
||||
.expect("should be able to spawn python under sandbox");
|
||||
|
||||
let status = child
|
||||
.wait()
|
||||
.await
|
||||
.expect("should be able to wait for child process");
|
||||
assert!(status.success(), "python exited with {status:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sandbox_distinguishes_command_and_policy_cwds() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
#[cfg(target_os = "linux")]
|
||||
let sandbox_env = match linux_sandbox_test_env().await {
|
||||
Some(env) => env,
|
||||
None => return,
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let sandbox_env = HashMap::new();
|
||||
let temp = tempfile::tempdir().expect("should be able to create temp dir");
|
||||
let sandbox_root = temp.path().join("sandbox");
|
||||
let command_root = temp.path().join("command").abs();
|
||||
create_dir_all(&sandbox_root).await.expect("mkdir");
|
||||
create_dir_all(&command_root).await.expect("mkdir");
|
||||
let canonical_sandbox_root = tokio::fs::canonicalize(&sandbox_root)
|
||||
.await
|
||||
.expect("canonicalize sandbox root")
|
||||
.abs();
|
||||
let canonical_allowed_path = canonical_sandbox_root.join("allowed.txt");
|
||||
|
||||
let disallowed_path = command_root.join("forbidden.txt");
|
||||
|
||||
// Note writable_roots is empty: verify that `canonical_allowed_path` is
|
||||
// writable only because it is under the sandbox policy cwd, not because it
|
||||
// is under a writable root.
|
||||
let permission_profile = PermissionProfile::workspace_write_with(
|
||||
&[],
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
/*exclude_tmpdir_env_var*/ true,
|
||||
/*exclude_slash_tmp*/ true,
|
||||
);
|
||||
|
||||
// Attempt to write inside the command cwd, which is outside of the sandbox policy cwd.
|
||||
let mut child = spawn_command_under_sandbox(
|
||||
vec![
|
||||
"bash".to_string(),
|
||||
"-lc".to_string(),
|
||||
"echo forbidden > forbidden.txt".to_string(),
|
||||
],
|
||||
command_root.clone(),
|
||||
&permission_profile,
|
||||
&canonical_sandbox_root,
|
||||
StdioPolicy::Inherit,
|
||||
sandbox_env.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("should spawn command writing to forbidden path");
|
||||
|
||||
let status = child
|
||||
.wait()
|
||||
.await
|
||||
.expect("should wait for forbidden command");
|
||||
assert!(
|
||||
!status.success(),
|
||||
"sandbox unexpectedly allowed writing to command cwd: {status:?}"
|
||||
);
|
||||
let forbidden_exists = tokio::fs::try_exists(&disallowed_path)
|
||||
.await
|
||||
.expect("try_exists failed");
|
||||
assert!(
|
||||
!forbidden_exists,
|
||||
"forbidden path should not have been created"
|
||||
);
|
||||
|
||||
// Writing to the sandbox policy cwd after changing directories into it should succeed.
|
||||
let mut child = spawn_command_under_sandbox(
|
||||
vec![
|
||||
"/usr/bin/touch".to_string(),
|
||||
canonical_allowed_path.to_string_lossy().into_owned(),
|
||||
],
|
||||
command_root,
|
||||
&permission_profile,
|
||||
&canonical_sandbox_root,
|
||||
StdioPolicy::Inherit,
|
||||
sandbox_env,
|
||||
)
|
||||
.await
|
||||
.expect("should spawn command writing to sandbox root");
|
||||
|
||||
let status = child.wait().await.expect("should wait for allowed command");
|
||||
assert!(
|
||||
status.success(),
|
||||
"sandbox blocked allowed write: {status:?}"
|
||||
);
|
||||
let allowed_exists = tokio::fs::try_exists(&canonical_allowed_path)
|
||||
.await
|
||||
.expect("try_exists allowed failed");
|
||||
assert!(allowed_exists, "allowed path should exist");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sandbox_blocks_first_time_dot_codex_creation() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
#[cfg(target_os = "linux")]
|
||||
let sandbox_env = match linux_sandbox_test_env().await {
|
||||
Some(env) => env,
|
||||
None => return,
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let sandbox_env = HashMap::new();
|
||||
|
||||
let temp = tempfile::tempdir().expect("should be able to create temp dir");
|
||||
let repo_root = temp.path().join("repo").abs();
|
||||
create_dir_all(&repo_root).await.expect("mkdir repo");
|
||||
let dot_codex = repo_root.join(".codex");
|
||||
let config_toml = dot_codex.join("config.toml");
|
||||
let permission_profile = PermissionProfile::workspace_write_with(
|
||||
&[],
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
/*exclude_tmpdir_env_var*/ true,
|
||||
/*exclude_slash_tmp*/ true,
|
||||
);
|
||||
|
||||
let mut child = spawn_command_under_sandbox(
|
||||
vec![
|
||||
"bash".to_string(),
|
||||
"-lc".to_string(),
|
||||
"mkdir -p .codex && echo 'sandbox_mode = \"danger-full-access\"' > .codex/config.toml"
|
||||
.to_string(),
|
||||
],
|
||||
repo_root.clone(),
|
||||
&permission_profile,
|
||||
&repo_root,
|
||||
StdioPolicy::RedirectForShellTool,
|
||||
sandbox_env,
|
||||
)
|
||||
.await
|
||||
.expect("should spawn command creating .codex");
|
||||
|
||||
let status = child.wait().await.expect("should wait for .codex command");
|
||||
assert!(
|
||||
!status.success(),
|
||||
"sandbox unexpectedly allowed first-time .codex creation: {status:?}"
|
||||
);
|
||||
let dot_codex_metadata = tokio::fs::symlink_metadata(&dot_codex).await;
|
||||
if let Ok(metadata) = dot_codex_metadata {
|
||||
assert!(
|
||||
!metadata.is_dir(),
|
||||
"{} should not be creatable as a directory",
|
||||
dot_codex.display()
|
||||
);
|
||||
} else if let Err(err) = &dot_codex_metadata {
|
||||
assert_eq!(
|
||||
err.kind(),
|
||||
io::ErrorKind::NotFound,
|
||||
"unexpected metadata error for {}: {err}",
|
||||
dot_codex.display()
|
||||
);
|
||||
}
|
||||
let config_toml_exists = match tokio::fs::try_exists(&config_toml).await {
|
||||
Ok(exists) => exists,
|
||||
Err(err) if err.kind() == io::ErrorKind::NotADirectory => false,
|
||||
Err(err) => panic!("try_exists {} failed: {err}", config_toml.display()),
|
||||
};
|
||||
assert!(
|
||||
!config_toml_exists,
|
||||
"{} should not have been created",
|
||||
config_toml.display()
|
||||
);
|
||||
}
|
||||
|
||||
fn unix_sock_body() {
|
||||
unsafe {
|
||||
let mut fds = [0i32; 2];
|
||||
let r = libc::socketpair(libc::AF_UNIX, libc::SOCK_DGRAM, 0, fds.as_mut_ptr());
|
||||
assert_eq!(
|
||||
r,
|
||||
0,
|
||||
"socketpair(AF_UNIX, SOCK_DGRAM) failed: {}",
|
||||
io::Error::last_os_error()
|
||||
);
|
||||
|
||||
let msg = b"hello_unix";
|
||||
// write() from one end (generic write is allowed)
|
||||
let sent = libc::write(fds[0], msg.as_ptr() as *const libc::c_void, msg.len());
|
||||
assert!(sent >= 0, "write() failed: {}", io::Error::last_os_error());
|
||||
|
||||
// recvfrom() on the other end. We don’t need the address for socketpair,
|
||||
// so we pass null pointers for src address.
|
||||
let mut buf = [0u8; 64];
|
||||
let recvd = libc::recvfrom(
|
||||
fds[1],
|
||||
buf.as_mut_ptr() as *mut libc::c_void,
|
||||
buf.len(),
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null_mut(),
|
||||
);
|
||||
assert!(
|
||||
recvd >= 0,
|
||||
"recvfrom() failed: {}",
|
||||
io::Error::last_os_error()
|
||||
);
|
||||
|
||||
let recvd_slice = &buf[..(recvd as usize)];
|
||||
assert_eq!(
|
||||
recvd_slice,
|
||||
&msg[..],
|
||||
"payload mismatch: sent {} bytes, got {} bytes",
|
||||
msg.len(),
|
||||
recvd
|
||||
);
|
||||
|
||||
// Also exercise AF_UNIX stream socketpair quickly to ensure AF_UNIX in general works.
|
||||
let mut sfds = [0i32; 2];
|
||||
let sr = libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM, 0, sfds.as_mut_ptr());
|
||||
assert_eq!(
|
||||
sr,
|
||||
0,
|
||||
"socketpair(AF_UNIX, SOCK_STREAM) failed: {}",
|
||||
io::Error::last_os_error()
|
||||
);
|
||||
let snt2 = libc::write(sfds[0], msg.as_ptr() as *const libc::c_void, msg.len());
|
||||
assert!(
|
||||
snt2 >= 0,
|
||||
"write(stream) failed: {}",
|
||||
io::Error::last_os_error()
|
||||
);
|
||||
let mut b2 = [0u8; 64];
|
||||
let rcv2 = libc::recv(sfds[1], b2.as_mut_ptr() as *mut libc::c_void, b2.len(), 0);
|
||||
assert!(
|
||||
rcv2 >= 0,
|
||||
"recv(stream) failed: {}",
|
||||
io::Error::last_os_error()
|
||||
);
|
||||
|
||||
// Clean up
|
||||
let _ = libc::close(sfds[0]);
|
||||
let _ = libc::close(sfds[1]);
|
||||
let _ = libc::close(fds[0]);
|
||||
let _ = libc::close(fds[1]);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn allow_unix_socketpair_recvfrom() {
|
||||
run_code_under_sandbox(
|
||||
"allow_unix_socketpair_recvfrom",
|
||||
&PermissionProfile::read_only(),
|
||||
|| async { unix_sock_body() },
|
||||
)
|
||||
.await
|
||||
.expect("should be able to reexec");
|
||||
}
|
||||
|
||||
const IN_SANDBOX_ENV_VAR: &str = "IN_SANDBOX";
|
||||
|
||||
pub async fn run_code_under_sandbox<F, Fut>(
|
||||
test_selector: &str,
|
||||
permission_profile: &PermissionProfile,
|
||||
child_body: F,
|
||||
) -> io::Result<Option<ExitStatus>>
|
||||
where
|
||||
F: FnOnce() -> Fut + Send + 'static,
|
||||
Fut: Future<Output = ()> + Send + 'static,
|
||||
{
|
||||
if std::env::var(IN_SANDBOX_ENV_VAR).is_err() {
|
||||
let exe = std::env::current_exe()?;
|
||||
let mut cmds = vec![exe.to_string_lossy().into_owned(), "--exact".into()];
|
||||
let mut stdio_policy = StdioPolicy::RedirectForShellTool;
|
||||
// Allow for us to pass forward --nocapture / use the right stdio policy.
|
||||
if std::env::args().any(|a| a == "--nocapture") {
|
||||
cmds.push("--nocapture".into());
|
||||
stdio_policy = StdioPolicy::Inherit;
|
||||
}
|
||||
cmds.push(test_selector.into());
|
||||
|
||||
// Your existing launcher:
|
||||
let command_cwd =
|
||||
AbsolutePathBuf::current_dir().expect("should be able to get current dir");
|
||||
let sandbox_cwd = command_cwd.clone();
|
||||
let mut child = spawn_command_under_sandbox(
|
||||
cmds,
|
||||
command_cwd,
|
||||
permission_profile,
|
||||
&sandbox_cwd,
|
||||
stdio_policy,
|
||||
HashMap::from([("IN_SANDBOX".into(), "1".into())]),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let status = child.wait().await?;
|
||||
Ok(Some(status))
|
||||
} else {
|
||||
// Child branch: run the provided body.
|
||||
child_body().await;
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
880
codex-rs/exec/tests/suite/seatbelt.rs
Normal file
880
codex-rs/exec/tests/suite/seatbelt.rs
Normal file
@@ -0,0 +1,880 @@
|
||||
use super::sandbox::spawn_command_under_sandbox;
|
||||
use codex_core::spawn::StdioPolicy;
|
||||
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::NetworkSandboxPolicy;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::os::unix::fs::symlink;
|
||||
use std::process::Output;
|
||||
use std::time::Duration;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn codex_home_symlink_opt_out_uses_loaded_user_config() -> anyhow::Result<()> {
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use serde_json::json;
|
||||
|
||||
core_test_support::skip_if_sandbox!(Ok(()));
|
||||
for (home_env, root_alias, enabled, ignore_user_config) in [
|
||||
("user-home", Some("user-home"), true, false),
|
||||
("home-link/../.codex", Some(".codex"), false, false),
|
||||
("home-link/../.codex", None, true, false),
|
||||
("user-home", Some("user-home"), true, true),
|
||||
] {
|
||||
let test = test_codex_exec();
|
||||
let home = test.home_path().join(".codex");
|
||||
let project_home = test.cwd_path().join(".codex");
|
||||
let child = test.home_path().join("child");
|
||||
for directory in [&home, &project_home, &child] {
|
||||
fs::create_dir(directory)?;
|
||||
}
|
||||
symlink(&home, test.cwd_path().join("user-home"))?;
|
||||
symlink(&child, test.cwd_path().join("home-link"))?;
|
||||
fs::write(
|
||||
home.join("config.toml"),
|
||||
format!("allow_symlinked_codex_home = {enabled}\n"),
|
||||
)?;
|
||||
// The checkout must not enable the opt-out, even when `..` follows a symlink.
|
||||
fs::write(
|
||||
project_home.join("config.toml"),
|
||||
"allow_symlinked_codex_home = true\n",
|
||||
)?;
|
||||
let target = TempDir::new()?;
|
||||
for root in [&home, &project_home] {
|
||||
symlink(target.path(), root.join("visualizations"))?;
|
||||
}
|
||||
let writable_home =
|
||||
root_alias.map_or_else(|| home.clone(), |alias| test.cwd_path().join(alias));
|
||||
let visualizations = writable_home.join("visualizations");
|
||||
let shell_args = json!({
|
||||
"cmd": "printf shell > shell.txt",
|
||||
"workdir": visualizations,
|
||||
"shell": "/bin/sh",
|
||||
"login": false,
|
||||
})
|
||||
.to_string();
|
||||
let patch = format!(
|
||||
"*** Begin Patch\n*** Add File: {}/patch.txt\n+patched\n*** End Patch",
|
||||
visualizations.display()
|
||||
);
|
||||
let server = responses::start_mock_server().await;
|
||||
let should_run = enabled && !ignore_user_config;
|
||||
let mock = responses::mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
responses::sse(vec![
|
||||
responses::ev_function_call("shell", "exec_command", &shell_args),
|
||||
responses::ev_apply_patch_custom_tool_call("patch", &patch),
|
||||
responses::ev_completed("response-1"),
|
||||
]),
|
||||
responses::sse(vec![responses::ev_completed("response-2")]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
let mut command = test.cmd_with_server(&server);
|
||||
command
|
||||
.env_remove("CODEX_API_KEY")
|
||||
.env_remove("OPENAI_API_KEY")
|
||||
.env_remove("CODEX_ACCESS_TOKEN")
|
||||
.env("CODEX_HOME", home_env)
|
||||
.args(["--skip-git-repo-check", "--sandbox", "workspace-write", "--add-dir"])
|
||||
.arg(&visualizations)
|
||||
.args(["-c", "approvals_reviewer=\"user\"", "-c", "features.shell_snapshot_v2=false"])
|
||||
// Session overrides cannot authorize the host's exception either.
|
||||
.args(["-c", "allow_symlinked_codex_home=true"])
|
||||
.args(["-c", "model_provider=\"test\"", "-c"])
|
||||
.arg(format!(
|
||||
"model_providers.test={{name=\"test\",base_url={:?},wire_api=\"responses\",requires_openai_auth=false,supports_websockets=false}}",
|
||||
format!("{}/v1", server.uri())
|
||||
))
|
||||
.arg("write the files");
|
||||
if ignore_user_config {
|
||||
command.arg("--ignore-user-config");
|
||||
}
|
||||
let output = command.output()?;
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
assert_eq!(mock.requests().len(), 2);
|
||||
if should_run {
|
||||
assert_eq!(fs::read(target.path().join("shell.txt"))?, b"shell");
|
||||
assert_eq!(fs::read(target.path().join("patch.txt"))?, b"patched\n");
|
||||
} else {
|
||||
let shell_output = mock
|
||||
.function_call_output_text("shell")
|
||||
.expect("shell tool output");
|
||||
assert!(
|
||||
shell_output.contains("symlinked writable roots are not supported"),
|
||||
"{shell_output}"
|
||||
);
|
||||
assert!(!target.path().join("shell.txt").exists());
|
||||
assert!(!target.path().join("patch.txt").exists());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn workspace_fixture() -> (TempDir, AbsolutePathBuf) {
|
||||
let temp_dir = TempDir::new().expect("create temporary directory");
|
||||
let workspace = temp_dir.path().join("workspace");
|
||||
fs::create_dir(&workspace).expect("create workspace");
|
||||
let workspace = AbsolutePathBuf::from_absolute_path(
|
||||
workspace.canonicalize().expect("canonicalize workspace"),
|
||||
)
|
||||
.expect("workspace is absolute");
|
||||
(temp_dir, workspace)
|
||||
}
|
||||
|
||||
fn permission_profile(
|
||||
workspace: &AbsolutePathBuf,
|
||||
restricted_paths: Vec<(FileSystemPath, FileSystemAccessMode)>,
|
||||
) -> PermissionProfile {
|
||||
let mut file_system_policy = FileSystemSandboxPolicy::read_only();
|
||||
file_system_policy.entries.push(FileSystemSandboxEntry::new(
|
||||
workspace.clone().into(),
|
||||
FileSystemAccessMode::Write,
|
||||
));
|
||||
file_system_policy.entries.extend(
|
||||
restricted_paths
|
||||
.into_iter()
|
||||
.map(|(path, access)| FileSystemSandboxEntry::new(path, access)),
|
||||
);
|
||||
|
||||
PermissionProfile::from_runtime_permissions(
|
||||
&file_system_policy,
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
)
|
||||
}
|
||||
|
||||
fn denied_glob_profile(workspace: &AbsolutePathBuf, pattern: String) -> PermissionProfile {
|
||||
permission_profile(
|
||||
workspace,
|
||||
vec![(
|
||||
FileSystemPath::GlobPattern { pattern },
|
||||
FileSystemAccessMode::Deny,
|
||||
)],
|
||||
)
|
||||
}
|
||||
|
||||
async fn run_sandboxed_command(
|
||||
command: Vec<String>,
|
||||
workspace: &AbsolutePathBuf,
|
||||
permission_profile: &PermissionProfile,
|
||||
) -> Output {
|
||||
spawn_command_under_sandbox(
|
||||
command,
|
||||
workspace.clone(),
|
||||
permission_profile,
|
||||
workspace,
|
||||
StdioPolicy::RedirectForShellTool,
|
||||
HashMap::new(),
|
||||
)
|
||||
.await
|
||||
.expect("spawn command under production Seatbelt policy")
|
||||
.wait_with_output()
|
||||
.await
|
||||
.expect("wait for sandboxed command")
|
||||
}
|
||||
|
||||
async fn run_path_command(
|
||||
executable: &str,
|
||||
path: &AbsolutePathBuf,
|
||||
workspace: &AbsolutePathBuf,
|
||||
profile: &PermissionProfile,
|
||||
) -> Output {
|
||||
run_sandboxed_command(
|
||||
vec![executable.to_string(), path.display().to_string()],
|
||||
workspace,
|
||||
profile,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn assert_denied_read(
|
||||
path: &AbsolutePathBuf,
|
||||
workspace: &AbsolutePathBuf,
|
||||
profile: &PermissionProfile,
|
||||
) {
|
||||
let output = run_path_command("/bin/cat", path, workspace, profile).await;
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"Seatbelt allowed reading {}: {output:?}",
|
||||
path.display()
|
||||
);
|
||||
assert!(output.stdout.is_empty(), "protected contents leaked");
|
||||
}
|
||||
|
||||
fn assert_file_contents(path: &AbsolutePathBuf, contents: &str) {
|
||||
assert_eq!(fs::read_to_string(path).expect("read fixture"), contents);
|
||||
}
|
||||
|
||||
async fn run_shell_command(
|
||||
script: &str,
|
||||
path: &AbsolutePathBuf,
|
||||
workspace: &AbsolutePathBuf,
|
||||
profile: &PermissionProfile,
|
||||
) -> Output {
|
||||
run_sandboxed_command(
|
||||
vec![
|
||||
"/bin/sh".to_string(),
|
||||
"-c".to_string(),
|
||||
script.to_string(),
|
||||
"sh".to_string(),
|
||||
path.display().to_string(),
|
||||
],
|
||||
workspace,
|
||||
profile,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn run_after_policy_applied(
|
||||
operation: &str,
|
||||
target: &AbsolutePathBuf,
|
||||
extra_args: Vec<String>,
|
||||
workspace: &AbsolutePathBuf,
|
||||
profile: &PermissionProfile,
|
||||
setup: impl FnOnce(),
|
||||
) -> Output {
|
||||
let label = target
|
||||
.as_path()
|
||||
.file_name()
|
||||
.expect("filename")
|
||||
.to_string_lossy();
|
||||
let ready = workspace.join(format!("{label}.ready.txt"));
|
||||
let proceed = workspace.join(format!("{label}.proceed.txt"));
|
||||
let script = format!(
|
||||
"printf ready > \"$2\"; while [ ! -e \"$3\" ]; do /bin/sleep 0.01; done; {operation}"
|
||||
);
|
||||
let mut command = vec![
|
||||
"/bin/sh".to_string(),
|
||||
"-c".to_string(),
|
||||
script,
|
||||
"sh".to_string(),
|
||||
target.display().to_string(),
|
||||
ready.display().to_string(),
|
||||
proceed.display().to_string(),
|
||||
];
|
||||
command.extend(extra_args);
|
||||
let child = spawn_command_under_sandbox(
|
||||
command,
|
||||
workspace.clone(),
|
||||
profile,
|
||||
workspace,
|
||||
StdioPolicy::RedirectForShellTool,
|
||||
HashMap::new(),
|
||||
)
|
||||
.await
|
||||
.expect("spawn command before creating protected fixture");
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while !ready.as_path().exists() {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("sandboxed command did not signal policy application");
|
||||
setup();
|
||||
fs::write(&proceed, "proceed").expect("release sandboxed command");
|
||||
child
|
||||
.wait_with_output()
|
||||
.await
|
||||
.expect("wait for sandboxed command")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn seatbelt_enforces_brace_alternation_and_escaped_deny_globs() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
|
||||
let (temp_dir, workspace) = workspace_fixture();
|
||||
let dotenv = workspace.join(".env");
|
||||
let secrets = workspace.join("secrets.yml");
|
||||
let escaped = workspace.join("config?.env");
|
||||
let allowed = workspace.join("notes.txt");
|
||||
for path in [&dotenv, &secrets, &escaped] {
|
||||
fs::write(path, "protected contents").expect("write protected fixture");
|
||||
}
|
||||
fs::write(&allowed, "allowed contents").expect("write allowed fixture");
|
||||
|
||||
let config = format!(
|
||||
r#"default_permissions = "test"
|
||||
[permissions.test]
|
||||
extends = ":read-only"
|
||||
[permissions.test.filesystem]
|
||||
"{workspace}" = "write"
|
||||
"{workspace}/{{.env,secrets.yml}}*" = "deny"
|
||||
'{workspace}/config\?.env' = "deny"
|
||||
"#,
|
||||
workspace = workspace.display()
|
||||
);
|
||||
fs::write(temp_dir.path().join("config.toml"), config).expect("write permissions config");
|
||||
let profile = core_test_support::load_default_config_for_test(&temp_dir)
|
||||
.await
|
||||
.permissions
|
||||
.effective_permission_profile();
|
||||
|
||||
for denied_path in [&dotenv, &secrets, &escaped] {
|
||||
assert_denied_read(denied_path, &workspace, &profile).await;
|
||||
}
|
||||
|
||||
let output = run_path_command("/bin/cat", &allowed, &workspace, &profile).await;
|
||||
assert!(output.status.success(), "allowed read failed: {output:?}");
|
||||
assert_eq!(output.stdout, b"allowed contents");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn seatbelt_blocks_renaming_ancestors_of_explicit_protected_files() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
|
||||
for access in [FileSystemAccessMode::Read, FileSystemAccessMode::Deny] {
|
||||
let (_temp_dir, workspace) = workspace_fixture();
|
||||
let private = workspace.join("private");
|
||||
let protected = private.join("secret.env");
|
||||
let renamed = workspace.join("exposed");
|
||||
fs::create_dir(&private).expect("create protected directory");
|
||||
fs::write(&protected, "protected contents").expect("write protected fixture");
|
||||
|
||||
let profile = permission_profile(&workspace, vec![(protected.clone().into(), access)]);
|
||||
let command = vec![
|
||||
"/bin/mv".to_string(),
|
||||
private.display().to_string(),
|
||||
renamed.display().to_string(),
|
||||
];
|
||||
let output = run_sandboxed_command(command.clone(), &workspace, &profile).await;
|
||||
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"Seatbelt allowed renaming an ancestor of a {access:?} path: {output:?}"
|
||||
);
|
||||
assert_file_contents(&protected, "protected contents");
|
||||
assert!(!renamed.as_path().exists(), "rename unexpectedly succeeded");
|
||||
|
||||
let unprotected = permission_profile(&workspace, Vec::new());
|
||||
let control = run_sandboxed_command(command, &workspace, &unprotected).await;
|
||||
assert!(
|
||||
control.status.success(),
|
||||
"rename without a protected descendant should succeed: {control:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn seatbelt_blocks_renaming_dynamic_glob_ancestors() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
|
||||
for component in [".githu?", "{.github,.gitlab}", r".githu\b", "*"] {
|
||||
let (_temp_dir, workspace) = workspace_fixture();
|
||||
let github = workspace.join(".github");
|
||||
let workflows = github.join("workflows");
|
||||
let protected = workflows.join("release.yml");
|
||||
let renamed = workspace.join("exposed");
|
||||
fs::create_dir_all(&workflows).expect("create protected directory");
|
||||
fs::write(&protected, "protected workflow").expect("write protected fixture");
|
||||
|
||||
let profile = denied_glob_profile(
|
||||
&workspace,
|
||||
format!("{}/{component}/workflows/*.yml", workspace.display()),
|
||||
);
|
||||
let command = vec![
|
||||
"/bin/mv".to_string(),
|
||||
github.display().to_string(),
|
||||
renamed.display().to_string(),
|
||||
];
|
||||
let output = run_sandboxed_command(command.clone(), &workspace, &profile).await;
|
||||
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"Seatbelt allowed renaming ancestor matched by {component:?}: {output:?}"
|
||||
);
|
||||
assert_file_contents(&protected, "protected workflow");
|
||||
|
||||
let unprotected = permission_profile(&workspace, Vec::new());
|
||||
let control = run_sandboxed_command(command, &workspace, &unprotected).await;
|
||||
assert!(
|
||||
control.status.success(),
|
||||
"rename without the deny glob should succeed: {control:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn seatbelt_blocks_renaming_protected_workspace_into_another_writable_root() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
|
||||
let (_temp_dir, workspace) = workspace_fixture();
|
||||
let destination = workspace
|
||||
.parent()
|
||||
.expect("workspace has a parent")
|
||||
.join("destination");
|
||||
let moved_workspace = destination.join("moved");
|
||||
let protected = workspace.join("secret.env");
|
||||
fs::create_dir(&destination).expect("create writable destination");
|
||||
fs::write(&protected, "protected contents").expect("write protected fixture");
|
||||
|
||||
let profile = permission_profile(
|
||||
&workspace,
|
||||
vec![
|
||||
(destination.clone().into(), FileSystemAccessMode::Write),
|
||||
(protected.clone().into(), FileSystemAccessMode::Read),
|
||||
],
|
||||
);
|
||||
let output = run_sandboxed_command(
|
||||
vec![
|
||||
"/bin/mv".to_string(),
|
||||
workspace.display().to_string(),
|
||||
moved_workspace.display().to_string(),
|
||||
],
|
||||
&workspace,
|
||||
&profile,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"Seatbelt allowed moving the workspace into another writable root: {output:?}"
|
||||
);
|
||||
assert_file_contents(&protected, "protected contents");
|
||||
assert!(
|
||||
!moved_workspace.as_path().exists(),
|
||||
"workspace unexpectedly moved"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn seatbelt_ancestor_protection_does_not_block_unlinking_regular_files() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
|
||||
let (_temp_dir, workspace) = workspace_fixture();
|
||||
let regular_file = workspace.join("regular-file");
|
||||
let hypothetical_descendant = regular_file.join("secret.env");
|
||||
fs::write(®ular_file, "replaceable").expect("write regular file");
|
||||
let profile = permission_profile(
|
||||
&workspace,
|
||||
vec![(hypothetical_descendant.into(), FileSystemAccessMode::Read)],
|
||||
);
|
||||
|
||||
let output = run_path_command("/bin/rm", ®ular_file, &workspace, &profile).await;
|
||||
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"directory-only ancestor protection blocked a regular file: {output:?}"
|
||||
);
|
||||
assert!(
|
||||
!regular_file.as_path().exists(),
|
||||
"regular file was not removed"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn seatbelt_deny_globs_block_writes_to_existing_and_new_files() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
|
||||
let (_temp_dir, workspace) = workspace_fixture();
|
||||
let protected = workspace.join("secret.env");
|
||||
let allowed = workspace.join("notes.txt");
|
||||
fs::write(&protected, "original").expect("write protected fixture");
|
||||
let profile = denied_glob_profile(&workspace, format!("{}/*.env", workspace.display()));
|
||||
|
||||
for (operation, script) in [
|
||||
("overwrite", "printf changed >> \"$1\""),
|
||||
("truncate", ": > \"$1\""),
|
||||
] {
|
||||
let output = run_shell_command(script, &protected, &workspace, &profile).await;
|
||||
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"Seatbelt allowed {operation} on a denied file: {output:?}"
|
||||
);
|
||||
assert_file_contents(&protected, "original");
|
||||
}
|
||||
|
||||
let unlink = run_path_command("/bin/rm", &protected, &workspace, &profile).await;
|
||||
assert!(
|
||||
!unlink.status.success(),
|
||||
"Seatbelt unexpectedly allowed unlinking a denied glob: {unlink:?}"
|
||||
);
|
||||
assert_file_contents(&protected, "original");
|
||||
|
||||
for (operation, write_script) in [
|
||||
("overwrite", "printf changed >> \"$1\""),
|
||||
("truncate", ": > \"$1\""),
|
||||
] {
|
||||
let late_protected = workspace.join(format!("late-{operation}.env"));
|
||||
let output = run_after_policy_applied(
|
||||
write_script,
|
||||
&late_protected,
|
||||
Vec::new(),
|
||||
&workspace,
|
||||
&profile,
|
||||
|| {
|
||||
fs::write(&late_protected, "created after policy generation")
|
||||
.expect("create protected fixture after sandbox launch");
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"Seatbelt allowed {operation} on a file created after policy generation: {output:?}"
|
||||
);
|
||||
assert_file_contents(&late_protected, "created after policy generation");
|
||||
}
|
||||
|
||||
let allowed_write =
|
||||
run_shell_command("printf allowed > \"$1\"", &allowed, &workspace, &profile).await;
|
||||
assert!(
|
||||
allowed_write.status.success(),
|
||||
"unrelated write should remain allowed: {allowed_write:?}"
|
||||
);
|
||||
assert_file_contents(&allowed, "allowed");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn seatbelt_standard_profiles_preserve_expected_filesystem_access() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
let (_temp_dir, workspace) = workspace_fixture();
|
||||
let inside = workspace.join("notes.txt");
|
||||
let outside = workspace.parent().expect("parent").join("outside.txt");
|
||||
fs::write(&inside, "original").expect("write workspace fixture");
|
||||
let profile = permission_profile(&workspace, Vec::new());
|
||||
let script = "set -e; /bin/cat \"$1\" >/dev/null; printf changed >> \"$1\"; /bin/mkdir \"$1.dir\"; /bin/mv \"$1\" \"$1.dir/moved\"; /bin/rm \"$1.dir/moved\"; /bin/rmdir \"$1.dir\"";
|
||||
let inside_output = run_shell_command(script, &inside, &workspace, &profile).await;
|
||||
assert!(
|
||||
inside_output.status.success(),
|
||||
"ordinary workspace operations failed: {inside_output:?}"
|
||||
);
|
||||
|
||||
let outside_output =
|
||||
run_shell_command("printf denied > \"$1\"", &outside, &workspace, &profile).await;
|
||||
assert!(
|
||||
!outside_output.status.success(),
|
||||
"write outside the workspace unexpectedly succeeded: {outside_output:?}"
|
||||
);
|
||||
assert!(!outside.as_path().exists(), "outside file was created");
|
||||
let readable = workspace.join("readable.txt");
|
||||
fs::write(&readable, "readable contents").expect("write read-only fixture");
|
||||
let profile = PermissionProfile::read_only();
|
||||
let read = run_path_command("/bin/cat", &readable, &workspace, &profile).await;
|
||||
assert!(read.status.success(), "ordinary read failed: {read:?}");
|
||||
assert_eq!(read.stdout, b"readable contents");
|
||||
|
||||
let write = run_shell_command("printf changed > \"$1\"", &readable, &workspace, &profile).await;
|
||||
assert!(
|
||||
!write.status.success(),
|
||||
"read-only write succeeded: {write:?}"
|
||||
);
|
||||
assert_file_contents(&readable, "readable contents");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn seatbelt_blocks_protected_reads_and_writes_through_symlink_aliases() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
|
||||
let (_temp_dir, workspace) = workspace_fixture();
|
||||
let private = workspace.join("private");
|
||||
let alias = workspace.join("alias");
|
||||
let protected = private.join("secret.env");
|
||||
let alias_path = alias.join("secret.env");
|
||||
fs::create_dir(&private).expect("create protected directory");
|
||||
fs::write(&protected, "protected contents").expect("write protected fixture");
|
||||
symlink(private.as_path(), alias.as_path()).expect("create directory symlink");
|
||||
|
||||
for (restricted_path, accessed_path) in [
|
||||
(FileSystemPath::from(protected.clone()), alias_path.clone()),
|
||||
(
|
||||
FileSystemPath::GlobPattern {
|
||||
pattern: format!("{}/*.env", private.display()),
|
||||
},
|
||||
alias_path.clone(),
|
||||
),
|
||||
(
|
||||
FileSystemPath::GlobPattern {
|
||||
pattern: format!("{}/*.env", alias.display()),
|
||||
},
|
||||
protected.clone(),
|
||||
),
|
||||
] {
|
||||
let profile = permission_profile(
|
||||
&workspace,
|
||||
vec![(restricted_path, FileSystemAccessMode::Deny)],
|
||||
);
|
||||
assert_denied_read(&accessed_path, &workspace, &profile).await;
|
||||
|
||||
let write = run_shell_command(
|
||||
"printf changed > \"$1\"",
|
||||
&accessed_path,
|
||||
&workspace,
|
||||
&profile,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
!write.status.success(),
|
||||
"Seatbelt allowed writing through protected symlink alias: {write:?}"
|
||||
);
|
||||
assert_file_contents(&protected, "protected contents");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn seatbelt_globstar_protects_files_and_ancestors_at_every_depth() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
|
||||
let (_temp_dir, workspace) = workspace_fixture();
|
||||
let first = workspace.join("first");
|
||||
let second = first.join("second");
|
||||
fs::create_dir_all(&second).expect("create nested fixture directories");
|
||||
let protected_paths = [
|
||||
workspace.join("root.env"),
|
||||
first.join("first.env"),
|
||||
second.join("second.env"),
|
||||
];
|
||||
for path in &protected_paths {
|
||||
fs::write(path, "protected contents").expect("write protected fixture");
|
||||
}
|
||||
let profile = denied_glob_profile(&workspace, format!("{}/**/*.env", workspace.display()));
|
||||
|
||||
for path in &protected_paths {
|
||||
assert_denied_read(path, &workspace, &profile).await;
|
||||
}
|
||||
|
||||
for ancestor in [&first, &second] {
|
||||
let destination = ancestor.with_extension("renamed");
|
||||
let output = run_sandboxed_command(
|
||||
vec![
|
||||
"/bin/mv".to_string(),
|
||||
ancestor.display().to_string(),
|
||||
destination.display().to_string(),
|
||||
],
|
||||
&workspace,
|
||||
&profile,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"globstar allowed renaming protected ancestor {}: {output:?}",
|
||||
ancestor.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn seatbelt_brace_alternatives_with_slashes_protect_each_branch() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
|
||||
let (_temp_dir, workspace) = workspace_fixture();
|
||||
let nested = workspace.join("private/nested");
|
||||
let other = workspace.join("other");
|
||||
let allowed = workspace.join("notes.txt");
|
||||
fs::create_dir_all(&nested).expect("create nested protected directory");
|
||||
fs::create_dir(&other).expect("create alternate protected directory");
|
||||
let protected_paths = [nested.join("secret.env"), other.join("secret.env")];
|
||||
for path in &protected_paths {
|
||||
fs::write(path, "protected contents").expect("write protected fixture");
|
||||
}
|
||||
fs::write(&allowed, "allowed contents").expect("write allowed fixture");
|
||||
let profile = denied_glob_profile(
|
||||
&workspace,
|
||||
format!("{}/{{private/nested,other}}/*.env", workspace.display()),
|
||||
);
|
||||
|
||||
for path in &protected_paths {
|
||||
assert_denied_read(path, &workspace, &profile).await;
|
||||
}
|
||||
|
||||
for ancestor in [&workspace.join("private"), &nested, &other] {
|
||||
let destination = ancestor.with_extension("renamed");
|
||||
let output = run_sandboxed_command(
|
||||
vec![
|
||||
"/bin/mv".to_string(),
|
||||
ancestor.display().to_string(),
|
||||
destination.display().to_string(),
|
||||
],
|
||||
&workspace,
|
||||
&profile,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"brace alternative allowed renaming {}: {output:?}",
|
||||
ancestor.display()
|
||||
);
|
||||
}
|
||||
|
||||
let output = run_path_command("/bin/cat", &allowed, &workspace, &profile).await;
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"brace alternatives produced an invalid or overly broad policy: {output:?}"
|
||||
);
|
||||
assert_eq!(output.stdout, b"allowed contents");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn seatbelt_protects_directory_trees_created_after_policy_application() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
|
||||
for operation in ["read", "rename"] {
|
||||
let (_temp_dir, workspace) = workspace_fixture();
|
||||
let late_directory = workspace.join("late/deep");
|
||||
let protected = late_directory.join("secret.env");
|
||||
let destination = workspace.join("exposed");
|
||||
let profile = denied_glob_profile(&workspace, format!("{}/**/*.env", workspace.display()));
|
||||
let operation_script = match operation {
|
||||
"read" => "/bin/cat \"$1\"",
|
||||
"rename" => "/bin/mv \"$4\" \"$5\"",
|
||||
_ => unreachable!("unknown operation"),
|
||||
};
|
||||
let output = run_after_policy_applied(
|
||||
operation_script,
|
||||
&protected,
|
||||
vec![
|
||||
workspace.join("late").display().to_string(),
|
||||
destination.display().to_string(),
|
||||
],
|
||||
&workspace,
|
||||
&profile,
|
||||
|| {
|
||||
fs::create_dir_all(&late_directory)
|
||||
.expect("create protected directory after policy");
|
||||
fs::write(&protected, "protected contents").expect("write protected fixture");
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"Seatbelt allowed {operation} after protected directory appeared: {output:?}"
|
||||
);
|
||||
assert_file_contents(&protected, "protected contents");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn seatbelt_blocks_atomic_rename_exchange_and_destination_replacement() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
|
||||
for (operation, flags) in [("exchange", libc::RENAME_SWAP), ("replace", 0)] {
|
||||
let (_temp_dir, workspace) = workspace_fixture();
|
||||
let private = workspace.join("private");
|
||||
let destination = workspace.join("destination");
|
||||
let protected = private.join("secret.env");
|
||||
fs::create_dir(&private).expect("create protected directory");
|
||||
fs::create_dir(&destination).expect("create replacement directory");
|
||||
fs::write(&protected, "protected contents").expect("write protected fixture");
|
||||
let profile = permission_profile(
|
||||
&workspace,
|
||||
vec![(protected.clone().into(), FileSystemAccessMode::Read)],
|
||||
);
|
||||
let script = "import ctypes, os, sys; libc = ctypes.CDLL(None, use_errno=True); result = libc.renameatx_np(-2, os.fsencode(sys.argv[1]), -2, os.fsencode(sys.argv[2]), int(sys.argv[3])); sys.exit(0 if result == 0 else ctypes.get_errno())";
|
||||
let command = vec![
|
||||
"/usr/bin/python3".to_string(),
|
||||
"-c".to_string(),
|
||||
script.to_string(),
|
||||
private.display().to_string(),
|
||||
destination.display().to_string(),
|
||||
flags.to_string(),
|
||||
];
|
||||
let output = run_sandboxed_command(command.clone(), &workspace, &profile).await;
|
||||
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"Seatbelt allowed atomic {operation} of a protected ancestor: {output:?}"
|
||||
);
|
||||
assert_file_contents(&protected, "protected contents");
|
||||
|
||||
let unprotected = permission_profile(&workspace, Vec::new());
|
||||
let control = run_sandboxed_command(command, &workspace, &unprotected).await;
|
||||
assert!(
|
||||
control.status.success(),
|
||||
"unprotected atomic {operation} should succeed: {control:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn seatbelt_blocks_protected_ancestor_moves_across_writable_roots() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
|
||||
for destination_is_nested in [false, true] {
|
||||
for use_glob in [false, true] {
|
||||
let (_temp_dir, workspace) = workspace_fixture();
|
||||
let private = workspace.join("private");
|
||||
let protected = private.join("secret.env");
|
||||
let destination = if destination_is_nested {
|
||||
workspace.join("destination")
|
||||
} else {
|
||||
workspace
|
||||
.parent()
|
||||
.expect("workspace has a parent")
|
||||
.join("destination")
|
||||
};
|
||||
let moved = destination.join("moved");
|
||||
fs::create_dir(&private).expect("create protected directory");
|
||||
fs::create_dir(&destination).expect("create writable destination");
|
||||
fs::write(&protected, "protected contents").expect("write protected fixture");
|
||||
let protected_path = if use_glob {
|
||||
FileSystemPath::GlobPattern {
|
||||
pattern: format!("{}/*.env", private.display()),
|
||||
}
|
||||
} else {
|
||||
protected.clone().into()
|
||||
};
|
||||
let profile = permission_profile(
|
||||
&workspace,
|
||||
vec![
|
||||
(destination.clone().into(), FileSystemAccessMode::Write),
|
||||
(protected_path, FileSystemAccessMode::Deny),
|
||||
],
|
||||
);
|
||||
|
||||
let output = run_sandboxed_command(
|
||||
vec![
|
||||
"/bin/mv".to_string(),
|
||||
private.display().to_string(),
|
||||
moved.display().to_string(),
|
||||
],
|
||||
&workspace,
|
||||
&profile,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"protected ancestor crossed writable roots: nested={destination_is_nested}, glob={use_glob}, output={output:?}"
|
||||
);
|
||||
assert_file_contents(&protected, "protected contents");
|
||||
assert!(!moved.as_path().exists(), "protected ancestor was moved");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn seatbelt_blocks_creating_files_matched_by_denied_globs() {
|
||||
core_test_support::skip_if_sandbox!();
|
||||
|
||||
let (_temp_dir, workspace) = workspace_fixture();
|
||||
let nested = workspace.join("nested");
|
||||
fs::create_dir(&nested).expect("create nested directory");
|
||||
let profile = denied_glob_profile(&workspace, format!("{}/**/*.env", workspace.display()));
|
||||
|
||||
for path in [workspace.join("created.env"), nested.join("created.env")] {
|
||||
let output =
|
||||
run_shell_command("printf created > \"$1\"", &path, &workspace, &profile).await;
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"Seatbelt allowed creation at a denied path: {output:?}"
|
||||
);
|
||||
assert!(!path.as_path().exists(), "denied file was created");
|
||||
}
|
||||
|
||||
let allowed = nested.join("created.txt");
|
||||
let output = run_path_command("/usr/bin/touch", &allowed, &workspace, &profile).await;
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"unrelated file creation should succeed: {output:?}"
|
||||
);
|
||||
assert!(allowed.as_path().exists(), "unrelated file was not created");
|
||||
}
|
||||
33
codex-rs/exec/tests/suite/server_error_exit.rs
Normal file
33
codex-rs/exec/tests/suite/server_error_exit.rs
Normal file
@@ -0,0 +1,33 @@
|
||||
#![cfg(not(target_os = "windows"))]
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
|
||||
/// Verify that when the server reports an error, `codex-exec` exits with a
|
||||
/// non-zero status code so automation can detect failures.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exits_non_zero_when_server_reports_error() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
|
||||
// Mock a simple Responses API SSE stream that immediately reports a
|
||||
// `response.failed` event with an error message.
|
||||
let server = responses::start_mock_server().await;
|
||||
let body = responses::sse(vec![serde_json::json!({
|
||||
"type": "response.failed",
|
||||
"response": {
|
||||
"id": "resp_err_1",
|
||||
"error": {"code": "rate_limit_exceeded", "message": "synthetic server error"}
|
||||
}
|
||||
})]);
|
||||
responses::mount_sse_once(&server, body).await;
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg("tell me something")
|
||||
.arg("--experimental-json")
|
||||
.assert()
|
||||
.code(1);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
423
codex-rs/exec/tests/suite/worktree.rs
Normal file
423
codex-rs/exec/tests/suite/worktree.rs
Normal file
@@ -0,0 +1,423 @@
|
||||
//! Exercises gated shared-pool execution and preserves existing checkout ownership.
|
||||
//! Observe ownership at the first model request, before the process can finish.
|
||||
|
||||
use anyhow::Context;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_worktree::CreateWorktree;
|
||||
use codex_worktree::WorktreeManager;
|
||||
use codex_worktree::WorktreeSettings;
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::process::Output;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
fn git(cwd: &Path, args: &[&str]) -> anyhow::Result<()> {
|
||||
let output = Command::new("git")
|
||||
.current_dir(cwd)
|
||||
.args([
|
||||
"-c",
|
||||
"user.name=Worktree Test",
|
||||
"-c",
|
||||
"user.email=test@example.invalid",
|
||||
])
|
||||
.args(args)
|
||||
.output()?;
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn started_thread(output: Output) -> anyhow::Result<String> {
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let events = String::from_utf8(output.stdout)?
|
||||
.lines()
|
||||
.map(serde_json::from_str::<Value>)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
events
|
||||
.iter()
|
||||
.find(|event| event["type"] == "thread.started")
|
||||
.and_then(|event| event["thread_id"].as_str())
|
||||
.map(str::to_owned)
|
||||
.context("exec should report its thread id")
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn worktree_start_and_fork_use_host_pool_and_preserve_legacy_resume() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let home = AbsolutePathBuf::from_absolute_path(test.home_path())?
|
||||
.canonicalize()?
|
||||
.into_path_buf();
|
||||
let source = AbsolutePathBuf::from_absolute_path(test.cwd_path())?
|
||||
.canonicalize()?
|
||||
.into_path_buf();
|
||||
let extra = source.join("extra");
|
||||
fs::create_dir(&extra)?;
|
||||
fs::write(extra.join("tracked.txt"), "tracked")?;
|
||||
fs::write(source.join("AGENTS.md"), "managed checkout instructions")?;
|
||||
git(&source, &["init", "--quiet"])?;
|
||||
git(&source, &["add", "."])?;
|
||||
git(
|
||||
&source,
|
||||
&["commit", "--quiet", "--no-gpg-sign", "-m", "initial"],
|
||||
)?;
|
||||
let pool = home.join("shared-worktrees");
|
||||
let other_pool = serde_json::to_string(&home.join("session-only-pool"))?;
|
||||
fs::write(
|
||||
home.join("config.toml"),
|
||||
format!(
|
||||
"sandbox_mode = \"workspace-write\"\nfeatures.worktrees = true\n[desktop]\ngit-worktree-root = {}\n[projects.{}]\ntrust_level = \"trusted\"\n",
|
||||
serde_json::to_string(&pool)?,
|
||||
serde_json::to_string(&source)?,
|
||||
),
|
||||
)?;
|
||||
fs::write(
|
||||
home.join("demo.config.toml"),
|
||||
format!("features.worktrees = false\n[desktop]\ngit-worktree-root = {other_pool}\n"),
|
||||
)?;
|
||||
let mut settings = WorktreeSettings::for_cli(&home, /*desktop*/ None)?;
|
||||
settings.root = pool;
|
||||
let legacy_manager = WorktreeManager::new(WorktreeSettings {
|
||||
root: home.join("worktrees-cli"),
|
||||
..settings.clone()
|
||||
});
|
||||
let legacy = legacy_manager.create(&CreateWorktree {
|
||||
source_cwd: source.clone(),
|
||||
base: None,
|
||||
})?;
|
||||
let manager = WorktreeManager::new(settings);
|
||||
let body = responses::sse(vec![
|
||||
responses::ev_response_created("response_1"),
|
||||
responses::ev_assistant_message("message_1", "done"),
|
||||
responses::ev_completed("response_1"),
|
||||
]);
|
||||
let server = responses::start_mock_server().await;
|
||||
let seed_mock = responses::mount_sse_once(&server, body.clone()).await;
|
||||
let legacy_id = started_thread(
|
||||
test.cmd_with_server(&server)
|
||||
.current_dir(legacy.cwd.join("extra"))
|
||||
.args(["--json", "legacy seed"])
|
||||
.output()?,
|
||||
)?;
|
||||
seed_mock.single_request();
|
||||
legacy_manager.bind_thread(&legacy.root, &legacy_id)?;
|
||||
fs::write(source.join("AGENTS.md"), "uncommitted source instructions")?;
|
||||
fs::create_dir(source.join(".codex"))?;
|
||||
fs::write(source.join(".codex/config.toml"), "[invalid source config")?;
|
||||
|
||||
let launcher = tempfile::tempdir()?;
|
||||
fs::create_dir(launcher.path().join("extra"))?;
|
||||
let mut known_roots = Vec::new();
|
||||
for (fork, overrides) in [
|
||||
(false, Vec::new()),
|
||||
(
|
||||
true,
|
||||
vec![
|
||||
"--profile".to_owned(),
|
||||
"demo".to_owned(),
|
||||
"-c".to_owned(),
|
||||
"features.worktrees=true".to_owned(),
|
||||
"-c".to_owned(),
|
||||
format!("desktop.git-worktree-root={other_pool}"),
|
||||
"-c".to_owned(),
|
||||
format!("desktop={{git-worktree-root={other_pool}}}"),
|
||||
],
|
||||
),
|
||||
(true, vec!["--cd".to_owned(), extra.display().to_string()]),
|
||||
] {
|
||||
let explicit_cd = overrides.first().is_some_and(|arg| arg == "--cd");
|
||||
let server = responses::start_mock_server().await;
|
||||
let observed_owner = Arc::new(Mutex::<Option<String>>::default());
|
||||
let captured_owner = Arc::clone(&observed_owner);
|
||||
let observed_manager = manager.clone();
|
||||
let observed_source = source.clone();
|
||||
let previous_roots = known_roots.clone();
|
||||
// A matcher is needed here to inspect metadata at request time, not after exit.
|
||||
let response_mock = responses::mount_sse_once_match(
|
||||
&server,
|
||||
move |_: &wiremock::Request| {
|
||||
let owner = observed_manager
|
||||
.list(&observed_source)
|
||||
.expect("list shared checkouts")
|
||||
.into_iter()
|
||||
.find(|checkout| !previous_roots.contains(&checkout.root))
|
||||
.and_then(|checkout| {
|
||||
observed_manager.owner(&checkout.root).expect("read owner")
|
||||
});
|
||||
*captured_owner.lock().expect("capture request owner") = owner;
|
||||
true
|
||||
},
|
||||
body.clone(),
|
||||
)
|
||||
.await;
|
||||
let mut command = test.cmd_with_server(&server);
|
||||
command
|
||||
.args(["--json", "--worktree", "--add-dir", "extra"])
|
||||
.args(overrides);
|
||||
if fork {
|
||||
command
|
||||
.current_dir(launcher.path())
|
||||
.arg("fork")
|
||||
.arg(&legacy_id);
|
||||
}
|
||||
let thread_id = started_thread(command.arg("describe checkout").output()?)?;
|
||||
assert_eq!(
|
||||
*observed_owner.lock().expect("read captured owner"),
|
||||
Some(thread_id)
|
||||
);
|
||||
let checkout = manager
|
||||
.list(&source)?
|
||||
.into_iter()
|
||||
.find(|checkout| !known_roots.contains(&checkout.root))
|
||||
.context("one new shared checkout")?;
|
||||
let request = response_mock.single_request();
|
||||
let context = request
|
||||
.message_input_texts("user")
|
||||
.into_iter()
|
||||
.chain(request.message_input_texts("developer"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let checkout_cwd = AbsolutePathBuf::from_absolute_path(if explicit_cd {
|
||||
checkout.root.join("extra")
|
||||
} else {
|
||||
checkout.cwd.clone()
|
||||
})?
|
||||
.canonicalize()?;
|
||||
assert!(
|
||||
context.contains(checkout_cwd.to_string_lossy().as_ref()),
|
||||
"{context}"
|
||||
);
|
||||
assert!(
|
||||
context.contains(
|
||||
if fork {
|
||||
launcher.path().join("extra")
|
||||
} else {
|
||||
extra.clone()
|
||||
}
|
||||
.to_string_lossy()
|
||||
.as_ref()
|
||||
),
|
||||
"{context}"
|
||||
);
|
||||
assert!(
|
||||
context.contains("managed checkout instructions"),
|
||||
"{context}"
|
||||
);
|
||||
assert!(
|
||||
!context.contains("uncommitted source instructions"),
|
||||
"{context}"
|
||||
);
|
||||
known_roots.push(checkout.root);
|
||||
}
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let resume_mock = responses::mount_sse_once(&server, body).await;
|
||||
let resumed_id = started_thread(
|
||||
test.cmd_with_server(&server)
|
||||
.current_dir(legacy.cwd.join("extra"))
|
||||
.args(["--json", "resume", &legacy_id, "continue legacy"])
|
||||
.output()?,
|
||||
)?;
|
||||
assert_eq!(resumed_id, legacy_id);
|
||||
assert_eq!(legacy_manager.owner(&legacy.root)?, Some(legacy_id.clone()));
|
||||
let legacy_cwd =
|
||||
AbsolutePathBuf::from_absolute_path(legacy.cwd.join("extra"))?.canonicalize()?;
|
||||
assert!(
|
||||
resume_mock
|
||||
.single_request()
|
||||
.message_input_texts("user")
|
||||
.iter()
|
||||
.any(|text| text.contains(legacy_cwd.to_string_lossy().as_ref()))
|
||||
);
|
||||
fs::write(
|
||||
home.join("config.toml"),
|
||||
format!(
|
||||
"features.worktrees=true\n[projects.{}]\ntrust_level=\"untrusted\"\n",
|
||||
serde_json::to_string(&source)?,
|
||||
),
|
||||
)?;
|
||||
for args in [vec!["prompt"], vec!["fork", legacy_id.as_str(), "prompt"]] {
|
||||
let output = test.cmd().arg("--worktree").args(args).output()?;
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("explicitly untrusted"));
|
||||
}
|
||||
assert!(!home.join("worktrees").exists());
|
||||
|
||||
// Synthetic enterprise claims let the cloud bundle, not a local project entry,
|
||||
// supply the source's distrust decision.
|
||||
fs::write(
|
||||
home.join("auth.json"),
|
||||
serde_json::to_vec(&serde_json::json!({
|
||||
"auth_mode": "chatgpt",
|
||||
"tokens": {
|
||||
"id_token": "e30.eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF9wbGFuX3R5cGUiOiJlbnRlcnByaXNlIiwiY2hhdGdwdF9hY2NvdW50X2lkIjoid29ya3NwYWNlLTEyMyIsImNoYXRncHRfdXNlcl9pZCI6InVzZXItMTIzIn19.signature",
|
||||
"access_token": "test-access-token",
|
||||
"refresh_token": "test-refresh-token",
|
||||
"account_id": "workspace-123"
|
||||
}
|
||||
}))?,
|
||||
)?;
|
||||
fs::write(
|
||||
home.join("config.toml"),
|
||||
format!(
|
||||
"features.worktrees=true\ncli_auth_credentials_store=\"file\"\nchatgpt_base_url=\"{}/backend-api\"\n",
|
||||
server.uri(),
|
||||
),
|
||||
)?;
|
||||
wiremock::Mock::given(wiremock::matchers::method("GET"))
|
||||
.and(wiremock::matchers::path("/backend-api/wham/config/bundle"))
|
||||
.respond_with(
|
||||
wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"config_toml": { "enterprise_managed": [{
|
||||
"id": "source-trust", "name": "Source trust",
|
||||
"contents": format!(
|
||||
"[projects.{}]\ntrust_level=\"untrusted\"\n[projects.{}]\ntrust_level=\"untrusted\"\n",
|
||||
serde_json::to_string(&source)?,
|
||||
serde_json::to_string(&legacy.cwd.join("extra"))?,
|
||||
)
|
||||
}] }
|
||||
})),
|
||||
)
|
||||
.mount(&server)
|
||||
.await;
|
||||
for args in [vec!["prompt"], vec!["fork", legacy_id.as_str(), "prompt"]] {
|
||||
let request_count = if args.first() == Some(&"fork") {
|
||||
// The saved checkout can choose file auth even when the launcher does not.
|
||||
fs::remove_file(source.join(".codex/config.toml"))?;
|
||||
fs::create_dir_all(legacy.cwd.join(".codex"))?;
|
||||
fs::write(
|
||||
legacy.cwd.join(".codex/config.toml"),
|
||||
"cli_auth_credentials_store=\"file\"\n",
|
||||
)?;
|
||||
git(&legacy.cwd, &["add", ".codex/config.toml"])?;
|
||||
git(
|
||||
&legacy.cwd,
|
||||
&["commit", "--quiet", "--no-gpg-sign", "-m", "file auth"],
|
||||
)?;
|
||||
fs::write(
|
||||
home.join("config.toml"),
|
||||
format!(
|
||||
"features.worktrees=true\ncli_auth_credentials_store=\"ephemeral\"\nchatgpt_base_url=\"{}/backend-api\"\n[projects.{}]\ntrust_level=\"trusted\"\n",
|
||||
server.uri(),
|
||||
serde_json::to_string(&source)?,
|
||||
),
|
||||
)?;
|
||||
let cache = home.join("cloud-config-bundle-cache.json");
|
||||
if cache.exists() {
|
||||
fs::remove_file(&cache)?;
|
||||
}
|
||||
Some(server.received_requests().await.context("requests")?.len())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let output = test
|
||||
.cmd()
|
||||
.current_dir(if request_count.is_some() {
|
||||
launcher.path()
|
||||
} else {
|
||||
&source
|
||||
})
|
||||
.env_remove("CODEX_API_KEY")
|
||||
.env_remove("OPENAI_API_KEY")
|
||||
.env_remove("CODEX_ACCESS_TOKEN")
|
||||
.args(["--json", "--worktree", "--strict-config"])
|
||||
.args(args)
|
||||
.output()?;
|
||||
assert!(
|
||||
!output.status.success()
|
||||
&& String::from_utf8_lossy(&output.stderr).contains("explicitly untrusted"),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
if let Some(request_count) = request_count {
|
||||
assert!(!String::from_utf8_lossy(&output.stdout).contains("thread.started"));
|
||||
let denied_manager =
|
||||
WorktreeManager::new(WorktreeSettings::for_cli(&home, /*desktop*/ None)?);
|
||||
let checkout = denied_manager
|
||||
.list(&legacy.cwd)?
|
||||
.into_iter()
|
||||
.next()
|
||||
.context("denied checkout remains for manual removal")?;
|
||||
assert_eq!(denied_manager.owner(&checkout.root)?, None);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
assert!(
|
||||
stderr.contains(
|
||||
checkout
|
||||
.root
|
||||
.file_name()
|
||||
.context("checkout name")?
|
||||
.to_string_lossy()
|
||||
.as_ref()
|
||||
)
|
||||
);
|
||||
assert!(stderr.contains("Remove it manually with `git worktree remove`"));
|
||||
assert!(
|
||||
server
|
||||
.received_requests()
|
||||
.await
|
||||
.context("requests")?
|
||||
.iter()
|
||||
.skip(request_count)
|
||||
.any(|request| request.url.path() == "/backend-api/wham/config/bundle")
|
||||
);
|
||||
} else {
|
||||
assert!(!home.join("worktrees").exists());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worktree_rejects_remote_defaults_before_allocation() -> anyhow::Result<()> {
|
||||
for route in ["environment", "file"] {
|
||||
let test = test_codex_exec();
|
||||
let mut command = test.cmd();
|
||||
if route == "environment" {
|
||||
command.env("CODEX_EXEC_SERVER_URL", "ws://127.0.0.1:9");
|
||||
} else {
|
||||
fs::write(
|
||||
test.home_path().join("environments.toml"),
|
||||
"default = 'remote'\n[[environments]]\nid = 'remote'\nurl = 'ws://127.0.0.1:9'\n",
|
||||
)?;
|
||||
}
|
||||
let output = command
|
||||
.args(["--worktree", "-c", "features.worktrees=true", "prompt"])
|
||||
.output()?;
|
||||
assert!(!output.status.success(), "{route}");
|
||||
assert!(
|
||||
String::from_utf8_lossy(&output.stderr).contains("--worktree requires local execution"),
|
||||
"{route}: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert!(!test.home_path().join("worktrees").exists(), "{route}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worktree_rejects_ignored_config_before_allocation() -> anyhow::Result<()> {
|
||||
let test = test_codex_exec();
|
||||
let output = test
|
||||
.cmd()
|
||||
.args(["--worktree", "--ignore-user-config", "prompt"])
|
||||
.output()?;
|
||||
assert!(!output.status.success());
|
||||
assert!(
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
.contains("--worktree cannot be combined with --ignore-user-config")
|
||||
);
|
||||
assert!(!test.home_path().join("worktrees").exists());
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user