From 1d8a8daf67e85fc1d61ef5e559287a66769c9116 Mon Sep 17 00:00:00 2001 From: Chris Bookholt Date: Mon, 29 Jun 2026 17:00:22 -0700 Subject: [PATCH] Address generic Git safety review --- codex-rs/core/src/exec_policy.rs | 8 +- codex-rs/core/src/exec_policy_tests.rs | 42 +++- .../tools/runtimes/shell/unix_escalation.rs | 147 +++++++++++++- .../runtimes/shell/unix_escalation_tests.rs | 188 ++++++++++++++++++ codex-rs/core/tests/suite/exec_policy.rs | 120 +++++++++++ 5 files changed, 496 insertions(+), 9 deletions(-) diff --git a/codex-rs/core/src/exec_policy.rs b/codex-rs/core/src/exec_policy.rs index ad4c8b8f39..28974f43de 100644 --- a/codex-rs/core/src/exec_policy.rs +++ b/codex-rs/core/src/exec_policy.rs @@ -866,11 +866,15 @@ fn suppress_repo_sensitive_git_amendment( fn starts_with_git_executable(command: &[String]) -> bool { let Some(executable_name) = command .first() - .and_then(|executable| Path::new(executable).file_name()) - .and_then(|name| name.to_str()) + .and_then(|executable| executable.rsplit(['/', '\\']).next()) else { return false; }; + let executable_name = executable_name + .as_bytes() + .get(..2) + .filter(|prefix| prefix[0].is_ascii_alphabetic() && prefix[1] == b':') + .map_or(executable_name, |_| &executable_name[2..]); let executable_name = executable_name.to_ascii_lowercase(); let executable_name = [".exe", ".cmd", ".bat", ".com"] .into_iter() diff --git a/codex-rs/core/src/exec_policy_tests.rs b/codex-rs/core/src/exec_policy_tests.rs index 1becceda6f..6b289c97ff 100644 --- a/codex-rs/core/src/exec_policy_tests.rs +++ b/codex-rs/core/src/exec_policy_tests.rs @@ -1196,6 +1196,41 @@ fn path_qualified_safe_basename_requires_approval_for_untrusted_projects() { ); } +#[test] +fn git_executable_detection_is_platform_independent() { + for executable in [ + "git", + "GIT", + "/usr/bin/git", + "/opt/tools/GiT.ExE", + r"C:\Program Files\Git\cmd\git.exe", + r"C:/Program Files/Git/cmd/GIT.CMD", + r"C:git.exe", + r"d:GIT.CmD", + r"..\bin\git.BaT", + r".\git.CoM", + ] { + assert!( + starts_with_git_executable(&[executable.to_string()]), + "expected {executable:?} to be recognized as Git" + ); + } + + for executable in [ + "git-lfs", + "legit", + "git.exe.old", + "/usr/bin/git/", + r"C:\tools\git.exe\helper", + r"C:notgit.exe", + ] { + assert!( + !starts_with_git_executable(&[executable.to_string()]), + "expected {executable:?} not to be recognized as Git" + ); + } +} + #[tokio::test] async fn generic_git_policy_matrix_preserves_sandbox_and_escalation_semantics() { let command = vec!["git".to_string(), "status".to_string()]; @@ -1306,13 +1341,10 @@ async fn generic_git_never_offers_requested_or_shell_lowered_durable_amendments( ], None, ), + (vec!["/usr/bin/git".to_string(), "status".to_string()], None), ( vec![ - if cfg!(windows) { - r"C:\Program Files\Git\cmd\git.exe".to_string() - } else { - "/usr/bin/git".to_string() - }, + r"C:\Program Files\Git\cmd\GIT.EXE".to_string(), "status".to_string(), ], None, diff --git a/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs b/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs index 10cb460205..34f040d13d 100644 --- a/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs +++ b/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs @@ -68,7 +68,10 @@ use codex_shell_escalation::Stopwatch; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_path_uri::PathUri; use std::collections::HashMap; +use std::ffi::CString; use std::io; +use std::os::unix::ffi::OsStrExt; +use std::path::Path; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; @@ -245,6 +248,11 @@ pub(super) async fn try_run_zsh_fork( sandbox_permissions: req.sandbox_permissions, approval_sandbox_permissions, prompt_permissions: req.additional_permissions.clone(), + trusted_executable_dirs: trusted_executable_dirs( + &command_executor.env, + &command_executor.file_system_sandbox_policy, + &command_executor.cwd, + ), stopwatch: stopwatch.clone(), }; @@ -332,6 +340,11 @@ pub(crate) async fn prepare_unified_exec_zsh_fork( req.additional_permissions_preapproved, ), prompt_permissions: req.additional_permissions.clone(), + trusted_executable_dirs: trusted_executable_dirs( + &command_executor.env, + &command_executor.file_system_sandbox_policy, + &command_executor.cwd, + ), stopwatch: Stopwatch::unlimited(), }; @@ -364,6 +377,7 @@ struct CoreShellActionProvider { sandbox_permissions: SandboxPermissions, approval_sandbox_permissions: SandboxPermissions, prompt_permissions: Option, + trusted_executable_dirs: Vec, stopwatch: Stopwatch, } @@ -655,6 +669,8 @@ impl CoreShellActionProvider { sandbox_permissions: self.approval_sandbox_permissions, enable_shell_wrapper_parsing: ENABLE_INTERCEPTED_EXEC_POLICY_SHELL_WRAPPER_PARSING, + trusted_executable_dirs: self.trusted_executable_dirs.clone(), + cwd: workdir.clone(), }, ) }; @@ -723,27 +739,51 @@ fn evaluate_intercepted_exec_policy( windows_sandbox_level, sandbox_permissions, enable_shell_wrapper_parsing, + trusted_executable_dirs, + cwd, } = context; + let file_system_sandbox_policy = permission_profile.file_system_sandbox_policy(); let CandidateCommands { commands, used_complex_parsing, + trusted_executable_name, } = if enable_shell_wrapper_parsing { // In this codepath, the first argument in `commands` could be a bare // name like `find` instead of an absolute path like `/usr/bin/find`. // It could also be a shell built-in like `echo`. - commands_for_intercepted_exec_policy(program, argv) + commands_for_intercepted_exec_policy( + program, + argv, + &trusted_executable_dirs, + &file_system_sandbox_policy, + &cwd, + ) } else { // In this codepath, `commands` has a single entry where the program // is always an absolute path. CandidateCommands { commands: vec![join_program_and_argv(program, argv)], used_complex_parsing: false, + trusted_executable_name: trusted_intercepted_executable_name( + program, + argv, + &trusted_executable_dirs, + &file_system_sandbox_policy, + &cwd, + ), } }; let fallback = |cmd: &[String]| { + let normalized_fallback_command = trusted_executable_name.as_ref().map(|name| { + let mut normalized = cmd.to_vec(); + if let Some(executable) = normalized.first_mut() { + *executable = name.clone(); + } + normalized + }); crate::exec_policy::render_decision_for_unmatched_command( - cmd, + normalized_fallback_command.as_deref().unwrap_or(cmd), crate::exec_policy::UnmatchedCommandContext { approval_policy, permission_profile: &permission_profile, @@ -771,16 +811,28 @@ struct InterceptedExecPolicyContext { windows_sandbox_level: WindowsSandboxLevel, sandbox_permissions: SandboxPermissions, enable_shell_wrapper_parsing: bool, + trusted_executable_dirs: Vec, + cwd: AbsolutePathBuf, } struct CandidateCommands { commands: Vec>, used_complex_parsing: bool, + trusted_executable_name: Option, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +struct TrustedExecutableDir { + path: PathBuf, + canonical_path: PathBuf, } fn commands_for_intercepted_exec_policy( program: &AbsolutePathBuf, argv: &[String], + trusted_executable_dirs: &[TrustedExecutableDir], + file_system_sandbox_policy: &FileSystemSandboxPolicy, + cwd: &AbsolutePathBuf, ) -> CandidateCommands { if let [_, flag, script] = argv { let shell_command = [ @@ -792,12 +844,14 @@ fn commands_for_intercepted_exec_policy( return CandidateCommands { commands, used_complex_parsing: false, + trusted_executable_name: None, }; } if let Some(single_command) = parse_shell_lc_single_command_prefix(&shell_command) { return CandidateCommands { commands: vec![single_command], used_complex_parsing: true, + trusted_executable_name: None, }; } } @@ -805,9 +859,98 @@ fn commands_for_intercepted_exec_policy( CandidateCommands { commands: vec![join_program_and_argv(program, argv)], used_complex_parsing: false, + trusted_executable_name: trusted_intercepted_executable_name( + program, + argv, + trusted_executable_dirs, + file_system_sandbox_policy, + cwd, + ), } } +fn trusted_executable_dirs( + env: &HashMap, + file_system_sandbox_policy: &FileSystemSandboxPolicy, + cwd: &AbsolutePathBuf, +) -> Vec { + env.get("PATH") + .into_iter() + .flat_map(std::env::split_paths) + .filter(|path| path.is_absolute()) + .filter_map(|path| { + if agent_can_write_path(file_system_sandbox_policy, cwd, &path) { + return None; + } + let canonical_path = std::fs::canonicalize(&path).ok()?; + if agent_can_write_path(file_system_sandbox_policy, cwd, &canonical_path) { + return None; + } + Some(TrustedExecutableDir { + path, + canonical_path, + }) + }) + .collect() +} + +fn trusted_intercepted_executable_name( + program: &AbsolutePathBuf, + argv: &[String], + trusted_executable_dirs: &[TrustedExecutableDir], + file_system_sandbox_policy: &FileSystemSandboxPolicy, + cwd: &AbsolutePathBuf, +) -> Option { + let argv_zero = argv.first()?; + let argv_zero_path = Path::new(argv_zero); + let is_bare_name = argv_zero_path.components().count() == 1; + let resolved_name_matches = program.as_path().file_name() == Some(argv_zero_path.as_os_str()); + let resolved_from_trusted_path = program.as_path().parent().is_some_and(|parent| { + trusted_executable_dirs.iter().any(|directory| { + directory.path == parent + && std::fs::canonicalize(&directory.path) + .is_ok_and(|canonical_path| canonical_path == directory.canonical_path) + }) + }); + let resolved_target_is_read_only = + std::fs::canonicalize(program.as_path()) + .ok() + .is_some_and(|canonical_program| { + !agent_can_write_path(file_system_sandbox_policy, cwd, &canonical_program) + }); + + if is_bare_name + && resolved_name_matches + && resolved_from_trusted_path + && resolved_target_is_read_only + { + Some(argv_zero.clone()) + } else { + None + } +} + +fn agent_can_write_path( + file_system_sandbox_policy: &FileSystemSandboxPolicy, + cwd: &AbsolutePathBuf, + path: &Path, +) -> bool { + if !file_system_sandbox_policy.has_full_disk_write_access() { + return path.ancestors().any(|ancestor| { + file_system_sandbox_policy.can_write_path_with_cwd(ancestor, cwd.as_path()) + }); + } + + path.ancestors().any(|ancestor| { + let Ok(ancestor) = CString::new(ancestor.as_os_str().as_bytes()) else { + return true; + }; + // SAFETY: `ancestor` is a NUL-terminated C string that remains alive + // for the duration of this read-only access check. + unsafe { libc::access(ancestor.as_ptr(), libc::W_OK) == 0 } + }) +} + struct CoreShellCommandExecutor { command: Vec, cwd: AbsolutePathBuf, diff --git a/codex-rs/core/src/tools/runtimes/shell/unix_escalation_tests.rs b/codex-rs/core/src/tools/runtimes/shell/unix_escalation_tests.rs index 5478c1d946..505824018e 100644 --- a/codex-rs/core/src/tools/runtimes/shell/unix_escalation_tests.rs +++ b/codex-rs/core/src/tools/runtimes/shell/unix_escalation_tests.rs @@ -7,6 +7,7 @@ use super::evaluate_intercepted_exec_policy; use super::extract_shell_script; use super::join_program_and_argv; use super::map_exec_result; +use super::trusted_executable_dirs; use crate::config::Constrained; use crate::sandboxing::SandboxPermissions; use crate::session::tests::make_session_and_context; @@ -42,6 +43,8 @@ use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; use serde_json::Value; use std::collections::HashMap; +use std::os::unix::fs::PermissionsExt; +use std::path::Path; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; @@ -250,6 +253,9 @@ fn commands_for_intercepted_exec_policy_parses_plain_shell_wrappers() { let candidate_commands = commands_for_intercepted_exec_policy( &program, &["not-bash".into(), "-lc".into(), "git status && pwd".into()], + &[], + &read_only_file_system_sandbox_policy(), + &test_sandbox_cwd(), ); assert_eq!( @@ -260,6 +266,172 @@ fn commands_for_intercepted_exec_policy_parses_plain_shell_wrappers() { ] ); assert!(!candidate_commands.used_complex_parsing); + assert_eq!(candidate_commands.trusted_executable_name, None); +} + +fn intercepted_unless_trusted_decision( + program: &Path, + argv: &[&str], + permission_profile: PermissionProfile, + cwd: &Path, + path_dirs: &[&Path], +) -> Decision { + let cwd = AbsolutePathBuf::from_absolute_path(cwd).unwrap(); + let mut env = HashMap::new(); + env.insert( + "PATH".to_string(), + std::env::join_paths(path_dirs) + .unwrap() + .into_string() + .unwrap(), + ); + let trusted_executable_dirs = + trusted_executable_dirs(&env, &permission_profile.file_system_sandbox_policy(), &cwd); + evaluate_intercepted_exec_policy( + &PolicyParser::new().build(), + &AbsolutePathBuf::from_absolute_path(program).unwrap(), + &argv + .iter() + .map(|arg| (*arg).to_string()) + .collect::>(), + InterceptedExecPolicyContext { + approval_policy: AskForApproval::UnlessTrusted, + permission_profile, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + sandbox_permissions: SandboxPermissions::UseDefault, + enable_shell_wrapper_parsing: false, + trusted_executable_dirs, + cwd, + }, + ) + .decision +} + +#[test] +fn trusted_executable_dirs_exclude_sandbox_writable_ancestor() { + let workspace = tempfile::tempdir().unwrap(); + let locked = workspace.path().join("locked"); + let bin = locked.join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o555)).unwrap(); + std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o555)).unwrap(); + let cwd = AbsolutePathBuf::from_absolute_path(workspace.path()).unwrap(); + let permission_profile = PermissionProfile::workspace_write(); + let mut env = HashMap::new(); + env.insert("PATH".to_string(), bin.display().to_string()); + + assert!( + trusted_executable_dirs(&env, &permission_profile.file_system_sandbox_policy(), &cwd) + .is_empty() + ); + + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap(); + std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap(); +} + +#[test] +fn intercepted_exec_policy_normalizes_only_trusted_bare_path_resolution() { + let trusted_program_path = ["/bin/ls", "/usr/bin/ls"] + .into_iter() + .find(|path| Path::new(path).is_file()) + .expect("test host should provide ls"); + let trusted_program = Path::new(trusted_program_path); + let trusted_dir = trusted_program.parent().expect("ls should have a parent"); + + for profile in [ + PermissionProfile::workspace_write(), + PermissionProfile::Disabled, + ] { + assert_eq!( + intercepted_unless_trusted_decision( + trusted_program, + &["ls", "."], + profile, + Path::new("/workspace"), + &[trusted_dir], + ), + Decision::Allow + ); + } + + for argv in [ + ["./ls"].as_slice(), + [trusted_program_path].as_slice(), + ["not-ls"].as_slice(), + ] { + assert_eq!( + intercepted_unless_trusted_decision( + trusted_program, + argv, + PermissionProfile::workspace_write(), + Path::new("/workspace"), + &[trusted_dir], + ), + Decision::Prompt + ); + } + + let writable_path = tempfile::tempdir().unwrap(); + let shadow_program_path = writable_path.path().join("ls"); + std::fs::write(&shadow_program_path, "not a trusted host executable").unwrap(); + for profile in [ + PermissionProfile::workspace_write(), + PermissionProfile::Disabled, + ] { + assert_eq!( + intercepted_unless_trusted_decision( + &shadow_program_path, + &["ls"], + profile, + writable_path.path(), + &[writable_path.path()], + ), + Decision::Prompt + ); + } +} + +#[test] +fn intercepted_exec_policy_rejects_symlink_into_writable_target() { + let root = tempfile::tempdir().unwrap(); + let trusted_bin = root.path().join("trusted-bin"); + let writable_dir = root.path().join("writable"); + std::fs::create_dir_all(&trusted_bin).unwrap(); + std::fs::create_dir_all(&writable_dir).unwrap(); + let trusted_bin = std::fs::canonicalize(trusted_bin).unwrap(); + let writable_dir = std::fs::canonicalize(writable_dir).unwrap(); + let writable_target = writable_dir.join("ls"); + std::fs::write(&writable_target, "attacker controlled").unwrap(); + let linked_program = trusted_bin.join("ls"); + std::os::unix::fs::symlink(&writable_target, &linked_program).unwrap(); + + let cwd = AbsolutePathBuf::from_absolute_path(&writable_dir).unwrap(); + let file_system_sandbox_policy = FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + access: FileSystemAccessMode::Read, + }, + FileSystemSandboxEntry { + path: FileSystemPath::Path { path: cwd.clone() }, + access: FileSystemAccessMode::Write, + }, + ]); + let permission_profile = PermissionProfile::from_runtime_permissions( + &file_system_sandbox_policy, + NetworkSandboxPolicy::Restricted, + ); + assert_eq!( + intercepted_unless_trusted_decision( + &linked_program, + &["ls"], + permission_profile, + cwd.as_path(), + &[&trusted_bin], + ), + Decision::Prompt + ); } #[test] @@ -434,6 +606,7 @@ async fn preapproved_additional_permissions_escalate_intercepted_exec() -> anyho sandbox_permissions: SandboxPermissions::WithAdditionalPermissions, approval_sandbox_permissions: SandboxPermissions::UseDefault, prompt_permissions: Some(requested_permissions), + trusted_executable_dirs: Vec::new(), stopwatch: codex_shell_escalation::Stopwatch::new(Duration::from_secs(1)), }; @@ -570,6 +743,7 @@ async fn execve_permission_request_hook_short_circuits_prompt() -> anyhow::Resul sandbox_permissions: SandboxPermissions::RequireEscalated, approval_sandbox_permissions: SandboxPermissions::RequireEscalated, prompt_permissions: None, + trusted_executable_dirs: Vec::new(), stopwatch: codex_shell_escalation::Stopwatch::new(Duration::from_secs(1)), }; @@ -634,6 +808,8 @@ fn evaluate_intercepted_exec_policy_uses_wrapper_command_when_shell_wrapper_pars windows_sandbox_level: WindowsSandboxLevel::Disabled, sandbox_permissions: SandboxPermissions::UseDefault, enable_shell_wrapper_parsing: enable_intercepted_exec_policy_shell_wrapper_parsing, + trusted_executable_dirs: Vec::new(), + cwd: test_sandbox_cwd(), }, ); @@ -685,6 +861,8 @@ fn evaluate_intercepted_exec_policy_matches_inner_shell_commands_when_enabled() windows_sandbox_level: WindowsSandboxLevel::Disabled, sandbox_permissions: SandboxPermissions::UseDefault, enable_shell_wrapper_parsing: enable_intercepted_exec_policy_shell_wrapper_parsing, + trusted_executable_dirs: Vec::new(), + cwd: test_sandbox_cwd(), }, ); @@ -727,6 +905,8 @@ host_executable(name = "git", paths = ["{git_path_literal}"]) windows_sandbox_level: WindowsSandboxLevel::Disabled, sandbox_permissions: SandboxPermissions::UseDefault, enable_shell_wrapper_parsing: false, + trusted_executable_dirs: Vec::new(), + cwd: test_sandbox_cwd(), }, ); @@ -781,6 +961,7 @@ prefix_rule(pattern = ["{cat_path_literal}"], decision = "allow") sandbox_permissions: SandboxPermissions::UseDefault, approval_sandbox_permissions: SandboxPermissions::UseDefault, prompt_permissions: None, + trusted_executable_dirs: Vec::new(), stopwatch: codex_shell_escalation::Stopwatch::new(Duration::from_secs(1)), }; @@ -824,6 +1005,7 @@ async fn denied_reads_keep_granular_sandbox_rejection_for_escalation() -> anyhow sandbox_permissions: SandboxPermissions::RequireEscalated, approval_sandbox_permissions: SandboxPermissions::RequireEscalated, prompt_permissions: None, + trusted_executable_dirs: Vec::new(), stopwatch: codex_shell_escalation::Stopwatch::new(Duration::from_secs(1)), }; @@ -865,6 +1047,8 @@ fn intercepted_exec_policy_treats_preapproved_additional_permissions_as_default( /*additional_permissions_preapproved*/ true, ), enable_shell_wrapper_parsing: false, + trusted_executable_dirs: Vec::new(), + cwd: test_sandbox_cwd(), }, ); let fresh_request = evaluate_intercepted_exec_policy( @@ -877,6 +1061,8 @@ fn intercepted_exec_policy_treats_preapproved_additional_permissions_as_default( windows_sandbox_level: WindowsSandboxLevel::Disabled, sandbox_permissions: SandboxPermissions::WithAdditionalPermissions, enable_shell_wrapper_parsing: false, + trusted_executable_dirs: Vec::new(), + cwd: test_sandbox_cwd(), }, ); @@ -910,6 +1096,8 @@ host_executable(name = "git", paths = ["{allowed_git_literal}"]) windows_sandbox_level: WindowsSandboxLevel::Disabled, sandbox_permissions: SandboxPermissions::UseDefault, enable_shell_wrapper_parsing: false, + trusted_executable_dirs: Vec::new(), + cwd: test_sandbox_cwd(), }, ); diff --git a/codex-rs/core/tests/suite/exec_policy.rs b/codex-rs/core/tests/suite/exec_policy.rs index 4e64c66b0a..4709cc802b 100644 --- a/codex-rs/core/tests/suite/exec_policy.rs +++ b/codex-rs/core/tests/suite/exec_policy.rs @@ -9,6 +9,7 @@ use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; +use codex_protocol::protocol::ReviewDecision; use codex_protocol::user_input::UserInput; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; @@ -21,6 +22,7 @@ use core_test_support::test_codex::local_selections; use core_test_support::test_codex::test_codex; use core_test_support::test_codex::turn_permission_fields; use core_test_support::wait_for_event; +use pretty_assertions::assert_eq; use serde_json::Value; use serde_json::json; use std::fs; @@ -88,6 +90,124 @@ fn assert_no_matched_rules_invariant(output_item: &Value) { ); } +#[derive(Clone, Copy, Debug)] +enum AgentExecTool { + Shell, + UnifiedExec, +} + +async fn assert_generic_git_prompts_without_amendment(tool: AgentExecTool) -> Result<()> { + let server = start_mock_server().await; + let mut builder = test_codex().with_config(move |config| { + if matches!(tool, AgentExecTool::UnifiedExec) { + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); + } + }); + let test = builder.build(&server).await?; + let (call_id, tool_name, args) = match tool { + AgentExecTool::Shell => ( + "git-approval-shell", + "shell_command", + json!({ + "command": "git status --short", + "timeout_ms": 1_000, + }), + ), + AgentExecTool::UnifiedExec => ( + "git-approval-unified-exec", + "exec_command", + json!({ + "cmd": "git status --short", + "yield_time_ms": 1_000, + }), + ), + }; + + mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-git-approval-1"), + ev_function_call(call_id, tool_name, &serde_json::to_string(&args)?), + ev_completed("resp-git-approval-1"), + ]), + ) + .await; + let results_mock = mount_sse_once( + &server, + sse(vec![ + ev_assistant_message("msg-git-approval-1", "done"), + ev_completed("resp-git-approval-2"), + ]), + ) + .await; + + submit_user_turn( + &test, + "run repository-sensitive git status", + AskForApproval::UnlessTrusted, + PermissionProfile::Disabled, + None, + ) + .await?; + + let approval_event = wait_for_event(&test.codex, |event| { + matches!( + event, + EventMsg::ExecApprovalRequest(_) | EventMsg::TurnComplete(_) + ) + }) + .await; + let EventMsg::ExecApprovalRequest(approval) = approval_event else { + panic!("{tool:?} git command completed without requesting approval"); + }; + assert_eq!(approval.proposed_execpolicy_amendment, None); + assert!( + approval + .command + .iter() + .any(|argument| argument.contains("git status --short")), + "unexpected {tool:?} approval command: {:?}", + approval.command + ); + + test.codex + .submit(Op::ExecApproval { + id: approval.effective_approval_id(), + turn_id: None, + decision: ReviewDecision::Denied, + }) + .await?; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; + + let output_item = results_mock.single_request().function_call_output(call_id); + let output = output_item + .get("output") + .and_then(Value::as_str) + .expect("function call output should include a string output payload"); + assert!( + output.contains("rejected by user"), + "unexpected {tool:?} denial output: {output}" + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn generic_git_shell_command_prompts_without_amendment() -> Result<()> { + assert_generic_git_prompts_without_amendment(AgentExecTool::Shell).await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn generic_git_unified_exec_prompts_without_amendment() -> Result<()> { + assert_generic_git_prompts_without_amendment(AgentExecTool::UnifiedExec).await +} + #[cfg(windows)] #[tokio::test] async fn unified_exec_disabled_windows_sandbox_rejects_managed_read_only_command() -> Result<()> {