mirror of
https://github.com/openai/codex.git
synced 2026-09-11 20:36:49 +00:00
## Why An `apply_patch` path can be replaced with a symlink after verification, allowing an unsandboxed patch operation to reach a different file than the one that was approved. ## What changed - Add `follow_symlinks` options to executor filesystem reads, writes, metadata lookups, directory creation, and removal, including the corresponding `followSymlinks` protocol fields. - Implement no-follow filesystem operations on Unix and Windows that reject links in any path component and restrict file access to regular files. - Run `apply_patch` with symlink traversal disabled when an otherwise-required sandbox is bypassed, while retaining the existing follow-symlink default for standalone callers. ## Testing - Cover leaf and ancestor symlinks across patch add, update, delete, and move operations, including a path swap after verification. - Exercise local and remote no-follow filesystem behavior, concurrent directory creation, special-file rejection, and Windows reparse points. GitOrigin-RevId: 43fd479084891493ce13564fbd894b98f329c6dd
324 lines
11 KiB
Rust
324 lines
11 KiB
Rust
use std::path::Path;
|
|
use std::time::Duration;
|
|
|
|
use anyhow::Context;
|
|
use anyhow::Result;
|
|
use app_test_support::MockResponsesConfig;
|
|
use app_test_support::PathBufExt;
|
|
use app_test_support::TestAppServer;
|
|
use app_test_support::create_final_assistant_message_sse_response;
|
|
use app_test_support::create_mock_responses_server_sequence;
|
|
use codex_app_server_protocol::ThreadStartParams;
|
|
use codex_app_server_protocol::ThreadStartResponse;
|
|
use codex_app_server_protocol::TurnStartParams;
|
|
use codex_app_server_protocol::UserInput as V2UserInput;
|
|
use codex_features::Feature;
|
|
use codex_shell_command::shell_detect::ShellType;
|
|
use codex_shell_command::shell_detect::detect_shell_type;
|
|
use core_test_support::responses;
|
|
use pretty_assertions::assert_eq;
|
|
use serde_json::json;
|
|
use tempfile::TempDir;
|
|
use tokio::time::timeout;
|
|
|
|
const AGENTS_INSTRUCTIONS: &str = "selected environment workspace instructions";
|
|
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(10);
|
|
|
|
fn write_mock_config(codex_home: &Path, server_uri: &str) -> std::io::Result<()> {
|
|
MockResponsesConfig::new(server_uri)
|
|
.with_root_config("compact_prompt = \"compact\"\nmodel_auto_compact_token_limit = 100000")
|
|
.with_provider_config("supports_websockets = false")
|
|
.write(codex_home)
|
|
}
|
|
|
|
fn text_turn_params(thread_id: String, prompt: &str) -> TurnStartParams {
|
|
TurnStartParams {
|
|
thread_id,
|
|
input: vec![V2UserInput::Text {
|
|
text: prompt.to_string(),
|
|
text_elements: Vec::new(),
|
|
}],
|
|
..Default::default()
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn thread_start_reports_selected_environment_metadata() -> Result<()> {
|
|
let server = responses::start_mock_server().await;
|
|
let codex_home = TempDir::new()?;
|
|
write_mock_config(codex_home.path(), &server.uri())?;
|
|
let mut app_server = TestAppServer::builder()
|
|
.with_codex_home(codex_home.path())
|
|
.build_initialized()
|
|
.await?;
|
|
let selected_workspace_roots = app_server
|
|
.auto_env()?
|
|
.selection()
|
|
.workspace_roots
|
|
.iter()
|
|
.filter_map(|root| root.to_abs_path().ok())
|
|
.collect::<Vec<_>>();
|
|
|
|
let ThreadStartResponse {
|
|
cwd,
|
|
runtime_workspace_roots,
|
|
active_permission_profile,
|
|
..
|
|
} = app_server
|
|
.start_thread(ThreadStartParams::default())
|
|
.await?;
|
|
let host_cwd = codex_home.path().to_path_buf().abs().canonicalize()?;
|
|
let cwd = cwd.canonicalize()?;
|
|
assert_eq!(
|
|
(cwd, runtime_workspace_roots, active_permission_profile),
|
|
(
|
|
// TODO(anp): Return the selected environment's native cwd from thread/start.
|
|
host_cwd,
|
|
selected_workspace_roots,
|
|
// TODO(anp): Report the implicit built-in permission profile instead of None.
|
|
None,
|
|
)
|
|
);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn thread_start_reports_selected_environment_instruction_source() -> Result<()> {
|
|
let server = responses::start_mock_server().await;
|
|
let response_mock = responses::mount_sse_once(
|
|
&server,
|
|
responses::sse(vec![
|
|
responses::ev_response_created("resp-1"),
|
|
responses::ev_assistant_message("msg-1", "done"),
|
|
responses::ev_completed("resp-1"),
|
|
]),
|
|
)
|
|
.await;
|
|
let codex_home = TempDir::new()?;
|
|
write_mock_config(codex_home.path(), &server.uri())?;
|
|
let mut app_server = TestAppServer::builder()
|
|
.with_codex_home(codex_home.path())
|
|
.build_initialized()
|
|
.await?;
|
|
|
|
let (agents_source, environment_cwd) = {
|
|
let auto_env = app_server.auto_env()?;
|
|
let environment_cwd = auto_env.selection().cwd.clone();
|
|
let agents_source = environment_cwd.join("AGENTS.md")?;
|
|
auto_env
|
|
.environment()
|
|
.get_filesystem()
|
|
.write_file(
|
|
&agents_source,
|
|
AGENTS_INSTRUCTIONS.as_bytes().to_vec(),
|
|
Default::default(),
|
|
/*sandbox*/ None,
|
|
)
|
|
.await?;
|
|
(agents_source, environment_cwd)
|
|
};
|
|
|
|
let response = app_server
|
|
.start_thread(ThreadStartParams::default())
|
|
.await?;
|
|
|
|
assert_eq!(response.instruction_sources, vec![agents_source.into()]);
|
|
timeout(
|
|
DEFAULT_READ_TIMEOUT,
|
|
app_server.start_turn_and_wait_for_completion(text_turn_params(
|
|
response.thread.id,
|
|
"inspect workspace instructions",
|
|
)),
|
|
)
|
|
.await??;
|
|
|
|
let user_context = response_mock.single_request().message_input_texts("user");
|
|
let instructions = user_context
|
|
.iter()
|
|
.find(|text| text.starts_with("# AGENTS.md instructions"))
|
|
.context("selected environment instructions should be model visible")?;
|
|
let expected_instructions = format!(
|
|
"# AGENTS.md instructions for {}\n\n<INSTRUCTIONS>\n{AGENTS_INSTRUCTIONS}\n</INSTRUCTIONS>",
|
|
environment_cwd.inferred_native_path_string()
|
|
);
|
|
assert_eq!(instructions, &expected_instructions);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn turn_model_context_uses_selected_environment() -> Result<()> {
|
|
let server = responses::start_mock_server().await;
|
|
let response_mock = responses::mount_sse_once(
|
|
&server,
|
|
responses::sse(vec![
|
|
responses::ev_response_created("resp-1"),
|
|
responses::ev_assistant_message("msg-1", "done"),
|
|
responses::ev_completed("resp-1"),
|
|
]),
|
|
)
|
|
.await;
|
|
let codex_home = TempDir::new()?;
|
|
write_mock_config(codex_home.path(), &server.uri())?;
|
|
let mut app_server = TestAppServer::builder()
|
|
.with_codex_home(codex_home.path())
|
|
.build_initialized()
|
|
.await?;
|
|
let (environment_cwd, environment_shell) = {
|
|
let auto_env = app_server.auto_env()?;
|
|
(
|
|
auto_env.selection().cwd.clone(),
|
|
auto_env.environment().info().await?.shell.name,
|
|
)
|
|
};
|
|
|
|
let thread = app_server
|
|
.start_thread(ThreadStartParams::default())
|
|
.await?
|
|
.thread;
|
|
timeout(
|
|
DEFAULT_READ_TIMEOUT,
|
|
app_server.start_turn_and_wait_for_completion(text_turn_params(
|
|
thread.id,
|
|
"inspect the selected environment",
|
|
)),
|
|
)
|
|
.await??;
|
|
|
|
let user_context = response_mock.single_request().message_input_texts("user");
|
|
let environment_context = user_context
|
|
.iter()
|
|
.find(|text| text.starts_with("<environment_context>"))
|
|
.context("selected environment context should be model visible")?;
|
|
let shell = environment_context
|
|
.lines()
|
|
.find(|line| line.trim_start().starts_with("<shell>"))
|
|
.map(str::trim)
|
|
.map(str::to_string);
|
|
let cwd = environment_context
|
|
.lines()
|
|
.find(|line| line.trim_start().starts_with("<cwd>"))
|
|
.map(str::trim)
|
|
.map(str::to_string);
|
|
assert_eq!(
|
|
(shell, cwd),
|
|
(
|
|
Some(format!("<shell>{environment_shell}</shell>")),
|
|
Some(format!(
|
|
"<cwd>{}</cwd>",
|
|
environment_cwd.inferred_native_path_string()
|
|
)),
|
|
)
|
|
);
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn command_execution_notifications_preserve_selected_environment_paths() -> Result<()> {
|
|
let command_arguments = serde_json::to_string(&json!({
|
|
"cmd": "cat main.rs",
|
|
"yield_time_ms": 10_000,
|
|
}))?;
|
|
let server = create_mock_responses_server_sequence(vec![
|
|
responses::sse(vec![
|
|
responses::ev_response_created("resp-1"),
|
|
responses::ev_function_call(
|
|
"selected-environment-read",
|
|
"exec_command",
|
|
&command_arguments,
|
|
),
|
|
responses::ev_completed("resp-1"),
|
|
]),
|
|
create_final_assistant_message_sse_response("done")?,
|
|
])
|
|
.await;
|
|
let codex_home = TempDir::new()?;
|
|
MockResponsesConfig::new(&server.uri())
|
|
.with_root_config("compact_prompt = \"compact\"\nmodel_auto_compact_token_limit = 100000")
|
|
.with_provider_config("supports_websockets = false")
|
|
.with_sandbox_mode("danger-full-access")
|
|
.enable_feature(Feature::UnifiedExec)
|
|
.write(codex_home.path())?;
|
|
let mut app_server = TestAppServer::builder()
|
|
.with_codex_home(codex_home.path())
|
|
.build_initialized()
|
|
.await?;
|
|
|
|
let (expected_path, shell) = {
|
|
let environment = app_server.auto_env()?;
|
|
let path = environment.selection().cwd.join("main.rs")?;
|
|
environment
|
|
.environment()
|
|
.get_filesystem()
|
|
.write_file(
|
|
&path,
|
|
b"fn main() {}\n".to_vec(),
|
|
Default::default(),
|
|
/*sandbox*/ None,
|
|
)
|
|
.await?;
|
|
(
|
|
path.inferred_native_path_string(),
|
|
environment.environment().info().await?.shell,
|
|
)
|
|
};
|
|
let thread = app_server
|
|
.start_thread(ThreadStartParams::default())
|
|
.await?
|
|
.thread;
|
|
timeout(
|
|
DEFAULT_READ_TIMEOUT,
|
|
app_server.start_turn_and_wait_for_completion(text_turn_params(thread.id, "read main.rs")),
|
|
)
|
|
.await??;
|
|
|
|
let expected_actions = match shell.name.as_str() {
|
|
// Windows shell scripts are not yet parsed into file-read command actions.
|
|
"powershell" => {
|
|
let command = if detect_shell_type(&shell.path) == Some(ShellType::PowerShell) {
|
|
"cat main.rs".to_string()
|
|
} else {
|
|
shlex::try_join([shell.path.as_str(), "-Command", "cat main.rs"])?
|
|
};
|
|
json!([{
|
|
"type": "unknown",
|
|
"command": command,
|
|
}])
|
|
}
|
|
"cmd" => {
|
|
let command = shlex::try_join([shell.path.as_str(), "/c", "cat main.rs"])?;
|
|
json!([{
|
|
"type": "unknown",
|
|
"command": command,
|
|
}])
|
|
}
|
|
_ => json!([{
|
|
"type": "read",
|
|
"command": "cat main.rs",
|
|
"name": "main.rs",
|
|
"path": expected_path,
|
|
}]),
|
|
};
|
|
|
|
for method in ["item/started", "item/completed"] {
|
|
let notification = timeout(
|
|
DEFAULT_READ_TIMEOUT,
|
|
app_server.read_stream_until_matching_notification(method, |notification| {
|
|
notification.method == method
|
|
&& notification
|
|
.params
|
|
.as_ref()
|
|
.is_some_and(|params| params["item"]["id"] == "selected-environment-read")
|
|
}),
|
|
)
|
|
.await??;
|
|
let params = notification
|
|
.params
|
|
.context("command execution notification should include params")?;
|
|
assert_eq!(params["item"]["commandActions"], expected_actions);
|
|
}
|
|
|
|
Ok(())
|
|
}
|