From 61500eed405fbc108df74ff49ede726051c7aca6 Mon Sep 17 00:00:00 2001 From: starr-openai Date: Wed, 8 Apr 2026 14:14:47 -0700 Subject: [PATCH] codex: centralize sandbox spawn env preparation Prepare sandbox env inside the sandbox transform result so core and exec-server do not have to mutate the request at their spawn boundaries. Co-authored-by: Codex --- codex-rs/core/src/exec.rs | 30 +----- codex-rs/core/src/exec_tests.rs | 3 +- codex-rs/core/src/sandboxing/mod.rs | 5 +- codex-rs/core/src/tools/js_repl/mod.rs | 13 +-- .../tools/runtimes/shell/unix_escalation.rs | 9 +- .../core/src/tools/runtimes/unified_exec.rs | 5 +- codex-rs/core/src/tools/sandboxing.rs | 11 ++- codex-rs/core/src/tools/spec_tests.rs | 1 - codex-rs/exec-server/README.md | 2 +- .../exec-server/src/bin/codex-exec-server.rs | 31 ++++-- codex-rs/exec-server/src/environment.rs | 39 +++++++- codex-rs/exec-server/src/lib.rs | 1 - codex-rs/exec-server/src/local_process.rs | 61 +++++------- codex-rs/exec-server/src/server.rs | 8 +- codex-rs/sandboxing/src/manager.rs | 26 +---- codex-rs/sandboxing/src/manager_tests.rs | 98 +++++++++---------- codex-rs/sandboxing/src/seatbelt_tests.rs | 3 +- .../tools/src/tool_registry_plan_tests.rs | 1 - codex-rs/tui/src/lib.rs | 5 +- 19 files changed, 166 insertions(+), 186 deletions(-) diff --git a/codex-rs/core/src/exec.rs b/codex-rs/core/src/exec.rs index 464f9215ac..e7907cacec 100644 --- a/codex-rs/core/src/exec.rs +++ b/codex-rs/core/src/exec.rs @@ -40,7 +40,6 @@ use codex_protocol::protocol::ExecOutputStream; use codex_protocol::protocol::SandboxPolicy; use codex_sandboxing::SandboxCommand; use codex_sandboxing::SandboxLaunchConfig; -use codex_sandboxing::SandboxManager; use codex_sandboxing::SandboxType; use codex_sandboxing::SandboxablePreference; use codex_utils_absolute_path::AbsolutePathBuf; @@ -115,21 +114,6 @@ pub enum ExecCapturePolicy { FullBuffer, } -fn select_process_exec_tool_sandbox_type( - file_system_sandbox_policy: &FileSystemSandboxPolicy, - network_sandbox_policy: NetworkSandboxPolicy, - windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel, - enforce_managed_network: bool, -) -> SandboxType { - SandboxManager::new().select_initial( - file_system_sandbox_policy, - network_sandbox_policy, - SandboxablePreference::Auto, - windows_sandbox_level, - enforce_managed_network, - ) -} - /// Mechanism to terminate an exec invocation before it finishes naturally. #[derive(Clone, Debug)] pub enum ExecExpiration { @@ -238,15 +222,7 @@ pub fn build_exec_request( codex_linux_sandbox_exe: &Option, use_legacy_landlock: bool, ) -> Result { - let windows_sandbox_level = params.windows_sandbox_level; let enforce_managed_network = params.network.is_some(); - let sandbox_type = select_process_exec_tool_sandbox_type( - file_system_sandbox_policy, - network_sandbox_policy, - windows_sandbox_level, - enforce_managed_network, - ); - tracing::debug!("Sandbox type: {sandbox_type:?}"); let ExecParams { command, @@ -271,7 +247,6 @@ pub fn build_exec_request( )) })?; - let manager = SandboxManager::new(); let command = SandboxCommand { program: program.clone().into(), args: args.to_vec(), @@ -284,7 +259,7 @@ pub fn build_exec_request( capture_policy, }; let sandbox_launch_config = SandboxLaunchConfig { - sandbox_preference: SandboxablePreference::from_selected_sandbox(sandbox_type), + sandbox_preference: SandboxablePreference::Auto, policy: sandbox_policy.clone(), file_system_policy: file_system_sandbox_policy.clone(), network_policy: network_sandbox_policy, @@ -295,7 +270,7 @@ pub fn build_exec_request( windows_sandbox_private_desktop, use_legacy_landlock, }; - let mut exec_req = manager + let mut exec_req = codex_sandboxing::SandboxManager::new() .transform( command, &sandbox_launch_config, @@ -304,6 +279,7 @@ pub fn build_exec_request( ) .map(|request| ExecRequest::from_sandbox_exec_request(request, options)) .map_err(CodexErr::from)?; + tracing::debug!("Sandbox type: {:?}", exec_req.sandbox); exec_req.windows_restricted_token_filesystem_overlay = resolve_windows_restricted_token_filesystem_overlay( exec_req.sandbox, diff --git a/codex-rs/core/src/exec_tests.rs b/codex-rs/core/src/exec_tests.rs index 3cde807c0f..86a757b66a 100644 --- a/codex-rs/core/src/exec_tests.rs +++ b/codex-rs/core/src/exec_tests.rs @@ -688,9 +688,10 @@ fn process_exec_tool_call_uses_platform_sandbox_for_network_only_restrictions() .unwrap_or(SandboxType::None); assert_eq!( - select_process_exec_tool_sandbox_type( + codex_sandboxing::SandboxManager::new().select_initial( &FileSystemSandboxPolicy::unrestricted(), NetworkSandboxPolicy::Restricted, + codex_sandboxing::SandboxablePreference::Auto, codex_protocol::config_types::WindowsSandboxLevel::Disabled, /*enforce_managed_network*/ false, ), diff --git a/codex-rs/core/src/sandboxing/mod.rs b/codex-rs/core/src/sandboxing/mod.rs index 76845c9f3f..83578bfbb5 100644 --- a/codex-rs/core/src/sandboxing/mod.rs +++ b/codex-rs/core/src/sandboxing/mod.rs @@ -85,10 +85,11 @@ impl ExecRequest { } pub(crate) fn from_sandbox_exec_request( - mut request: SandboxExecRequest, + request: SandboxExecRequest, options: ExecOptions, ) -> Self { - request.prepare_env_for_spawn(); + // SandboxManager::transform prepares spawn env (`CODEX_SANDBOX*`). + // This adapter only attaches core-owned exec options. let SandboxExecRequest { command, cwd, diff --git a/codex-rs/core/src/tools/js_repl/mod.rs b/codex-rs/core/src/tools/js_repl/mod.rs index d4b509954b..1894855eb8 100644 --- a/codex-rs/core/src/tools/js_repl/mod.rs +++ b/codex-rs/core/src/tools/js_repl/mod.rs @@ -43,7 +43,6 @@ use crate::tools::ToolRouter; use crate::tools::context::SharedTurnDiffTracker; use codex_sandboxing::SandboxCommand; use codex_sandboxing::SandboxLaunchConfig; -use codex_sandboxing::SandboxManager; use codex_sandboxing::SandboxablePreference; use codex_tools::ToolSpec; use codex_utils_output_truncation::TruncationPolicy; @@ -1030,20 +1029,12 @@ impl JsReplManager { ); } - let sandbox = SandboxManager::new(); let has_managed_network_requirements = turn .config .config_layer_stack .requirements_toml() .network .is_some(); - let sandbox_type = sandbox.select_initial( - &turn.file_system_sandbox_policy, - turn.network_sandbox_policy, - SandboxablePreference::Auto, - turn.windows_sandbox_level, - has_managed_network_requirements, - ); let command = SandboxCommand { program: node_path.into_os_string(), args: vec![ @@ -1059,7 +1050,7 @@ impl JsReplManager { capture_policy: ExecCapturePolicy::ShellTool, }; let sandbox_launch_config = SandboxLaunchConfig { - sandbox_preference: SandboxablePreference::from_selected_sandbox(sandbox_type), + sandbox_preference: SandboxablePreference::Auto, policy: turn.sandbox_policy.get().clone(), file_system_policy: turn.file_system_sandbox_policy.clone(), network_policy: turn.network_sandbox_policy, @@ -1073,7 +1064,7 @@ impl JsReplManager { .windows_sandbox_private_desktop, use_legacy_landlock: turn.features.use_legacy_landlock(), }; - let exec_env = sandbox + let exec_env = codex_sandboxing::SandboxManager::new() .transform( command, &sandbox_launch_config, 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 5d1542362d..cbf0066b8f 100644 --- a/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs +++ b/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs @@ -817,13 +817,6 @@ impl CoreShellCommandExecutor { .split_first() .ok_or_else(|| anyhow::anyhow!("prepared command must not be empty"))?; let sandbox_manager = SandboxManager::new(); - let sandbox = sandbox_manager.select_initial( - file_system_sandbox_policy, - network_sandbox_policy, - SandboxablePreference::Auto, - self.windows_sandbox_level, - self.network.is_some(), - ); let command = SandboxCommand { program: program.clone().into(), args: args.to_vec(), @@ -836,7 +829,7 @@ impl CoreShellCommandExecutor { capture_policy: ExecCapturePolicy::ShellTool, }; let sandbox_launch_config = SandboxLaunchConfig { - sandbox_preference: SandboxablePreference::from_selected_sandbox(sandbox), + sandbox_preference: SandboxablePreference::Auto, policy: sandbox_policy.clone(), file_system_policy: file_system_sandbox_policy.clone(), network_policy: network_sandbox_policy, diff --git a/codex-rs/core/src/tools/runtimes/unified_exec.rs b/codex-rs/core/src/tools/runtimes/unified_exec.rs index 1834ed40b8..87d1d93c83 100644 --- a/codex-rs/core/src/tools/runtimes/unified_exec.rs +++ b/codex-rs/core/src/tools/runtimes/unified_exec.rs @@ -88,7 +88,7 @@ fn build_remote_exec_sandbox_config( additional_permissions: Option, ) -> SandboxLaunchConfig { SandboxLaunchConfig { - sandbox_preference: SandboxablePreference::from_selected_sandbox(attempt.sandbox), + sandbox_preference: attempt.sandbox_preference(), policy: attempt.policy.clone(), file_system_policy: attempt.file_system_policy.clone(), network_policy: attempt.network_policy, @@ -244,6 +244,9 @@ impl<'a> ToolRuntime for UnifiedExecRunt .as_ref() .filter(|environment| environment.exec_server_url().is_some()) { + // Let the exec-server host perform sandbox transformation for its platform. + // The local fallback below still transforms in core, where the session's + // linux-sandbox helper path and zsh-fork spawn lifecycle are available. if let UnifiedExecShellMode::ZshFork(_) = &self.shell_mode { return Err(ToolError::Rejected( "unified_exec zsh-fork is not supported when exec_server_url is configured" diff --git a/codex-rs/core/src/tools/sandboxing.rs b/codex-rs/core/src/tools/sandboxing.rs index ce992c5595..530acb50e1 100644 --- a/codex-rs/core/src/tools/sandboxing.rs +++ b/codex-rs/core/src/tools/sandboxing.rs @@ -332,6 +332,15 @@ pub(crate) struct SandboxAttempt<'a> { } impl<'a> SandboxAttempt<'a> { + pub(crate) fn sandbox_preference(&self) -> SandboxablePreference { + match self.sandbox { + SandboxType::None => SandboxablePreference::Forbid, + SandboxType::MacosSeatbelt + | SandboxType::LinuxSeccomp + | SandboxType::WindowsRestrictedToken => SandboxablePreference::Require, + } + } + pub fn env_for( &self, command: SandboxCommand, @@ -339,7 +348,7 @@ impl<'a> SandboxAttempt<'a> { network: Option<&NetworkProxy>, ) -> Result { let sandbox_launch_config = SandboxLaunchConfig { - sandbox_preference: SandboxablePreference::from_selected_sandbox(self.sandbox), + sandbox_preference: self.sandbox_preference(), policy: self.policy.clone(), file_system_policy: self.file_system_policy.clone(), network_policy: self.network_policy, diff --git a/codex-rs/core/src/tools/spec_tests.rs b/codex-rs/core/src/tools/spec_tests.rs index 2d49a39944..2a2c11a917 100644 --- a/codex-rs/core/src/tools/spec_tests.rs +++ b/codex-rs/core/src/tools/spec_tests.rs @@ -175,7 +175,6 @@ fn multi_agent_v2_tools_config() -> ToolsConfig { session_source: SessionSource::Cli, sandbox_policy: &SandboxPolicy::DangerFullAccess, windows_sandbox_level: WindowsSandboxLevel::Disabled, - image_generation_tool_auth_allowed: true, }) } diff --git a/codex-rs/exec-server/README.md b/codex-rs/exec-server/README.md index 3c71dfa19a..baab977d55 100644 --- a/codex-rs/exec-server/README.md +++ b/codex-rs/exec-server/README.md @@ -242,7 +242,7 @@ The crate exports: - `RemoteExecServerConnectArgs` - protocol structs `InitializeParams` and `InitializeResponse` - `DEFAULT_LISTEN_URL` and `ExecServerListenUrlParseError` -- `run_main_with_listen_url()` +- `run_main_with_runtime()` - `run_main()` for embedding the websocket server in a binary ## Example session diff --git a/codex-rs/exec-server/src/bin/codex-exec-server.rs b/codex-rs/exec-server/src/bin/codex-exec-server.rs index cbf34abc47..adcae8dba6 100644 --- a/codex-rs/exec-server/src/bin/codex-exec-server.rs +++ b/codex-rs/exec-server/src/bin/codex-exec-server.rs @@ -1,6 +1,6 @@ use clap::Parser; -#[cfg(target_os = "linux")] +use std::future::Future; use std::path::PathBuf; #[cfg(target_os = "linux")] @@ -18,6 +18,26 @@ struct ExecServerArgs { } fn main() -> anyhow::Result<()> { + linux_sandbox_arg0_dispatch_or_else(run_main) +} + +async fn run_main(codex_linux_sandbox_exe: Option) -> anyhow::Result<()> { + let args = ExecServerArgs::parse(); + let runtime = codex_exec_server::ExecServerRuntimeConfig::new(codex_linux_sandbox_exe); + codex_exec_server::run_main_with_runtime(&args.listen, runtime) + .await + .map_err(|err| anyhow::Error::msg(err.to_string()))?; + Ok(()) +} + +// Keep this standalone-server wrapper local instead of using +// codex_arg0::arg0_dispatch_or_else: codex-arg0 owns CLI aliases such as +// apply_patch, and depends on codex-exec-server to apply patches. +fn linux_sandbox_arg0_dispatch_or_else(main_fn: F) -> anyhow::Result<()> +where + F: FnOnce(Option) -> Fut, + Fut: Future>, +{ dispatch_linux_sandbox_arg0(); let _linux_sandbox_alias = LinuxSandboxAlias::create(); @@ -31,14 +51,7 @@ fn main() -> anyhow::Result<()> { let runtime = tokio::runtime::Builder::new_multi_thread() .enable_all() .build()?; - runtime.block_on(async move { - let args = ExecServerArgs::parse(); - let runtime = codex_exec_server::ExecServerRuntimeConfig::new(codex_linux_sandbox_exe); - codex_exec_server::run_main_with_runtime(&args.listen, runtime) - .await - .map_err(|err| anyhow::Error::msg(err.to_string()))?; - Ok(()) - }) + runtime.block_on(main_fn(codex_linux_sandbox_exe)) } #[cfg(target_os = "linux")] diff --git a/codex-rs/exec-server/src/environment.rs b/codex-rs/exec-server/src/environment.rs index bfd7b88837..9af9926b98 100644 --- a/codex-rs/exec-server/src/environment.rs +++ b/codex-rs/exec-server/src/environment.rs @@ -4,6 +4,7 @@ use tokio::sync::OnceCell; use crate::ExecServerClient; use crate::ExecServerError; +use crate::ExecServerRuntimeConfig; use crate::RemoteExecServerConnectArgs; use crate::file_system::ExecutorFileSystem; use crate::local_file_system::LocalFileSystem; @@ -22,6 +23,7 @@ pub const CODEX_EXEC_SERVER_URL_ENV_VAR: &str = "CODEX_EXEC_SERVER_URL"; pub struct EnvironmentManager { exec_server_url: Option, disabled: bool, + runtime: ExecServerRuntimeConfig, current_environment: OnceCell>>, } @@ -34,17 +36,33 @@ impl Default for EnvironmentManager { impl EnvironmentManager { /// Builds a manager from the raw `CODEX_EXEC_SERVER_URL` value. pub fn new(exec_server_url: Option) -> Self { + Self::new_with_runtime(exec_server_url, ExecServerRuntimeConfig::detect()) + } + + /// Builds a manager from the raw `CODEX_EXEC_SERVER_URL` value and the + /// runtime resources available in this client process. + pub fn new_with_runtime( + exec_server_url: Option, + runtime: ExecServerRuntimeConfig, + ) -> Self { let (exec_server_url, disabled) = normalize_exec_server_url(exec_server_url); Self { exec_server_url, disabled, + runtime, current_environment: OnceCell::new(), } } /// Builds a manager from process environment variables. pub fn from_env() -> Self { - Self::new(std::env::var(CODEX_EXEC_SERVER_URL_ENV_VAR).ok()) + Self::from_env_with_runtime(ExecServerRuntimeConfig::detect()) + } + + /// Builds a manager from process environment variables and explicit local + /// runtime resources. + pub fn from_env_with_runtime(runtime: ExecServerRuntimeConfig) -> Self { + Self::new_with_runtime(std::env::var(CODEX_EXEC_SERVER_URL_ENV_VAR).ok(), runtime) } /// Builds a manager from the currently selected environment, or from the @@ -54,11 +72,13 @@ impl EnvironmentManager { Some(environment) => Self { exec_server_url: environment.exec_server_url().map(str::to_owned), disabled: false, + runtime: ExecServerRuntimeConfig::detect(), current_environment: OnceCell::new(), }, None => Self { exec_server_url: None, disabled: true, + runtime: ExecServerRuntimeConfig::detect(), current_environment: OnceCell::new(), }, } @@ -82,7 +102,11 @@ impl EnvironmentManager { Ok(None) } else { Ok(Some(Arc::new( - Environment::create(self.exec_server_url.clone()).await?, + Environment::create_with_runtime( + self.exec_server_url.clone(), + self.runtime.clone(), + ) + .await?, ))) } }) @@ -132,6 +156,15 @@ impl std::fmt::Debug for Environment { impl Environment { /// Builds an environment from the raw `CODEX_EXEC_SERVER_URL` value. pub async fn create(exec_server_url: Option) -> Result { + Self::create_with_runtime(exec_server_url, ExecServerRuntimeConfig::detect()).await + } + + /// Builds an environment from the raw `CODEX_EXEC_SERVER_URL` value and + /// runtime resources available when spawning local processes. + pub async fn create_with_runtime( + exec_server_url: Option, + runtime: ExecServerRuntimeConfig, + ) -> Result { let (exec_server_url, disabled) = normalize_exec_server_url(exec_server_url); if disabled { return Err(ExecServerError::Protocol( @@ -161,7 +194,7 @@ impl Environment { )); } None => { - let local_process = LocalProcess::default(); + let local_process = LocalProcess::default_with_runtime(runtime); local_process .initialize() .map_err(|err| ExecServerError::Protocol(err.message))?; diff --git a/codex-rs/exec-server/src/lib.rs b/codex-rs/exec-server/src/lib.rs index 1cd38ac0ef..42a4dad79f 100644 --- a/codex-rs/exec-server/src/lib.rs +++ b/codex-rs/exec-server/src/lib.rs @@ -66,5 +66,4 @@ pub use protocol::WriteStatus; pub use server::DEFAULT_LISTEN_URL; pub use server::ExecServerListenUrlParseError; pub use server::run_main; -pub use server::run_main_with_listen_url; pub use server::run_main_with_runtime; diff --git a/codex-rs/exec-server/src/local_process.rs b/codex-rs/exec-server/src/local_process.rs index 66b743bf8c..d123f9e8fb 100644 --- a/codex-rs/exec-server/src/local_process.rs +++ b/codex-rs/exec-server/src/local_process.rs @@ -1,6 +1,5 @@ use std::collections::HashMap; use std::collections::VecDeque; -use std::path::Path; use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::AtomicBool; @@ -11,6 +10,7 @@ use async_trait::async_trait; use codex_app_server_protocol::JSONRPCErrorError; use codex_sandboxing::SandboxCommand; use codex_sandboxing::SandboxExecRequest; +use codex_sandboxing::SandboxManager; use codex_sandboxing::SandboxType; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_pty::ExecCommandSession; @@ -123,18 +123,20 @@ struct StartedProcess { impl Default for LocalProcess { fn default() -> Self { - let (outgoing_tx, mut outgoing_rx) = - mpsc::channel::(NOTIFICATION_CHANNEL_CAPACITY); - tokio::spawn(async move { while outgoing_rx.recv().await.is_some() {} }); - Self::new(RpcNotificationSender::new(outgoing_tx)) + Self::default_with_runtime(ExecServerRuntimeConfig::detect()) } } impl LocalProcess { - pub(crate) fn new(notifications: RpcNotificationSender) -> Self { - Self::new_with_runtime(notifications, ExecServerRuntimeConfig::detect()) + pub(crate) fn default_with_runtime(runtime: ExecServerRuntimeConfig) -> Self { + let (outgoing_tx, mut outgoing_rx) = + mpsc::channel::(NOTIFICATION_CHANNEL_CAPACITY); + tokio::spawn(async move { while outgoing_rx.recv().await.is_some() {} }); + Self::new_with_runtime(RpcNotificationSender::new(outgoing_tx), runtime) } +} +impl LocalProcess { pub(crate) fn new_with_runtime( notifications: RpcNotificationSender, runtime: ExecServerRuntimeConfig, @@ -502,48 +504,33 @@ impl ExecProcess for LocalExecProcess { } } -fn build_sandbox_command( - argv: &[String], - cwd: &Path, - env: &HashMap, - additional_permissions: Option, -) -> Result { - let (program, args) = argv - .split_first() - .ok_or_else(|| invalid_params("argv must not be empty".to_string()))?; - Ok(SandboxCommand { - program: program.clone().into(), - args: args.to_vec(), - cwd: AbsolutePathBuf::try_from(cwd) - .map_err(|err| invalid_params(format!("cwd must be absolute: {err}")))?, - env: env.clone(), - additional_permissions, - }) -} - fn prepare_exec_launch( params: &ExecParams, runtime: &ExecServerRuntimeConfig, ) -> Result { - let command = build_sandbox_command( - ¶ms.argv, - params.cwd.as_path(), - ¶ms.env, - params.sandbox.additional_permissions.clone(), - )?; - let mut launch = params - .sandbox + let (program, args) = params + .argv + .split_first() + .ok_or_else(|| invalid_params("argv must not be empty".to_string()))?; + let command = SandboxCommand { + program: program.clone().into(), + args: args.to_vec(), + cwd: AbsolutePathBuf::try_from(params.cwd.as_path()) + .map_err(|err| invalid_params(format!("cwd must be absolute: {err}")))?, + env: params.env.clone(), + additional_permissions: params.sandbox.additional_permissions.clone(), + }; + SandboxManager::new() .transform( command, + ¶ms.sandbox, // TODO: Thread managed-network proxy state across exec-server so // sandbox profile generation preserves proxy-specific allowances. /*network*/ None, runtime.codex_linux_sandbox_exe.as_deref(), ) - .map_err(|err| internal_error(format!("failed to build sandbox launch: {err}")))?; - launch.prepare_env_for_spawn(); - Ok(launch) + .map_err(|err| internal_error(format!("failed to build sandbox launch: {err}"))) } impl LocalProcess { diff --git a/codex-rs/exec-server/src/server.rs b/codex-rs/exec-server/src/server.rs index 56a5871673..6ca594c60d 100644 --- a/codex-rs/exec-server/src/server.rs +++ b/codex-rs/exec-server/src/server.rs @@ -10,13 +10,7 @@ pub use transport::DEFAULT_LISTEN_URL; pub use transport::ExecServerListenUrlParseError; pub async fn run_main() -> Result<(), Box> { - run_main_with_listen_url(DEFAULT_LISTEN_URL).await -} - -pub async fn run_main_with_listen_url( - listen_url: &str, -) -> Result<(), Box> { - transport::run_transport(listen_url, crate::ExecServerRuntimeConfig::detect()).await + run_main_with_runtime(DEFAULT_LISTEN_URL, crate::ExecServerRuntimeConfig::detect()).await } pub async fn run_main_with_runtime( diff --git a/codex-rs/sandboxing/src/manager.rs b/codex-rs/sandboxing/src/manager.rs index 08460f5c2c..9042143320 100644 --- a/codex-rs/sandboxing/src/manager.rs +++ b/codex-rs/sandboxing/src/manager.rs @@ -51,17 +51,6 @@ pub enum SandboxablePreference { Forbid, } -impl SandboxablePreference { - pub fn from_selected_sandbox(sandbox: SandboxType) -> Self { - match sandbox { - SandboxType::None => Self::Forbid, - SandboxType::MacosSeatbelt - | SandboxType::LinuxSeccomp - | SandboxType::WindowsRestrictedToken => Self::Require, - } - } -} - #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SandboxLaunchConfig { @@ -92,15 +81,6 @@ impl SandboxLaunchConfig { use_legacy_landlock: false, } } - - pub fn transform( - &self, - command: SandboxCommand, - network: Option<&NetworkProxy>, - codex_linux_sandbox_exe: Option<&Path>, - ) -> Result { - SandboxManager::new().transform(command, self, network, codex_linux_sandbox_exe) - } } pub fn get_platform_sandbox(windows_sandbox_enabled: bool) -> Option { @@ -291,7 +271,7 @@ impl SandboxManager { SandboxType::WindowsRestrictedToken => (os_argv_to_strings(argv), None), }; - Ok(SandboxExecRequest { + let mut request = SandboxExecRequest { command: argv, cwd: command.cwd, env: command.env, @@ -303,7 +283,9 @@ impl SandboxManager { file_system_sandbox_policy: effective_file_system_policy, network_sandbox_policy: effective_network_policy, arg0: arg0_override, - }) + }; + request.prepare_env_for_spawn(); + Ok(request) } } diff --git a/codex-rs/sandboxing/src/manager_tests.rs b/codex-rs/sandboxing/src/manager_tests.rs index 60d2a8bfdf..1e04f67b43 100644 --- a/codex-rs/sandboxing/src/manager_tests.rs +++ b/codex-rs/sandboxing/src/manager_tests.rs @@ -21,30 +21,8 @@ use codex_utils_absolute_path::AbsolutePathBuf; use dunce::canonicalize; use pretty_assertions::assert_eq; use std::collections::HashMap; -use std::path::Path; use tempfile::TempDir; -fn test_launch_config( - cwd: &Path, - policy: SandboxPolicy, - file_system_policy: FileSystemSandboxPolicy, - network_policy: NetworkSandboxPolicy, - sandbox_preference: SandboxablePreference, -) -> SandboxLaunchConfig { - SandboxLaunchConfig { - sandbox_preference, - policy, - file_system_policy, - network_policy, - sandbox_policy_cwd: cwd.to_path_buf(), - additional_permissions: None, - enforce_managed_network: false, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - windows_sandbox_private_desktop: false, - use_legacy_landlock: false, - } -} - #[test] fn danger_full_access_defaults_to_no_sandbox_without_network_requirements() { let manager = SandboxManager::new(); @@ -106,15 +84,20 @@ fn transform_preserves_unrestricted_file_system_policy_for_restricted_network() env: HashMap::new(), additional_permissions: None, }, - &test_launch_config( - cwd.as_path(), - SandboxPolicy::ExternalSandbox { + &SandboxLaunchConfig { + sandbox_preference: SandboxablePreference::Forbid, + policy: SandboxPolicy::ExternalSandbox { network_access: NetworkAccess::Restricted, }, - FileSystemSandboxPolicy::unrestricted(), - NetworkSandboxPolicy::Restricted, - SandboxablePreference::Forbid, - ), + file_system_policy: FileSystemSandboxPolicy::unrestricted(), + network_policy: NetworkSandboxPolicy::Restricted, + sandbox_policy_cwd: cwd.as_path().to_path_buf(), + additional_permissions: None, + enforce_managed_network: false, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + windows_sandbox_private_desktop: false, + use_legacy_landlock: false, + }, /*network*/ None, /*codex_linux_sandbox_exe*/ None, ) @@ -156,15 +139,20 @@ fn transform_additional_permissions_enable_network_for_external_sandbox() { }), }), }, - &test_launch_config( - cwd.as_path(), - SandboxPolicy::ExternalSandbox { + &SandboxLaunchConfig { + sandbox_preference: SandboxablePreference::Forbid, + policy: SandboxPolicy::ExternalSandbox { network_access: NetworkAccess::Restricted, }, - FileSystemSandboxPolicy::unrestricted(), - NetworkSandboxPolicy::Restricted, - SandboxablePreference::Forbid, - ), + file_system_policy: FileSystemSandboxPolicy::unrestricted(), + network_policy: NetworkSandboxPolicy::Restricted, + sandbox_policy_cwd: cwd.as_path().to_path_buf(), + additional_permissions: None, + enforce_managed_network: false, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + windows_sandbox_private_desktop: false, + use_legacy_landlock: false, + }, /*network*/ None, /*codex_linux_sandbox_exe*/ None, ) @@ -208,13 +196,13 @@ fn transform_additional_permissions_preserves_denied_entries() { ..Default::default() }), }, - &test_launch_config( - cwd.as_path(), - SandboxPolicy::ReadOnly { + &SandboxLaunchConfig { + sandbox_preference: SandboxablePreference::Forbid, + policy: SandboxPolicy::ReadOnly { access: ReadOnlyAccess::FullAccess, network_access: false, }, - FileSystemSandboxPolicy::restricted(vec![ + file_system_policy: FileSystemSandboxPolicy::restricted(vec![ FileSystemSandboxEntry { path: FileSystemPath::Special { value: FileSystemSpecialPath::Root, @@ -228,9 +216,14 @@ fn transform_additional_permissions_preserves_denied_entries() { access: FileSystemAccessMode::None, }, ]), - NetworkSandboxPolicy::Restricted, - SandboxablePreference::Forbid, - ), + network_policy: NetworkSandboxPolicy::Restricted, + sandbox_policy_cwd: cwd.as_path().to_path_buf(), + additional_permissions: None, + enforce_managed_network: false, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + windows_sandbox_private_desktop: false, + use_legacy_landlock: false, + }, /*network*/ None, /*codex_linux_sandbox_exe*/ None, ) @@ -276,13 +269,18 @@ fn transform_linux_seccomp_request( env: HashMap::new(), additional_permissions: None, }, - &test_launch_config( - cwd.as_path(), - SandboxPolicy::DangerFullAccess, - FileSystemSandboxPolicy::unrestricted(), - NetworkSandboxPolicy::Enabled, - SandboxablePreference::Require, - ), + &SandboxLaunchConfig { + sandbox_preference: SandboxablePreference::Require, + policy: SandboxPolicy::DangerFullAccess, + file_system_policy: FileSystemSandboxPolicy::unrestricted(), + network_policy: NetworkSandboxPolicy::Enabled, + sandbox_policy_cwd: cwd.as_path().to_path_buf(), + additional_permissions: None, + enforce_managed_network: false, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + windows_sandbox_private_desktop: false, + use_legacy_landlock: false, + }, /*network*/ None, Some(codex_linux_sandbox_exe), ) diff --git a/codex-rs/sandboxing/src/seatbelt_tests.rs b/codex-rs/sandboxing/src/seatbelt_tests.rs index 88d47db75c..39dc8a927b 100644 --- a/codex-rs/sandboxing/src/seatbelt_tests.rs +++ b/codex-rs/sandboxing/src/seatbelt_tests.rs @@ -28,8 +28,7 @@ use tempfile::TempDir; fn assert_seatbelt_denied(stderr: &[u8], path: &Path) { let stderr = String::from_utf8_lossy(stderr); assert!( - (stderr.contains(&path.display().to_string()) - && stderr.contains("Operation not permitted")) + stderr.contains(&path.display().to_string()) || stderr.contains("sandbox-exec: sandbox_apply: Operation not permitted"), "unexpected stderr: {stderr}" ); diff --git a/codex-rs/tools/src/tool_registry_plan_tests.rs b/codex-rs/tools/src/tool_registry_plan_tests.rs index ffe5e3242a..7a66eaf0e4 100644 --- a/codex-rs/tools/src/tool_registry_plan_tests.rs +++ b/codex-rs/tools/src/tool_registry_plan_tests.rs @@ -1609,7 +1609,6 @@ fn code_mode_preserves_nullable_and_literal_mcp_input_shapes() { session_source: SessionSource::Cli, sandbox_policy: &SandboxPolicy::DangerFullAccess, windows_sandbox_level: WindowsSandboxLevel::Disabled, - image_generation_tool_auth_allowed: true, }); let (tools, _) = build_specs( diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index facae979f9..e2531f29cb 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -38,6 +38,7 @@ use codex_core::path_utils; use codex_core::read_session_meta_line; use codex_core::windows_sandbox::WindowsSandboxLevelExt; use codex_exec_server::EnvironmentManager; +use codex_exec_server::ExecServerRuntimeConfig; use codex_login::AuthConfig; use codex_login::default_client::set_default_client_residency_requirement; use codex_login::enforce_login_restrictions; @@ -709,7 +710,9 @@ pub async fn run_main( } }; - let environment_manager = Arc::new(EnvironmentManager::from_env()); + let environment_manager = Arc::new(EnvironmentManager::from_env_with_runtime( + ExecServerRuntimeConfig::new(arg0_paths.codex_linux_sandbox_exe.clone()), + )); let cwd = cli.cwd.clone(); let config_cwd = config_cwd_for_app_server_target(cwd.as_deref(), &app_server_target, &environment_manager)?;