From 9aa8c51741c7bd9ef7ff540449456cc8a8131ddc Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 28 May 2026 15:54:02 -0700 Subject: [PATCH 1/4] feat: gate unified exec zsh fork composition --- codex-rs/core/config.schema.json | 6 ++++ codex-rs/core/src/session/mod.rs | 1 - codex-rs/core/src/session/review.rs | 3 +- codex-rs/core/src/session/turn_context.rs | 4 +-- codex-rs/core/src/tools/spec_plan_tests.rs | 40 ++++++++++++++++++++++ codex-rs/features/src/lib.rs | 8 +++++ codex-rs/features/src/tests.rs | 10 ++++++ codex-rs/tools/src/lib.rs | 1 + codex-rs/tools/src/tool_config.rs | 15 ++++++-- codex-rs/tools/src/tool_config_tests.rs | 26 ++++++++++++-- 10 files changed, 103 insertions(+), 11 deletions(-) diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 1dd6bda8a4..38b6344319 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -614,6 +614,9 @@ "unified_exec": { "type": "boolean" }, + "unified_exec_zsh_fork": { + "type": "boolean" + }, "use_legacy_landlock": { "type": "boolean" }, @@ -4708,6 +4711,9 @@ "unified_exec": { "type": "boolean" }, + "unified_exec_zsh_fork": { + "type": "boolean" + }, "use_legacy_landlock": { "type": "boolean" }, diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 8c535cd728..f242b2d918 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -362,7 +362,6 @@ use codex_protocol::protocol::WarningEvent; use codex_protocol::user_input::UserInput; use codex_tools::ToolEnvironmentMode; use codex_tools::UnifiedExecShellMode; -use codex_tools::shell_command_backend_for_features; use codex_utils_absolute_path::AbsolutePathBuf; #[cfg(test)] use codex_utils_stream_parser::ProposedPlanSegment; diff --git a/codex-rs/core/src/session/review.rs b/codex-rs/core/src/session/review.rs index 75b7539090..828760dee2 100644 --- a/codex-rs/core/src/session/review.rs +++ b/codex-rs/core/src/session/review.rs @@ -30,9 +30,8 @@ pub(super) async fn spawn_review_thread( .models_manager .list_models(RefreshStrategy::OnlineIfUncached) .await; - let shell_command_backend = shell_command_backend_for_features(review_features.get()); let unified_exec_shell_mode = UnifiedExecShellMode::for_session( - shell_command_backend, + codex_tools::unified_exec_zsh_fork_for_features(review_features.get()), crate::tools::tool_user_shell_type(sess.services.user_shell.as_ref()), sess.services.shell_zsh_path.as_ref(), sess.services.main_execve_wrapper_exe.as_ref(), diff --git a/codex-rs/core/src/session/turn_context.rs b/codex-rs/core/src/session/turn_context.rs index dba5d16a75..4df7df74c6 100644 --- a/codex-rs/core/src/session/turn_context.rs +++ b/codex-rs/core/src/session/turn_context.rs @@ -465,10 +465,8 @@ impl Session { let provider_for_context = create_model_provider(provider, auth_manager); let session_telemetry_for_context = session_telemetry; let available_models = models_manager.try_list_models().unwrap_or_default(); - let shell_command_backend = - shell_command_backend_for_features(per_turn_config.features.get()); let unified_exec_shell_mode = UnifiedExecShellMode::for_session( - shell_command_backend, + codex_tools::unified_exec_zsh_fork_for_features(per_turn_config.features.get()), crate::tools::tool_user_shell_type(user_shell), shell_zsh_path, main_execve_wrapper_exe, diff --git a/codex-rs/core/src/tools/spec_plan_tests.rs b/codex-rs/core/src/tools/spec_plan_tests.rs index a274f934c4..d5c027d4fa 100644 --- a/codex-rs/core/src/tools/spec_plan_tests.rs +++ b/codex-rs/core/src/tools/spec_plan_tests.rs @@ -382,6 +382,46 @@ async fn shell_family_registers_visible_unified_exec_and_hidden_legacy_shell() { assert_eq!(plan.exposure("shell_command"), ToolExposure::Hidden); } +#[tokio::test] +async fn shell_zsh_fork_stays_standalone_until_unified_exec_composition_is_enabled() { + let standalone = probe(|turn| { + set_features(turn, &[Feature::ShellTool, Feature::UnifiedExec]); + set_feature(turn, Feature::ShellZshFork, /*enabled*/ true); + set_feature(turn, Feature::UnifiedExecZshFork, /*enabled*/ false); + turn.model_info.shell_type = ConfigShellToolType::ShellCommand; + }) + .await; + + standalone.assert_visible_contains(&["shell_command"]); + standalone.assert_visible_lacks(&["exec_command", "write_stdin"]); + standalone.assert_registered_contains(&["shell_command"]); + standalone.assert_registered_lacks(&["exec_command", "write_stdin"]); + + let composed = probe(|turn| { + set_features( + turn, + &[ + Feature::ShellTool, + Feature::UnifiedExec, + Feature::ShellZshFork, + Feature::UnifiedExecZshFork, + ], + ); + turn.model_info.shell_type = ConfigShellToolType::ShellCommand; + }) + .await; + + if codex_utils_pty::conpty_supported() { + composed.assert_visible_contains(&["exec_command", "write_stdin"]); + composed.assert_visible_lacks(&["shell_command"]); + composed.assert_registered_contains(&["exec_command", "write_stdin", "shell_command"]); + assert_eq!(composed.exposure("shell_command"), ToolExposure::Hidden); + } else { + composed.assert_visible_contains(&["shell_command"]); + composed.assert_visible_lacks(&["exec_command", "write_stdin"]); + } +} + #[tokio::test] async fn environment_count_controls_environment_backed_tools() { let no_environment = probe(|turn| { diff --git a/codex-rs/features/src/lib.rs b/codex-rs/features/src/lib.rs index 116db0a5b5..65fa160cc4 100644 --- a/codex-rs/features/src/lib.rs +++ b/codex-rs/features/src/lib.rs @@ -90,6 +90,8 @@ pub enum Feature { UnifiedExec, /// Route shell tool execution through the zsh exec bridge. ShellZshFork, + /// Route unified exec through the zsh exec bridge when both are enabled. + UnifiedExecZshFork, /// Reflow transcript scrollback when the terminal is resized. TerminalResizeReflow, /// Stream structured progress while apply_patch input is being generated. @@ -739,6 +741,12 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::UnderDevelopment, default_enabled: false, }, + FeatureSpec { + id: Feature::UnifiedExecZshFork, + key: "unified_exec_zsh_fork", + stage: Stage::UnderDevelopment, + default_enabled: false, + }, FeatureSpec { id: Feature::ShellSnapshot, key: "shell_snapshot", diff --git a/codex-rs/features/src/tests.rs b/codex-rs/features/src/tests.rs index 5d7087e90b..718d76688b 100644 --- a/codex-rs/features/src/tests.rs +++ b/codex-rs/features/src/tests.rs @@ -136,6 +136,16 @@ fn request_permissions_tool_is_under_development() { assert_eq!(Feature::RequestPermissionsTool.default_enabled(), false); } +#[test] +fn unified_exec_zsh_fork_is_under_development() { + assert_eq!(Feature::UnifiedExecZshFork.stage(), Stage::UnderDevelopment); + assert_eq!(Feature::UnifiedExecZshFork.default_enabled(), false); + assert_eq!( + feature_for_key("unified_exec_zsh_fork"), + Some(Feature::UnifiedExecZshFork) + ); +} + #[test] fn remote_compaction_v2_is_under_development() { assert_eq!(Feature::RemoteCompactionV2.stage(), Stage::UnderDevelopment); diff --git a/codex-rs/tools/src/lib.rs b/codex-rs/tools/src/lib.rs index 91fa5830a3..a50708e7c5 100644 --- a/codex-rs/tools/src/lib.rs +++ b/codex-rs/tools/src/lib.rs @@ -75,6 +75,7 @@ pub use tool_config::ZshForkConfig; pub use tool_config::request_user_input_available_modes; pub use tool_config::shell_command_backend_for_features; pub use tool_config::shell_type_for_model_and_features; +pub use tool_config::unified_exec_zsh_fork_for_features; pub use tool_definition::ToolDefinition; pub use tool_discovery::DiscoverablePluginInfo; pub use tool_discovery::DiscoverableTool; diff --git a/codex-rs/tools/src/tool_config.rs b/codex-rs/tools/src/tool_config.rs index 3eaa73f189..08371d1570 100644 --- a/codex-rs/tools/src/tool_config.rs +++ b/codex-rs/tools/src/tool_config.rs @@ -41,6 +41,13 @@ pub fn shell_command_backend_for_features(features: &Features) -> ShellCommandBa } } +pub fn unified_exec_zsh_fork_for_features(features: &Features) -> bool { + features.enabled(Feature::ShellTool) + && features.enabled(Feature::UnifiedExec) + && features.enabled(Feature::ShellZshFork) + && features.enabled(Feature::UnifiedExecZshFork) +} + pub fn shell_type_for_model_and_features( model_info: &ModelInfo, features: &Features, @@ -58,7 +65,9 @@ pub fn shell_type_for_model_and_features( if !features.enabled(Feature::ShellTool) { ConfigShellToolType::Disabled - } else if features.enabled(Feature::ShellZshFork) { + } else if features.enabled(Feature::ShellZshFork) + && !unified_exec_zsh_fork_for_features(features) + { ConfigShellToolType::ShellCommand } else if unified_exec_enabled { if codex_utils_pty::conpty_supported() { @@ -85,13 +94,13 @@ pub struct ZshForkConfig { impl UnifiedExecShellMode { pub fn for_session( - shell_command_backend: ShellCommandBackendConfig, + use_zsh_fork: bool, user_shell_type: ToolUserShellType, shell_zsh_path: Option<&PathBuf>, main_execve_wrapper_exe: Option<&PathBuf>, ) -> Self { if cfg!(unix) - && shell_command_backend == ShellCommandBackendConfig::ZshFork + && use_zsh_fork && matches!(user_shell_type, ToolUserShellType::Zsh) && let (Some(shell_zsh_path), Some(main_execve_wrapper_exe)) = (shell_zsh_path, main_execve_wrapper_exe) diff --git a/codex-rs/tools/src/tool_config_tests.rs b/codex-rs/tools/src/tool_config_tests.rs index 033bf07b10..daa1282adb 100644 --- a/codex-rs/tools/src/tool_config_tests.rs +++ b/codex-rs/tools/src/tool_config_tests.rs @@ -81,6 +81,12 @@ fn shell_type_is_derived_from_model_and_feature_gates() { ConfigShellToolType::ShellCommand ); + features.enable(Feature::UnifiedExecZshFork); + assert_eq!( + shell_type_for_model_and_features(&model, &features), + expected_unified_exec + ); + features.disable(Feature::ShellTool); assert_eq!( shell_type_for_model_and_features(&model, &features), @@ -109,6 +115,22 @@ fn shell_command_backend_requires_both_shell_tool_and_zsh_fork() { ); } +#[test] +fn unified_exec_zsh_fork_requires_all_feature_gates() { + let mut features = shell_features(); + assert_eq!(unified_exec_zsh_fork_for_features(&features), false); + + features.enable(Feature::UnifiedExec); + features.enable(Feature::ShellZshFork); + assert_eq!(unified_exec_zsh_fork_for_features(&features), false); + + features.enable(Feature::UnifiedExecZshFork); + assert_eq!(unified_exec_zsh_fork_for_features(&features), true); + + features.disable(Feature::ShellTool); + assert_eq!(unified_exec_zsh_fork_for_features(&features), false); +} + #[test] fn request_user_input_modes_follow_default_mode_feature() { let mut features = Features::with_defaults(); @@ -131,7 +153,7 @@ fn unified_exec_shell_mode_uses_zsh_fork_only_when_all_inputs_match() { let shell = exe.clone(); let mode = UnifiedExecShellMode::for_session( - ShellCommandBackendConfig::ZshFork, + /*use_zsh_fork*/ true, ToolUserShellType::Zsh, Some(&shell), Some(&exe), @@ -144,7 +166,7 @@ fn unified_exec_shell_mode_uses_zsh_fork_only_when_all_inputs_match() { assert_eq!( UnifiedExecShellMode::for_session( - ShellCommandBackendConfig::Classic, + /*use_zsh_fork*/ false, ToolUserShellType::Zsh, Some(&shell), Some(&exe), From 9ecac8b2182b1edcafed2636971639db6981e41c Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 28 May 2026 15:54:02 -0700 Subject: [PATCH 2/4] refactor: hide shell override for zsh fork unified exec --- .../core/src/tools/handlers/shell_spec.rs | 19 +++++++---- .../src/tools/handlers/shell_spec_tests.rs | 22 ++++++++++++ .../handlers/unified_exec/exec_command.rs | 3 ++ codex-rs/core/src/tools/spec_plan.rs | 5 +++ codex-rs/core/src/tools/spec_plan_tests.rs | 34 +++++++++++++++++++ 5 files changed, 76 insertions(+), 7 deletions(-) diff --git a/codex-rs/core/src/tools/handlers/shell_spec.rs b/codex-rs/core/src/tools/handlers/shell_spec.rs index 43b78e3afe..7393eeee59 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 4774815fb2..1d1349ccb4 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 { @@ -89,6 +96,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/exec_command.rs b/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs index 83236881f3..72ac23691a 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 @@ -44,6 +44,7 @@ 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 +58,7 @@ impl Default for ExecCommandHandler { allow_login_shell: false, exec_permission_approvals_enabled: false, include_environment_id: false, + include_shell_parameter: true, }, } } @@ -81,6 +83,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, ) } diff --git a/codex-rs/core/src/tools/spec_plan.rs b/codex-rs/core/src/tools/spec_plan.rs index bb7baf4bd8..50935ccd70 100644 --- a/codex-rs/core/src/tools/spec_plan.rs +++ b/codex-rs/core/src/tools/spec_plan.rs @@ -72,6 +72,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; @@ -566,6 +567,10 @@ fn add_shell_tools(context: &CoreToolPlanContext<'_>, planned_tools: &mut Planne allow_login_shell, exec_permission_approvals_enabled, include_environment_id, + include_shell_parameter: !matches!( + &turn_context.unified_exec_shell_mode, + UnifiedExecShellMode::ZshFork(_) + ), })); planned_tools.add(WriteStdinHandler); diff --git a/codex-rs/core/src/tools/spec_plan_tests.rs b/codex-rs/core/src/tools/spec_plan_tests.rs index d5c027d4fa..af2f3c9162 100644 --- a/codex-rs/core/src/tools/spec_plan_tests.rs +++ b/codex-rs/core/src/tools/spec_plan_tests.rs @@ -380,6 +380,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] @@ -422,6 +423,39 @@ 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 exe = codex_utils_absolute_path::AbsolutePathBuf::try_from( + std::env::current_exe().expect("current exe path"), + ) + .expect("current exe should be absolute"); + + let plan = probe(|turn| { + set_features( + turn, + &[ + Feature::ShellTool, + Feature::UnifiedExec, + Feature::ShellZshFork, + Feature::UnifiedExecZshFork, + ], + ); + turn.unified_exec_shell_mode = + codex_tools::UnifiedExecShellMode::ZshFork(codex_tools::ZshForkConfig { + shell_zsh_path: exe.clone(), + main_execve_wrapper_exe: exe, + }); + }) + .await; + + plan.assert_visible_contains(&["exec_command", "write_stdin"]); + assert!(!has_parameter(plan.visible_spec("exec_command"), "shell")); +} + #[tokio::test] async fn environment_count_controls_environment_backed_tools() { let no_environment = probe(|turn| { From ef25cd8a8b0b8477e9df351cedc79c3a11dcd4db Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 28 May 2026 16:02:52 -0700 Subject: [PATCH 3/4] fix: sandbox zsh fork unified exec trampoline --- .../tools/runtimes/shell/unix_escalation.rs | 4 +- .../runtimes/shell/unix_escalation_tests.rs | 97 +++++++++++ .../core/src/tools/runtimes/unified_exec.rs | 161 +++++++++++++++++- 3 files changed, 252 insertions(+), 10 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 5fbf4ea33d..ef5418c438 100644 --- a/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs +++ b/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs @@ -617,7 +617,7 @@ impl EscalationPolicy for CoreShellActionProvider { let decision_driven_by_policy = Self::decision_driven_by_policy(&evaluation.matched_rules, evaluation.decision); let needs_escalation = - self.sandbox_permissions.requires_escalated_permissions() || decision_driven_by_policy; + self.sandbox_permissions.requests_sandbox_override() || decision_driven_by_policy; let decision_source = if decision_driven_by_policy { DecisionSource::PrefixRule @@ -844,7 +844,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 43d8e46952..05f54947c7 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; @@ -33,9 +37,11 @@ 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; @@ -318,6 +324,97 @@ 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 = PermissionProfile::workspace_write(); + 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 01054a0369..1285755eb2 100644 --- a/codex-rs/core/src/tools/runtimes/unified_exec.rs +++ b/codex-rs/core/src/tools/runtimes/unified_exec.rs @@ -45,6 +45,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; @@ -117,6 +118,61 @@ impl<'a> UnifiedExecRuntime<'a> { shell_mode, } } + + fn first_attempt_sandbox_permissions(&self, req: &UnifiedExecRequest) -> SandboxPermissions { + if matches!(&self.shell_mode, UnifiedExecShellMode::ZshFork(_)) { + 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 + { + 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 + { + None + } else { + req.additional_permissions.clone() + } + } } impl Sandboxable for UnifiedExecRuntime<'_> { @@ -202,7 +258,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( @@ -216,7 +272,7 @@ impl Approvable for UnifiedExecRuntime<'_> { } fn sandbox_permissions(&self, req: &UnifiedExecRequest) -> SandboxPermissions { - req.sandbox_permissions + self.first_attempt_sandbox_permissions(req) } } @@ -257,9 +313,12 @@ impl<'a> ToolRuntime for UnifiedExecRunt ) -> Result { let base_command = &req.command; let session_shell = ctx.session.user_shell(); - 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 launch_sandbox_permissions = self.launch_sandbox_permissions(req, attempt); + 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); } @@ -301,9 +360,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) @@ -387,6 +450,7 @@ mod tests { use crate::exec::DEFAULT_EXEC_COMMAND_TIMEOUT_MS; use crate::tools::sandboxing::ToolRuntime; use codex_exec_server::Environment; + use codex_tools::ZshForkConfig; use std::time::Duration; use tempfile::tempdir; @@ -448,4 +512,85 @@ 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_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 c57e17f3c48410177f2171433ce46504259bfd7b Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 28 May 2026 16:06:08 -0700 Subject: [PATCH 4/4] fix: honor parent approvals for intercepted execs --- .../tools/runtimes/shell/unix_escalation.rs | 38 +++++++++- .../runtimes/shell/unix_escalation_tests.rs | 75 +++++++++++++++++++ 2 files changed, 112 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 ef5418c438..0293b86080 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; @@ -98,6 +99,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<'_>, @@ -217,6 +231,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(), }; @@ -293,6 +312,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(), }; @@ -325,6 +349,7 @@ struct CoreShellActionProvider { sandbox_permissions: SandboxPermissions, approval_sandbox_permissions: SandboxPermissions, prompt_permissions: Option, + parent_sandbox_override_approved: bool, stopwatch: Stopwatch, } @@ -616,6 +641,17 @@ impl EscalationPolicy for CoreShellActionProvider { // fallback function. let decision_driven_by_policy = Self::decision_driven_by_policy(&evaluation.matched_rules, evaluation.decision); + // 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.requests_sandbox_override() || decision_driven_by_policy; @@ -633,7 +669,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 05f54947c7..8b6783e5ad 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 @@ -135,6 +135,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!( @@ -394,6 +430,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)), }; @@ -415,6 +452,43 @@ 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(flavor = "current_thread")] async fn execve_permission_request_hook_short_circuits_prompt() -> anyhow::Result<()> { let (session, mut turn_context) = make_session_and_context().await; @@ -527,6 +601,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)), };