From feb9eddc513c318adbda63bd953c1684deb6d8a3 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Mon, 1 Jun 2026 13:22:28 -0700 Subject: [PATCH 1/3] refactor: hide shell override for zsh fork unified exec (#24980) ## Why When unified exec is configured to launch through the zsh fork, local commands should not let the model override the shell binary with the `shell` parameter. The configured zsh fork is the mechanism that makes `execv(2)` interception reliable, so exposing `shell` for local zsh-fork execution would create a confusing API surface and undermine the composition. Remote environments are different: zsh-fork interception is local-only, so remote unified-exec calls must keep direct unified-exec behavior and still expose `shell` when a remote environment can be selected. ## What Changed - Taught the `exec_command` schema builder to omit the `shell` parameter when requested. - Hid `shell` from the unified-exec tool schema only when zsh-fork unified exec applies to all selectable environments. - Kept `shell` visible when any remote environment can be targeted, because those calls run through direct unified exec. - Made unified exec choose the effective shell mode per selected environment: local environments keep zsh-fork mode, remote environments use direct mode. - Left direct unified-exec behavior unchanged, including support for model-specified shells there. ## Verification - Added schema coverage showing `exec_command` can hide `shell`. - Added planner coverage showing zsh-fork unified exec hides `shell` for local-only execution while direct unified exec still exposes it. - Added planner coverage showing `shell` remains visible when a remote environment is available. - Added handler coverage showing remote environments use direct unified-exec shell mode instead of zsh-fork mode. - Ran the focused `codex-core` shell-parameter and zsh-fork tests. --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/openai/codex/pull/24980). * #24982 * #24981 * __->__ #24980 --- .../core/src/tools/handlers/shell_spec.rs | 19 ++-- .../src/tools/handlers/shell_spec_tests.rs | 22 +++++ .../core/src/tools/handlers/unified_exec.rs | 36 ++++++-- .../handlers/unified_exec/exec_command.rs | 9 +- .../src/tools/handlers/unified_exec_tests.rs | 50 ++++++++--- codex-rs/core/src/tools/spec_plan.rs | 13 +++ codex-rs/core/src/tools/spec_plan_tests.rs | 89 +++++++++++++++++++ codex-rs/core/src/unified_exec/mod.rs | 2 + .../core/src/unified_exec/process_manager.rs | 3 +- .../src/unified_exec/process_manager_tests.rs | 1 + 10 files changed, 215 insertions(+), 29 deletions(-) diff --git a/codex-rs/core/src/tools/handlers/shell_spec.rs b/codex-rs/core/src/tools/handlers/shell_spec.rs index 361f73bc04..13c531eaba 100644 --- a/codex-rs/core/src/tools/handlers/shell_spec.rs +++ b/codex-rs/core/src/tools/handlers/shell_spec.rs @@ -13,12 +13,15 @@ pub struct CommandToolOptions { #[cfg(test)] pub fn create_exec_command_tool(options: CommandToolOptions) -> ToolSpec { - create_exec_command_tool_with_environment_id(options, /*include_environment_id*/ false) + create_exec_command_tool_with_environment_id( + options, /*include_environment_id*/ false, /*include_shell_parameter*/ true, + ) } pub(crate) fn create_exec_command_tool_with_environment_id( options: CommandToolOptions, include_environment_id: bool, + include_shell_parameter: bool, ) -> ToolSpec { let mut properties = BTreeMap::from([ ( @@ -32,12 +35,6 @@ pub(crate) fn create_exec_command_tool_with_environment_id( .to_string(), )), ), - ( - "shell".to_string(), - JsonSchema::string(Some( - "Shell binary to launch. Defaults to the user's default shell.".to_string(), - )), - ), ( "tty".to_string(), JsonSchema::boolean(Some( @@ -58,6 +55,14 @@ pub(crate) fn create_exec_command_tool_with_environment_id( )), ), ]); + if include_shell_parameter { + properties.insert( + "shell".to_string(), + JsonSchema::string(Some( + "Shell binary to launch. Defaults to the user's default shell.".to_string(), + )), + ); + } if options.allow_login_shell { properties.insert( "login".to_string(), diff --git a/codex-rs/core/src/tools/handlers/shell_spec_tests.rs b/codex-rs/core/src/tools/handlers/shell_spec_tests.rs index c11f34e927..b7c0db7242 100644 --- a/codex-rs/core/src/tools/handlers/shell_spec_tests.rs +++ b/codex-rs/core/src/tools/handlers/shell_spec_tests.rs @@ -6,6 +6,13 @@ fn windows_shell_guidance_description() -> String { format!("\n\n{}", windows_shell_guidance()) } +fn has_parameter(tool: &ToolSpec, parameter_name: &str) -> bool { + serde_json::to_value(tool) + .expect("tool spec should serialize") + .pointer(&format!("/parameters/properties/{parameter_name}")) + .is_some() +} + #[test] fn exec_command_tool_matches_expected_spec() { let tool = create_exec_command_tool(CommandToolOptions { @@ -88,6 +95,21 @@ fn exec_command_tool_matches_expected_spec() { ); } +#[test] +fn exec_command_tool_can_hide_shell_parameter() { + let tool = create_exec_command_tool_with_environment_id( + CommandToolOptions { + allow_login_shell: true, + exec_permission_approvals_enabled: false, + }, + /*include_environment_id*/ false, + /*include_shell_parameter*/ false, + ); + + assert!(!has_parameter(&tool, "shell")); + assert!(has_parameter(&tool, "cmd")); +} + #[test] fn write_stdin_tool_matches_expected_spec() { let tool = create_write_stdin_tool(); diff --git a/codex-rs/core/src/tools/handlers/unified_exec.rs b/codex-rs/core/src/tools/handlers/unified_exec.rs index 170c1bd72f..6fa2e40685 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec.rs @@ -7,6 +7,7 @@ use crate::tools::context::ToolOutput; use crate::tools::context::ToolPayload; use crate::tools::hook_names::HookToolName; use crate::tools::registry::PostToolUsePayload; +use codex_exec_server::Environment; use codex_protocol::models::AdditionalPermissionProfile; use codex_tools::UnifiedExecShellMode; use serde::Deserialize; @@ -124,14 +125,33 @@ pub(crate) fn get_command( shell_type: shell.shell_type.clone(), }) } - UnifiedExecShellMode::ZshFork(zsh_fork_config) => Ok(ResolvedCommand { - command: vec![ - zsh_fork_config.shell_zsh_path.to_string_lossy().to_string(), - if use_login_shell { "-lc" } else { "-c" }.to_string(), - args.cmd.clone(), - ], - shell_type: ShellType::Zsh, - }), + UnifiedExecShellMode::ZshFork(zsh_fork_config) => { + if args.shell.is_some() { + return Err( + "`shell` is not supported for local zsh-fork exec; omit `shell` to use zsh-fork, or target a remote environment where `shell` is supported.".to_string(), + ); + } + + Ok(ResolvedCommand { + command: vec![ + zsh_fork_config.shell_zsh_path.to_string_lossy().to_string(), + if use_login_shell { "-lc" } else { "-c" }.to_string(), + args.cmd.clone(), + ], + shell_type: ShellType::Zsh, + }) + } + } +} + +pub(crate) fn shell_mode_for_environment( + turn_shell_mode: &UnifiedExecShellMode, + environment: &Environment, +) -> UnifiedExecShellMode { + if environment.is_remote() { + UnifiedExecShellMode::Direct + } else { + turn_shell_mode.clone() } } diff --git a/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs b/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs index 83236881f3..c26fa107c7 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs @@ -38,12 +38,14 @@ use super::ExecCommandArgs; use super::ExecCommandEnvironmentArgs; use super::get_command; use super::post_unified_exec_tool_use_payload; +use super::shell_mode_for_environment; #[derive(Clone, Copy)] pub(crate) struct ExecCommandHandlerOptions { pub(crate) allow_login_shell: bool, pub(crate) exec_permission_approvals_enabled: bool, pub(crate) include_environment_id: bool, + pub(crate) include_shell_parameter: bool, } pub struct ExecCommandHandler { @@ -57,6 +59,7 @@ impl Default for ExecCommandHandler { allow_login_shell: false, exec_permission_approvals_enabled: false, include_environment_id: false, + include_shell_parameter: true, }, } } @@ -81,6 +84,7 @@ impl ToolExecutor for ExecCommandHandler { exec_permission_approvals_enabled: self.options.exec_permission_approvals_enabled, }, self.options.include_environment_id, + self.options.include_shell_parameter, ) } @@ -140,10 +144,12 @@ impl ToolExecutor for ExecCommandHandler { ) .await; let process_id = manager.allocate_process_id().await; + let shell_mode = + shell_mode_for_environment(&turn.unified_exec_shell_mode, environment.as_ref()); let resolved_command = get_command( &args, session.user_shell(), - &turn.unified_exec_shell_mode, + &shell_mode, turn.config.permissions.allow_login_shell, ) .map_err(FunctionCallError::RespondToModel)?; @@ -260,6 +266,7 @@ impl ToolExecutor for ExecCommandHandler { cwd, sandbox_cwd: turn_environment.cwd.clone(), environment, + shell_mode, network: context.turn.network.clone(), tty, sandbox_permissions: effective_additional_permissions.sandbox_permissions, diff --git a/codex-rs/core/src/tools/handlers/unified_exec_tests.rs b/codex-rs/core/src/tools/handlers/unified_exec_tests.rs index 0eb9ebbedb..b33a0e85b0 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec_tests.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec_tests.rs @@ -1,6 +1,7 @@ use super::*; use crate::shell::ShellType; use crate::shell::default_user_shell; +use codex_exec_server::Environment; use codex_tools::UnifiedExecShellMode; use codex_tools::ZshForkConfig; use codex_utils_absolute_path::AbsolutePathBuf; @@ -165,7 +166,7 @@ fn test_get_command_rejects_explicit_login_when_disallowed() -> anyhow::Result<( } #[test] -fn test_get_command_ignores_explicit_shell_in_zsh_fork_mode() -> anyhow::Result<()> { +fn test_get_command_rejects_explicit_shell_in_zsh_fork_mode() -> anyhow::Result<()> { let json = r#"{"cmd": "echo hello", "shell": "/bin/bash"}"#; let args: ExecCommandArgs = parse_arguments(json)?; let shell_zsh_path = AbsolutePathBuf::from_absolute_path(if cfg!(windows) { @@ -174,7 +175,7 @@ fn test_get_command_ignores_explicit_shell_in_zsh_fork_mode() -> anyhow::Result< "/opt/codex/zsh" })?; let shell_mode = UnifiedExecShellMode::ZshFork(ZshForkConfig { - shell_zsh_path: shell_zsh_path.clone(), + shell_zsh_path, main_execve_wrapper_exe: AbsolutePathBuf::from_absolute_path(if cfg!(windows) { r"C:\opt\codex\codex-execve-wrapper" } else { @@ -182,23 +183,50 @@ fn test_get_command_ignores_explicit_shell_in_zsh_fork_mode() -> anyhow::Result< })?, }); - let resolved = get_command( + let err = get_command( &args, Arc::new(default_user_shell()), &shell_mode, /*allow_login_shell*/ true, ) - .map_err(anyhow::Error::msg)?; + .expect_err("explicit shell should be rejected"); + + assert!( + err.contains("`shell` is not supported for local zsh-fork exec"), + "unexpected error: {err}" + ); + Ok(()) +} + +#[tokio::test] +async fn shell_mode_for_environment_uses_direct_mode_for_remote_environments() -> anyhow::Result<()> +{ + let shell_zsh_path = AbsolutePathBuf::from_absolute_path(if cfg!(windows) { + r"C:\opt\codex\zsh" + } else { + "/opt/codex/zsh" + })?; + let shell_mode = UnifiedExecShellMode::ZshFork(ZshForkConfig { + shell_zsh_path, + main_execve_wrapper_exe: AbsolutePathBuf::from_absolute_path(if cfg!(windows) { + r"C:\opt\codex\codex-execve-wrapper" + } else { + "/opt/codex/codex-execve-wrapper" + })?, + }); + let local_environment = Environment::default_for_tests(); + let remote_environment = + Environment::create_for_tests(Some("ws://127.0.0.1:1/remote-exec-server".to_string()))?; assert_eq!( - resolved.command, - vec![ - shell_zsh_path.to_string_lossy().to_string(), - "-lc".to_string(), - "echo hello".to_string() - ] + shell_mode_for_environment(&shell_mode, &local_environment), + shell_mode ); - assert_eq!(resolved.shell_type, ShellType::Zsh); + assert_eq!( + shell_mode_for_environment(&shell_mode, &remote_environment), + UnifiedExecShellMode::Direct + ); + Ok(()) } diff --git a/codex-rs/core/src/tools/spec_plan.rs b/codex-rs/core/src/tools/spec_plan.rs index 3c8abf8f16..c7d9ae5aeb 100644 --- a/codex-rs/core/src/tools/spec_plan.rs +++ b/codex-rs/core/src/tools/spec_plan.rs @@ -73,6 +73,7 @@ use codex_tools::ToolExecutor; use codex_tools::ToolName; use codex_tools::ToolOutput; use codex_tools::ToolSpec; +use codex_tools::UnifiedExecShellMode; use codex_tools::can_request_original_image_detail; use codex_tools::collect_code_mode_exec_prompt_tool_definitions; use codex_tools::collect_request_plugin_install_entries; @@ -564,6 +565,7 @@ fn add_shell_tools(context: &CoreToolPlanContext<'_>, planned_tools: &mut Planne allow_login_shell, exec_permission_approvals_enabled, include_environment_id, + include_shell_parameter: unified_exec_should_include_shell_parameter(turn_context), })); planned_tools.add(WriteStdinHandler); @@ -580,6 +582,17 @@ fn add_shell_tools(context: &CoreToolPlanContext<'_>, planned_tools: &mut Planne } } +fn unified_exec_should_include_shell_parameter(turn_context: &TurnContext) -> bool { + !matches!( + &turn_context.unified_exec_shell_mode, + UnifiedExecShellMode::ZshFork(_) + ) || turn_context + .environments + .turn_environments + .iter() + .any(|environment| environment.environment.is_remote()) +} + fn add_mcp_resource_tools(context: &CoreToolPlanContext<'_>, planned_tools: &mut PlannedTools) { if context.mcp_tools.is_some() { planned_tools.add(ListMcpResourcesHandler); diff --git a/codex-rs/core/src/tools/spec_plan_tests.rs b/codex-rs/core/src/tools/spec_plan_tests.rs index 3f832ed0ac..e129e4ddaa 100644 --- a/codex-rs/core/src/tools/spec_plan_tests.rs +++ b/codex-rs/core/src/tools/spec_plan_tests.rs @@ -233,6 +233,21 @@ fn set_features(turn: &mut TurnContext, features: &[Feature]) { } } +fn zsh_fork_config_for_spec_plan_tests() -> codex_tools::ZshForkConfig { + let placeholder_exe = codex_utils_absolute_path::AbsolutePathBuf::try_from( + std::env::current_exe().expect("current exe path"), + ) + .expect("current exe should be absolute"); + + // Spec planning only checks whether the shell mode is ZshFork. These paths + // are never executed, so use a stable absolute placeholder instead of + // depending on packaged zsh-fork artifacts in schema tests. + codex_tools::ZshForkConfig { + shell_zsh_path: placeholder_exe.clone(), + main_execve_wrapper_exe: placeholder_exe, + } +} + fn update_config(turn: &mut TurnContext, update: impl FnOnce(&mut crate::config::Config)) { let mut config = (*turn.config).clone(); update(&mut config); @@ -406,6 +421,7 @@ async fn shell_family_registers_visible_unified_exec_and_hidden_legacy_shell() { plan.assert_visible_lacks(&["shell_command"]); plan.assert_registered_contains(&["exec_command", "write_stdin", "shell_command"]); assert_eq!(plan.exposure("shell_command"), ToolExposure::Hidden); + assert!(has_parameter(plan.visible_spec("exec_command"), "shell")); } #[tokio::test] @@ -448,6 +464,79 @@ async fn shell_zsh_fork_stays_standalone_until_unified_exec_composition_is_enabl } } +#[tokio::test] +async fn zsh_fork_unified_exec_hides_shell_parameter() { + if !codex_utils_pty::conpty_supported() { + return; + } + + let plan = probe(|turn| { + set_features( + turn, + &[ + Feature::ShellTool, + Feature::UnifiedExec, + Feature::ShellZshFork, + Feature::UnifiedExecZshFork, + ], + ); + turn.unified_exec_shell_mode = + codex_tools::UnifiedExecShellMode::ZshFork(zsh_fork_config_for_spec_plan_tests()); + }) + .await; + + plan.assert_visible_contains(&["exec_command", "write_stdin"]); + assert!(!has_parameter(plan.visible_spec("exec_command"), "shell")); +} + +#[tokio::test] +async fn zsh_fork_unified_exec_keeps_shell_parameter_when_remote_environment_available() { + if !codex_utils_pty::conpty_supported() { + return; + } + + let plan = probe(|turn| { + set_features( + turn, + &[ + Feature::ShellTool, + Feature::UnifiedExec, + Feature::ShellZshFork, + Feature::UnifiedExecZshFork, + ], + ); + turn.unified_exec_shell_mode = + codex_tools::UnifiedExecShellMode::ZshFork(zsh_fork_config_for_spec_plan_tests()); + let remote_cwd = turn + .environments + .primary() + .expect("primary environment") + .cwd + .clone(); + turn.environments + .turn_environments + .push(crate::session::turn_context::TurnEnvironment { + environment_id: "remote".to_string(), + environment: Arc::new( + codex_exec_server::Environment::create_for_tests(Some( + "ws://127.0.0.1:1/remote-exec-server".to_string(), + )) + .expect("remote test environment"), + ), + cwd: remote_cwd, + shell: None, + }); + }) + .await; + + plan.assert_visible_contains(&["exec_command", "write_stdin"]); + assert!(has_parameter(plan.visible_spec("exec_command"), "shell")); + assert!(has_parameter( + plan.visible_spec("exec_command"), + "environment_id" + )); +} + #[tokio::test] async fn environment_count_controls_environment_backed_tools() { let no_environment = probe(|turn| { diff --git a/codex-rs/core/src/unified_exec/mod.rs b/codex-rs/core/src/unified_exec/mod.rs index 6be32d26e7..94a7ab7c73 100644 --- a/codex-rs/core/src/unified_exec/mod.rs +++ b/codex-rs/core/src/unified_exec/mod.rs @@ -30,6 +30,7 @@ use std::sync::Weak; use codex_exec_server::Environment; use codex_network_proxy::NetworkProxy; use codex_protocol::models::AdditionalPermissionProfile; +use codex_tools::UnifiedExecShellMode; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_output_truncation::TruncationPolicy; use rand::Rng; @@ -97,6 +98,7 @@ pub(crate) struct ExecCommandRequest { pub cwd: AbsolutePathBuf, pub sandbox_cwd: AbsolutePathBuf, pub environment: Arc, + pub shell_mode: UnifiedExecShellMode, pub network: Option, pub tty: bool, pub sandbox_permissions: SandboxPermissions, diff --git a/codex-rs/core/src/unified_exec/process_manager.rs b/codex-rs/core/src/unified_exec/process_manager.rs index 83c750ebc4..563d486c69 100644 --- a/codex-rs/core/src/unified_exec/process_manager.rs +++ b/codex-rs/core/src/unified_exec/process_manager.rs @@ -1010,8 +1010,7 @@ impl UnifiedExecProcessManager { local_policy_env, }; let mut orchestrator = ToolOrchestrator::new(); - let mut runtime = - UnifiedExecRuntime::new(self, context.turn.unified_exec_shell_mode.clone()); + let mut runtime = UnifiedExecRuntime::new(self, request.shell_mode.clone()); let file_system_sandbox_policy = context.turn.file_system_sandbox_policy(); let exec_approval_requirement = context .session diff --git a/codex-rs/core/src/unified_exec/process_manager_tests.rs b/codex-rs/core/src/unified_exec/process_manager_tests.rs index 4d0597a844..9aa0e73814 100644 --- a/codex-rs/core/src/unified_exec/process_manager_tests.rs +++ b/codex-rs/core/src/unified_exec/process_manager_tests.rs @@ -179,6 +179,7 @@ async fn failed_initial_end_for_unstored_process_uses_fallback_output() { .environments .primary_environment() .expect("primary environment"), + shell_mode: codex_tools::UnifiedExecShellMode::Direct, network: None, tty: true, sandbox_permissions: crate::sandboxing::SandboxPermissions::UseDefault, From 47b40d828f9fa9139695f30660a7bae16dda7ddd Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Mon, 1 Jun 2026 13:23:08 -0700 Subject: [PATCH 2/3] fix: sandbox zsh fork unified exec trampoline --- .../tools/runtimes/shell/unix_escalation.rs | 6 +- .../runtimes/shell/unix_escalation_tests.rs | 101 ++++++++ .../core/src/tools/runtimes/unified_exec.rs | 242 +++++++++++++++++- 3 files changed, 333 insertions(+), 16 deletions(-) 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 2017718f7d..08d83e2f16 100644 --- a/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs +++ b/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs @@ -635,9 +635,11 @@ impl EscalationPolicy for CoreShellActionProvider { let decision_driven_by_policy = Self::decision_driven_by_policy(&evaluation.matched_rules, evaluation.decision); let unsandboxed_allowed = unsandboxed_execution_allowed(&self.file_system_sandbox_policy); - let needs_escalation = unsandboxed_allowed + let needs_unsandboxed_escalation = unsandboxed_allowed && (self.sandbox_permissions.requires_escalated_permissions() || decision_driven_by_policy); + let needs_escalation = + self.sandbox_permissions.uses_additional_permissions() || needs_unsandboxed_escalation; let decision_source = if decision_driven_by_policy { DecisionSource::PrefixRule @@ -866,7 +868,7 @@ impl ShellCommandExecutor for CoreShellCommandExecutor { EscalationExecution::Unsandboxed => PreparedExec { command, cwd: workdir.to_path_buf(), - env, + env: exec_env_for_sandbox_permissions(&env, SandboxPermissions::RequireEscalated), arg0: Some(first_arg.clone()), }, EscalationExecution::TurnDefault => { 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 6e7a1ced54..4386ef4c39 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 @@ -1,4 +1,5 @@ use super::CoreShellActionProvider; +use super::CoreShellCommandExecutor; use super::InterceptedExecPolicyContext; use super::ParsedShellCommand; use super::commands_for_intercepted_exec_policy; @@ -16,6 +17,9 @@ use codex_execpolicy::PolicyParser; use codex_execpolicy::RuleMatch; use codex_hooks::Hooks; use codex_hooks::HooksConfig; +use codex_network_proxy::PROXY_ACTIVE_ENV_KEY; +use codex_network_proxy::PROXY_ENV_KEYS; +use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::models::AdditionalPermissionProfile; use codex_protocol::models::FileSystemPermissions; use codex_protocol::models::PermissionProfile; @@ -29,13 +33,16 @@ use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::GranularApprovalConfig; use codex_protocol::protocol::GuardianCommandSource; use codex_sandboxing::SandboxType; +use codex_sandboxing::policy_transforms::effective_permission_profile; use codex_shell_escalation::EscalationExecution; use codex_shell_escalation::EscalationPermissions; use codex_shell_escalation::ExecResult; use codex_shell_escalation::ResolvedPermissionProfile; +use codex_shell_escalation::ShellCommandExecutor; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; use serde_json::Value; +use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; @@ -348,6 +355,100 @@ fn shell_request_escalation_execution_is_explicit() { ); } +#[tokio::test] +async fn unsandboxed_intercepted_exec_strips_managed_network_env() -> anyhow::Result<()> { + let workdir = test_sandbox_cwd(); + let executor = CoreShellCommandExecutor { + command: Vec::new(), + cwd: workdir.clone(), + permission_profile: PermissionProfile::workspace_write(), + file_system_sandbox_policy: read_only_file_system_sandbox_policy(), + network_sandbox_policy: NetworkSandboxPolicy::Restricted, + sandbox: SandboxType::None, + env: HashMap::new(), + network: None, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + arg0: None, + sandbox_policy_cwd: workdir.clone(), + windows_sandbox_workspace_roots: vec![workdir.clone()], + codex_linux_sandbox_exe: None, + use_legacy_landlock: false, + }; + let mut env = HashMap::new(); + env.insert(PROXY_ACTIVE_ENV_KEY.to_string(), "1".to_string()); + for key in PROXY_ENV_KEYS { + env.insert((*key).to_string(), format!("proxy-{key}")); + } + + let prepared = executor + .prepare_escalated_exec( + &AbsolutePathBuf::from_absolute_path("/usr/bin/curl")?, + &["curl".to_string(), "example.com".to_string()], + &workdir, + env, + EscalationExecution::Unsandboxed, + ) + .await?; + + assert!(!prepared.env.contains_key(PROXY_ACTIVE_ENV_KEY)); + for key in PROXY_ENV_KEYS { + assert!(!prepared.env.contains_key(*key)); + } + + Ok(()) +} + +#[tokio::test] +async fn preapproved_additional_permissions_escalate_intercepted_exec() -> anyhow::Result<()> { + let (session, turn_context) = make_session_and_context().await; + let requested_permissions = AdditionalPermissionProfile { + file_system: Some(FileSystemPermissions::from_read_write_roots( + /*read*/ None, + Some(vec![ + AbsolutePathBuf::from_absolute_path("/tmp/output").unwrap(), + ]), + )), + ..Default::default() + }; + let workdir = test_sandbox_cwd(); + let permission_profile = effective_permission_profile( + &PermissionProfile::workspace_write(), + Some(&requested_permissions), + ); + let provider = CoreShellActionProvider { + policy: Arc::new(RwLock::new(codex_execpolicy::Policy::empty())), + session: Arc::new(session), + turn: Arc::new(turn_context), + call_id: "preapproved-additional-permissions".to_string(), + tool_name: GuardianCommandSource::Shell, + approval_policy: AskForApproval::OnRequest, + permission_profile: permission_profile.clone(), + file_system_sandbox_policy: read_only_file_system_sandbox_policy(), + sandbox_policy_cwd: workdir.clone(), + sandbox_permissions: SandboxPermissions::WithAdditionalPermissions, + approval_sandbox_permissions: SandboxPermissions::UseDefault, + prompt_permissions: Some(requested_permissions), + stopwatch: codex_shell_escalation::Stopwatch::new(Duration::from_secs(1)), + }; + + let action = codex_shell_escalation::EscalationPolicy::determine_action( + &provider, + &AbsolutePathBuf::from_absolute_path("/usr/bin/printf")?, + &["printf".to_string(), "hello".to_string()], + &workdir, + ) + .await?; + + let expected = codex_shell_escalation::EscalationDecision::Escalate( + EscalationExecution::Permissions(EscalationPermissions::ResolvedPermissionProfile( + ResolvedPermissionProfile { permission_profile }, + )), + ); + assert_eq!(action, expected); + + Ok(()) +} + #[tokio::test(flavor = "current_thread")] async fn execve_permission_request_hook_short_circuits_prompt() -> anyhow::Result<()> { let (session, mut turn_context) = make_session_and_context().await; diff --git a/codex-rs/core/src/tools/runtimes/unified_exec.rs b/codex-rs/core/src/tools/runtimes/unified_exec.rs index e49c925728..5fbb432683 100644 --- a/codex-rs/core/src/tools/runtimes/unified_exec.rs +++ b/codex-rs/core/src/tools/runtimes/unified_exec.rs @@ -46,6 +46,7 @@ use codex_protocol::error::CodexErr; use codex_protocol::error::SandboxErr; use codex_protocol::models::AdditionalPermissionProfile; use codex_protocol::protocol::ReviewDecision; +use codex_sandboxing::SandboxType; use codex_sandboxing::SandboxablePreference; use codex_shell_command::powershell::prefix_powershell_script_with_utf8; use codex_tools::UnifiedExecShellMode; @@ -118,6 +119,65 @@ impl<'a> UnifiedExecRuntime<'a> { shell_mode, } } + + fn first_attempt_sandbox_permissions(&self, req: &UnifiedExecRequest) -> SandboxPermissions { + if matches!(&self.shell_mode, UnifiedExecShellMode::ZshFork(_)) + && req.sandbox_permissions.requires_escalated_permissions() + { + SandboxPermissions::UseDefault + } else { + req.sandbox_permissions + } + } + + fn first_attempt_exec_approval_requirement( + &self, + req: &UnifiedExecRequest, + ) -> ExecApprovalRequirement { + if matches!(&self.shell_mode, UnifiedExecShellMode::ZshFork(_)) + && let ExecApprovalRequirement::Skip { + bypass_sandbox: true, + proposed_execpolicy_amendment, + } = &req.exec_approval_requirement + { + ExecApprovalRequirement::Skip { + bypass_sandbox: false, + proposed_execpolicy_amendment: proposed_execpolicy_amendment.clone(), + } + } else { + req.exec_approval_requirement.clone() + } + } + + fn launch_sandbox_permissions( + &self, + req: &UnifiedExecRequest, + attempt: &SandboxAttempt<'_>, + ) -> SandboxPermissions { + if matches!(&self.shell_mode, UnifiedExecShellMode::ZshFork(_)) + && attempt.sandbox != SandboxType::None + && req.sandbox_permissions.requires_escalated_permissions() + { + SandboxPermissions::UseDefault + } else { + req.sandbox_permissions + } + } + + fn launch_additional_permissions( + &self, + req: &UnifiedExecRequest, + attempt: &SandboxAttempt<'_>, + ) -> Option { + if matches!(&self.shell_mode, UnifiedExecShellMode::ZshFork(_)) + && attempt.sandbox != SandboxType::None + && req.sandbox_permissions.requires_escalated_permissions() + { + None + } else { + req.additional_permissions.clone() + } + } } impl Sandboxable for UnifiedExecRuntime<'_> { @@ -203,7 +263,7 @@ impl Approvable for UnifiedExecRuntime<'_> { &self, req: &UnifiedExecRequest, ) -> Option { - Some(req.exec_approval_requirement.clone()) + Some(self.first_attempt_exec_approval_requirement(req)) } fn permission_request_payload( @@ -217,7 +277,7 @@ impl Approvable for UnifiedExecRuntime<'_> { } fn sandbox_permissions(&self, req: &UnifiedExecRequest) -> SandboxPermissions { - req.sandbox_permissions + self.first_attempt_sandbox_permissions(req) } } @@ -264,17 +324,15 @@ impl<'a> ToolRuntime for UnifiedExecRunt let base_command = &req.command; let session_shell = ctx.session.user_shell(); let (file_system_sandbox_policy, _) = attempt.permissions.to_runtime_permissions(); - let sandbox_permissions = sandbox_permissions_preserving_denied_reads( - req.sandbox_permissions, + let launch_sandbox_permissions = sandbox_permissions_preserving_denied_reads( + self.launch_sandbox_permissions(req, attempt), &file_system_sandbox_policy, ); - let req = &UnifiedExecRequest { - sandbox_permissions, - ..req.clone() - }; - let managed_network = - managed_network_for_sandbox_permissions(req.network.as_ref(), req.sandbox_permissions); - let mut env = exec_env_for_sandbox_permissions(&req.env, req.sandbox_permissions); + let managed_network = managed_network_for_sandbox_permissions( + req.network.as_ref(), + launch_sandbox_permissions, + ); + let mut env = exec_env_for_sandbox_permissions(&req.env, launch_sandbox_permissions); if let Some(network) = managed_network { network.apply_to_env(&mut env); } @@ -316,9 +374,13 @@ impl<'a> ToolRuntime for UnifiedExecRunt }; if let UnifiedExecShellMode::ZshFork(zsh_fork_config) = &self.shell_mode { - let command = - build_sandbox_command(&command, &req.cwd, &env, req.additional_permissions.clone()) - .map_err(|_| ToolError::Rejected("missing command line for PTY".to_string()))?; + let command = build_sandbox_command( + &command, + &req.cwd, + &env, + self.launch_additional_permissions(req, attempt), + ) + .map_err(|_| ToolError::Rejected("missing command line for PTY".to_string()))?; let options = unified_exec_options(attempt.network_denial_cancellation_token.clone()); let mut exec_env = attempt .env_for(command, options, managed_network) @@ -400,8 +462,15 @@ impl<'a> ToolRuntime for UnifiedExecRunt mod tests { use super::*; use crate::exec::DEFAULT_EXEC_COMMAND_TIMEOUT_MS; + use crate::tools::sandboxing::SandboxAttempt; use crate::tools::sandboxing::ToolRuntime; use codex_exec_server::Environment; + use codex_protocol::config_types::WindowsSandboxLevel; + use codex_protocol::models::NetworkPermissions; + use codex_protocol::models::PermissionProfile; + use codex_sandboxing::SandboxManager; + use codex_sandboxing::SandboxType; + use codex_tools::ZshForkConfig; use std::time::Duration; use tempfile::tempdir; @@ -463,4 +532,149 @@ mod tests { assert_eq!(runtime.sandbox_cwd(&request), Some(&sandbox_cwd)); } + + #[tokio::test] + async fn zsh_fork_first_attempt_uses_turn_default_sandbox_permissions() { + let manager = UnifiedExecProcessManager::default(); + let request = test_request( + SandboxPermissions::RequireEscalated, + ExecApprovalRequirement::NeedsApproval { + reason: None, + proposed_execpolicy_amendment: None, + }, + ); + let direct_runtime = UnifiedExecRuntime::new(&manager, UnifiedExecShellMode::Direct); + let zsh_fork_runtime = UnifiedExecRuntime::new(&manager, zsh_fork_mode()); + + assert_eq!( + direct_runtime.sandbox_permissions(&request), + SandboxPermissions::RequireEscalated + ); + assert_eq!( + zsh_fork_runtime.sandbox_permissions(&request), + SandboxPermissions::UseDefault + ); + } + + #[tokio::test] + async fn zsh_fork_first_attempt_preserves_additional_permissions_request() { + let manager = UnifiedExecProcessManager::default(); + let request = test_request( + SandboxPermissions::WithAdditionalPermissions, + ExecApprovalRequirement::NeedsApproval { + reason: None, + proposed_execpolicy_amendment: None, + }, + ); + let zsh_fork_runtime = UnifiedExecRuntime::new(&manager, zsh_fork_mode()); + + assert_eq!( + zsh_fork_runtime.sandbox_permissions(&request), + SandboxPermissions::WithAdditionalPermissions + ); + } + + #[tokio::test] + async fn zsh_fork_sandboxed_launch_preserves_additional_permissions() { + let manager = UnifiedExecProcessManager::default(); + let runtime = UnifiedExecRuntime::new(&manager, zsh_fork_mode()); + let additional_permissions = AdditionalPermissionProfile { + network: Some(NetworkPermissions { + enabled: Some(true), + }), + ..Default::default() + }; + let mut request = test_request( + SandboxPermissions::WithAdditionalPermissions, + ExecApprovalRequirement::NeedsApproval { + reason: None, + proposed_execpolicy_amendment: None, + }, + ); + request.additional_permissions = Some(additional_permissions.clone()); + let cwd = request.sandbox_cwd.clone(); + let workspace_roots = vec![cwd.clone()]; + let sandbox_manager = SandboxManager::new(); + let permissions = PermissionProfile::workspace_write(); + let attempt = SandboxAttempt { + sandbox: SandboxType::MacosSeatbelt, + permissions: &permissions, + enforce_managed_network: true, + manager: &sandbox_manager, + sandbox_cwd: &cwd, + workspace_roots: workspace_roots.as_slice(), + codex_linux_sandbox_exe: None, + use_legacy_landlock: false, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + windows_sandbox_private_desktop: false, + network_denial_cancellation_token: None, + }; + + assert_eq!( + runtime.launch_sandbox_permissions(&request, &attempt), + SandboxPermissions::WithAdditionalPermissions + ); + assert_eq!( + runtime.launch_additional_permissions(&request, &attempt), + Some(additional_permissions) + ); + } + + #[tokio::test] + async fn zsh_fork_execpolicy_allow_does_not_bypass_trampoline_sandbox() { + let manager = UnifiedExecProcessManager::default(); + let request = test_request( + SandboxPermissions::UseDefault, + ExecApprovalRequirement::Skip { + bypass_sandbox: true, + proposed_execpolicy_amendment: None, + }, + ); + let runtime = UnifiedExecRuntime::new(&manager, zsh_fork_mode()); + + assert_eq!( + runtime.exec_approval_requirement(&request), + Some(ExecApprovalRequirement::Skip { + bypass_sandbox: false, + proposed_execpolicy_amendment: None, + }) + ); + } + + fn test_request( + sandbox_permissions: SandboxPermissions, + exec_approval_requirement: ExecApprovalRequirement, + ) -> UnifiedExecRequest { + let cwd = AbsolutePathBuf::try_from(std::env::current_dir().unwrap()) + .expect("current dir is absolute"); + UnifiedExecRequest { + command: vec!["zsh".to_string(), "-c".to_string(), "echo hi".to_string()], + shell_type: ShellType::Zsh, + hook_command: "echo hi".to_string(), + process_id: 1000, + cwd: cwd.clone(), + sandbox_cwd: cwd, + environment: Arc::new(Environment::default_for_tests()), + env: HashMap::new(), + exec_server_env_config: None, + explicit_env_overrides: HashMap::new(), + network: None, + tty: false, + sandbox_permissions, + additional_permissions: None, + #[cfg(unix)] + additional_permissions_preapproved: false, + justification: None, + exec_approval_requirement, + } + } + + fn zsh_fork_mode() -> UnifiedExecShellMode { + let cwd = std::env::current_dir().expect("read current dir"); + UnifiedExecShellMode::ZshFork(ZshForkConfig { + shell_zsh_path: AbsolutePathBuf::try_from(cwd.join("zsh")).expect("absolute zsh path"), + main_execve_wrapper_exe: AbsolutePathBuf::try_from(cwd.join("execve-wrapper")) + .expect("absolute wrapper path"), + }) + } } From cd911bdae3bfb358d3bfed7d37f46f674de90884 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Mon, 1 Jun 2026 13:23:08 -0700 Subject: [PATCH 3/3] fix: honor parent approvals for intercepted execs --- .../tools/runtimes/shell/unix_escalation.rs | 38 +++++- .../runtimes/shell/unix_escalation_tests.rs | 127 ++++++++++++++++++ codex-rs/core/tests/common/zsh_fork.rs | 27 ++++ codex-rs/core/tests/suite/approvals.rs | 117 ++++++++++++++++ 4 files changed, 308 insertions(+), 1 deletion(-) 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 08d83e2f16..b5d609ac1f 100644 --- a/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs +++ b/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs @@ -17,6 +17,7 @@ use crate::shell::ShellType; use crate::tools::runtimes::build_sandbox_command; use crate::tools::runtimes::exec_env_for_sandbox_permissions; use crate::tools::runtimes::prepend_zsh_fork_bin_to_path; +use crate::tools::sandboxing::ExecApprovalRequirement; use crate::tools::sandboxing::PermissionRequestPayload; use crate::tools::sandboxing::SandboxAttempt; use crate::tools::sandboxing::ToolCtx; @@ -100,6 +101,19 @@ fn approval_sandbox_permissions( } } +fn parent_approved_sandbox_override( + sandbox_permissions: SandboxPermissions, + additional_permissions_preapproved: bool, + exec_approval_requirement: &ExecApprovalRequirement, +) -> bool { + sandbox_permissions.requests_sandbox_override() + && (additional_permissions_preapproved + || matches!( + exec_approval_requirement, + ExecApprovalRequirement::NeedsApproval { .. } + )) +} + pub(super) async fn try_run_zsh_fork( req: &ShellRequest, attempt: &SandboxAttempt<'_>, @@ -228,6 +242,11 @@ pub(super) async fn try_run_zsh_fork( sandbox_permissions: req.sandbox_permissions, approval_sandbox_permissions, prompt_permissions: req.additional_permissions.clone(), + parent_sandbox_override_approved: parent_approved_sandbox_override( + req.sandbox_permissions, + req.additional_permissions_preapproved, + &req.exec_approval_requirement, + ), stopwatch: stopwatch.clone(), }; @@ -304,6 +323,11 @@ pub(crate) async fn prepare_unified_exec_zsh_fork( req.additional_permissions_preapproved, ), prompt_permissions: req.additional_permissions.clone(), + parent_sandbox_override_approved: parent_approved_sandbox_override( + req.sandbox_permissions, + req.additional_permissions_preapproved, + &req.exec_approval_requirement, + ), stopwatch: Stopwatch::unlimited(), }; @@ -336,6 +360,7 @@ struct CoreShellActionProvider { sandbox_permissions: SandboxPermissions, approval_sandbox_permissions: SandboxPermissions, prompt_permissions: Option, + parent_sandbox_override_approved: bool, stopwatch: Stopwatch, } @@ -638,6 +663,17 @@ impl EscalationPolicy for CoreShellActionProvider { let needs_unsandboxed_escalation = unsandboxed_allowed && (self.sandbox_permissions.requires_escalated_permissions() || decision_driven_by_policy); + // The parent shell/unified-exec approval already covered unmatched + // prompts caused by its sandbox override. Explicit exec-policy rules + // still keep their own decisions. + let decision = if self.parent_sandbox_override_approved + && evaluation.decision == Decision::Prompt + && !decision_driven_by_policy + { + Decision::Allow + } else { + evaluation.decision + }; let needs_escalation = self.sandbox_permissions.uses_additional_permissions() || needs_unsandboxed_escalation; @@ -657,7 +693,7 @@ impl EscalationPolicy for CoreShellActionProvider { ), }; self.process_decision( - evaluation.decision, + decision, needs_escalation, program, argv, 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 4386ef4c39..07c27c9431 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 @@ -153,6 +153,42 @@ fn approval_sandbox_permissions_only_downgrades_preapproved_additional_permissio ); } +#[test] +fn parent_approved_sandbox_override_tracks_parent_approval_sources() { + assert!(super::parent_approved_sandbox_override( + SandboxPermissions::RequireEscalated, + /*additional_permissions_preapproved*/ false, + &crate::tools::sandboxing::ExecApprovalRequirement::NeedsApproval { + reason: None, + proposed_execpolicy_amendment: None, + }, + )); + assert!(super::parent_approved_sandbox_override( + SandboxPermissions::WithAdditionalPermissions, + /*additional_permissions_preapproved*/ true, + &crate::tools::sandboxing::ExecApprovalRequirement::Skip { + bypass_sandbox: false, + proposed_execpolicy_amendment: None, + }, + )); + assert!(!super::parent_approved_sandbox_override( + SandboxPermissions::UseDefault, + /*additional_permissions_preapproved*/ false, + &crate::tools::sandboxing::ExecApprovalRequirement::NeedsApproval { + reason: None, + proposed_execpolicy_amendment: None, + }, + )); + assert!(!super::parent_approved_sandbox_override( + SandboxPermissions::RequireEscalated, + /*additional_permissions_preapproved*/ false, + &crate::tools::sandboxing::ExecApprovalRequirement::Skip { + bypass_sandbox: true, + proposed_execpolicy_amendment: None, + }, + )); +} + #[test] fn extract_shell_script_preserves_login_flag() { assert_eq!( @@ -428,6 +464,7 @@ async fn preapproved_additional_permissions_escalate_intercepted_exec() -> anyho sandbox_permissions: SandboxPermissions::WithAdditionalPermissions, approval_sandbox_permissions: SandboxPermissions::UseDefault, prompt_permissions: Some(requested_permissions), + parent_sandbox_override_approved: true, stopwatch: codex_shell_escalation::Stopwatch::new(Duration::from_secs(1)), }; @@ -449,6 +486,93 @@ async fn preapproved_additional_permissions_escalate_intercepted_exec() -> anyho Ok(()) } +#[tokio::test] +async fn parent_require_escalated_approval_escalates_intercepted_exec() -> anyhow::Result<()> { + let (session, turn_context) = make_session_and_context().await; + let workdir = test_sandbox_cwd(); + let provider = CoreShellActionProvider { + policy: Arc::new(RwLock::new(codex_execpolicy::Policy::empty())), + session: Arc::new(session), + turn: Arc::new(turn_context), + call_id: "parent-require-escalated".to_string(), + tool_name: GuardianCommandSource::Shell, + approval_policy: AskForApproval::OnRequest, + permission_profile: PermissionProfile::workspace_write(), + file_system_sandbox_policy: read_only_file_system_sandbox_policy(), + sandbox_policy_cwd: workdir.clone(), + sandbox_permissions: SandboxPermissions::RequireEscalated, + approval_sandbox_permissions: SandboxPermissions::RequireEscalated, + prompt_permissions: None, + parent_sandbox_override_approved: true, + stopwatch: codex_shell_escalation::Stopwatch::new(Duration::from_secs(1)), + }; + + let action = codex_shell_escalation::EscalationPolicy::determine_action( + &provider, + &AbsolutePathBuf::from_absolute_path("/usr/bin/curl")?, + &["curl".to_string(), "example.com".to_string()], + &workdir, + ) + .await?; + + assert_eq!( + action, + codex_shell_escalation::EscalationDecision::Escalate(EscalationExecution::Unsandboxed) + ); + + Ok(()) +} + +#[tokio::test] +async fn parent_approval_does_not_override_intercepted_exec_policy_prompt() -> anyhow::Result<()> { + let (session, turn_context) = make_session_and_context().await; + let mut parser = PolicyParser::new(); + parser.parse( + "test.rules", + r#"prefix_rule(pattern = ["curl"], decision = "prompt")"#, + )?; + let workdir = test_sandbox_cwd(); + let provider = CoreShellActionProvider { + policy: Arc::new(RwLock::new(parser.build())), + session: Arc::new(session), + turn: Arc::new(turn_context), + call_id: "parent-policy-prompt".to_string(), + tool_name: GuardianCommandSource::Shell, + approval_policy: AskForApproval::Granular(GranularApprovalConfig { + sandbox_approval: true, + rules: false, + skill_approval: true, + request_permissions: true, + mcp_elicitations: true, + }), + permission_profile: PermissionProfile::workspace_write(), + file_system_sandbox_policy: read_only_file_system_sandbox_policy(), + sandbox_policy_cwd: workdir.clone(), + sandbox_permissions: SandboxPermissions::RequireEscalated, + approval_sandbox_permissions: SandboxPermissions::RequireEscalated, + prompt_permissions: None, + parent_sandbox_override_approved: true, + stopwatch: codex_shell_escalation::Stopwatch::new(Duration::from_secs(1)), + }; + + let action = codex_shell_escalation::EscalationPolicy::determine_action( + &provider, + &AbsolutePathBuf::from_absolute_path("/usr/bin/curl")?, + &["curl".to_string(), "example.com".to_string()], + &workdir, + ) + .await?; + + assert_eq!( + action, + codex_shell_escalation::EscalationDecision::Deny { + reason: Some("Execution forbidden by policy".to_string()), + } + ); + + Ok(()) +} + #[tokio::test(flavor = "current_thread")] async fn execve_permission_request_hook_short_circuits_prompt() -> anyhow::Result<()> { let (session, mut turn_context) = make_session_and_context().await; @@ -561,6 +685,7 @@ async fn execve_permission_request_hook_short_circuits_prompt() -> anyhow::Resul sandbox_permissions: SandboxPermissions::RequireEscalated, approval_sandbox_permissions: SandboxPermissions::RequireEscalated, prompt_permissions: None, + parent_sandbox_override_approved: false, stopwatch: codex_shell_escalation::Stopwatch::new(Duration::from_secs(1)), }; @@ -778,6 +903,7 @@ prefix_rule(pattern = ["{cat_path_literal}"], decision = "allow") sandbox_permissions: SandboxPermissions::UseDefault, approval_sandbox_permissions: SandboxPermissions::UseDefault, prompt_permissions: None, + parent_sandbox_override_approved: false, stopwatch: codex_shell_escalation::Stopwatch::new(Duration::from_secs(1)), }; @@ -821,6 +947,7 @@ async fn denied_reads_keep_granular_sandbox_rejection_for_escalation() -> anyhow sandbox_permissions: SandboxPermissions::RequireEscalated, approval_sandbox_permissions: SandboxPermissions::RequireEscalated, prompt_permissions: None, + parent_sandbox_override_approved: false, stopwatch: codex_shell_escalation::Stopwatch::new(Duration::from_secs(1)), }; diff --git a/codex-rs/core/tests/common/zsh_fork.rs b/codex-rs/core/tests/common/zsh_fork.rs index e58ebd81dd..5abfc753b9 100644 --- a/codex-rs/core/tests/common/zsh_fork.rs +++ b/codex-rs/core/tests/common/zsh_fork.rs @@ -94,6 +94,33 @@ where builder.build(server).await } +pub async fn build_unified_exec_zsh_fork_test( + server: &wiremock::MockServer, + runtime: ZshForkRuntime, + approval_policy: AskForApproval, + permission_profile: PermissionProfile, + pre_build_hook: F, +) -> Result +where + F: FnOnce(&Path) + Send + 'static, +{ + let mut builder = test_codex() + .with_pre_build_hook(pre_build_hook) + .with_config(move |config| { + runtime.apply_to_config(config, approval_policy, permission_profile); + config.use_experimental_unified_exec_tool = true; + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); + config + .features + .enable(Feature::UnifiedExecZshFork) + .expect("test config should allow feature update"); + }); + builder.build(server).await +} + fn find_test_zsh_path() -> Result> { let repo_root = codex_utils_cargo_bin::repo_root()?; let dotslash_zsh = repo_root.join("codex-rs/app-server/tests/suite/zsh"); diff --git a/codex-rs/core/tests/suite/approvals.rs b/codex-rs/core/tests/suite/approvals.rs index a91196a0b9..71484c0985 100644 --- a/codex-rs/core/tests/suite/approvals.rs +++ b/codex-rs/core/tests/suite/approvals.rs @@ -43,6 +43,7 @@ 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 core_test_support::wait_for_event_with_timeout; +use core_test_support::zsh_fork::build_unified_exec_zsh_fork_test; use core_test_support::zsh_fork::build_zsh_fork_test; use core_test_support::zsh_fork::restrictive_workspace_write_profile; use core_test_support::zsh_fork::zsh_fork_runtime; @@ -2800,6 +2801,122 @@ async fn matched_prefix_rule_runs_unsandboxed_under_zsh_fork() -> Result<()> { Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg(unix)] +async fn unified_exec_zsh_fork_parent_approval_escalates_intercepted_exec() -> Result<()> { + skip_if_no_network!(Ok(())); + + let Some(runtime) = zsh_fork_runtime("unified-exec zsh-fork parent approval test")? else { + return Ok(()); + }; + + let approval_policy = AskForApproval::OnRequest; + let permission_profile = restrictive_workspace_write_profile(); + let outside_dir = tempfile::tempdir_in(std::env::current_dir()?)?; + let outside_path = outside_dir + .path() + .join("unified-exec-zsh-fork-parent-approval.txt"); + let command = format!("touch {outside_path:?}"); + + let server = start_mock_server().await; + let outside_path_for_hook = outside_path.clone(); + let test = build_unified_exec_zsh_fork_test( + &server, + runtime, + approval_policy, + permission_profile, + move |_home| { + let _ = fs::remove_file(&outside_path_for_hook); + }, + ) + .await?; + + let call_id = "uexec-zsh-fork-parent-approval"; + let event = exec_command_event( + call_id, + &command, + Some(30_000), + SandboxPermissions::RequireEscalated, + Some("write outside the workspace for the test"), + )?; + let _ = mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-uexec-zsh-fork-parent-approval-1"), + event, + ev_completed("resp-uexec-zsh-fork-parent-approval-1"), + ]), + ) + .await; + let results = mount_sse_once( + &server, + sse(vec![ + ev_assistant_message("msg-uexec-zsh-fork-parent-approval-1", "done"), + ev_completed("resp-uexec-zsh-fork-parent-approval-2"), + ]), + ) + .await; + + let session_model = test.session_configured.model.clone(); + let (sandbox_policy, permission_profile) = turn_permission_fields( + test.session_configured.permission_profile.clone(), + test.cwd.path(), + ); + test.codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "run approved unified exec through zsh fork".into(), + text_elements: Vec::new(), + }], + environments: None, + final_output_json_schema: None, + responsesapi_client_metadata: None, + additional_context: Default::default(), + thread_settings: codex_protocol::protocol::ThreadSettingsOverrides { + cwd: Some(test.cwd.path().to_path_buf()), + approval_policy: Some(approval_policy), + approvals_reviewer: Some(ApprovalsReviewer::User), + sandbox_policy: Some(sandbox_policy), + permission_profile, + collaboration_mode: Some(codex_protocol::config_types::CollaborationMode { + mode: codex_protocol::config_types::ModeKind::Default, + settings: codex_protocol::config_types::Settings { + model: session_model, + reasoning_effort: None, + developer_instructions: None, + }, + }), + ..Default::default() + }, + }) + .await?; + + let approval = expect_exec_approval(&test, &command).await; + test.codex + .submit(Op::ExecApproval { + id: approval.effective_approval_id(), + turn_id: None, + decision: ReviewDecision::Approved, + }) + .await?; + wait_for_completion_without_approval(&test).await; + + let result = parse_result(&results.single_request().function_call_output(call_id)); + assert_eq!( + result.exit_code.unwrap_or(0), + 0, + "approved unified exec zsh-fork command should complete: {}", + result.stdout + ); + assert!( + outside_path.exists(), + "expected parent approval to let the intercepted touch run unsandboxed; output: {}", + result.stdout + ); + + Ok(()) +} + #[tokio::test(flavor = "current_thread")] #[cfg(unix)] async fn invalid_requested_prefix_rule_falls_back_for_compound_command() -> Result<()> {